package org.matrix.autotest.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.matrix.database.entity.Project;
import org.matrix.database.service.IProjectService;
import org.matrix.database.vo.CommonResult;
import org.matrix.database.vo.CommonResultObj;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author mry
 * @since 2022-01-07
 */
@CrossOrigin
@RestController
@RequestMapping("/projects")
@Api(tags = "对项目project的基本操作")
public class ProjectController {

    private final IProjectService projectService;

    public ProjectController(IProjectService projectService) {
        this.projectService = projectService;
    }

    /**
     * 查询所有项目
     *
     * @return 查询到的所有项目
     */
    @ApiOperation(value = "查询所有项目")
    @GetMapping
    public ResponseEntity<CommonResultObj<List<Project>>> findAllProject() {
        List<Project> results = projectService.findAllProject();
        if (results != null && results.size() != 0) {
            return CommonResult.success(results, "查询成功");
        } else {
            return CommonResult.failed("查询失败或无数据");
        }
    }

    /**
     * 添加项目
     *
     * @param project 项目
     * @return 添加的项目
     */
    @ApiOperation(value = "添加项目")
    @PostMapping
    public ResponseEntity<CommonResultObj<Project>> insertProject(@RequestBody Project project) {
        int i = projectService.insertProject(project);
        if (i != 0) {
            return CommonResult.success(project, "添加成功");
        } else {
            return CommonResult.failed("添加失败或已存在同名项目");
        }
    }

    /**
     * 修改项目
     *
     * @param project 项目
     * @return 修改后的项目
     */
    @ApiOperation(value = "修改项目")
    @PutMapping
    public ResponseEntity<CommonResultObj<Project>> updateProject(@RequestBody Project project) {
        int i = projectService.updateProject(project);
        if (i != 0) {
            return CommonResult.success(project, "修改成功");
        } else {
            return CommonResult.failed("修改失败");
        }
    }

    /**
     * 删除项目
     *
     * @param id 项目id
     * @return 是否删除成功
     */
    @ApiOperation(value = "根据id删除项目")
    @DeleteMapping("/{id}")
    public ResponseEntity<CommonResultObj<String>> deleteProject(@PathVariable Integer id) {
        int i = projectService.deleteProject(id);
        if (i != 0) {
            return CommonResult.success("id: " + id + "已删除", "删除成功");
        } else {
            return CommonResult.failed("删除失败,或不存在需要删除的数据");
        }
    }

}

