package com.microservices.pms.project.controller;

import com.alibaba.fastjson2.JSONObject;
import com.microservices.common.core.utils.StringUtils;
import com.microservices.common.core.web.controller.BaseController;
import com.microservices.common.core.web.domain.AjaxResult;
import com.microservices.common.log.annotation.Log;
import com.microservices.common.log.enums.BusinessType;
import com.microservices.common.security.annotation.Logical;
import com.microservices.common.security.annotation.RequiresPermissions;
import com.microservices.pms.project.domain.PmsProjectTestsheetIssues;
import com.microservices.pms.project.domain.vo.PmsProjectIssuesSearchVo;
import com.microservices.pms.project.domain.vo.PmsProjectTestsheetIssuesBatchInputVo;
import com.microservices.pms.project.domain.vo.PmsProjectTestsheetIssuesInputVo;
import com.microservices.pms.project.service.IPmsProjectTestsheetIssuesService;
import com.microservices.pms.project.service.PmsProjectIssuesService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 测试单执行用例关联缺陷Controller
 *
 * @author microservices
 * @date 2023-11-27
 */
@Api(tags = "项目管理-测试单执行用例关联缺陷")
@RestController
@RequestMapping("/{enterpriseIdentifier}/pmsProjectTestsheetIssues")
@ApiImplicitParams({
        @ApiImplicitParam(name = "enterpriseIdentifier", value = "企业标识", paramType = "path", dataType = "String")
})
public class PmsProjectTestsheetIssuesController extends BaseController
{
    @Autowired
    private IPmsProjectTestsheetIssuesService pmsProjectTestsheetIssuesService;

    @Autowired
    private PmsProjectIssuesService pmsProjectIssuesService;

    /**
     * 查询测试单执行用例关联缺陷列表
     */
    @ApiOperation(value = "查询测试单执行用例关联缺陷列表")
    @RequiresPermissions(value = {"pms:pmsProject:show", "pms:pmsProject:showMe"}, logical = Logical.OR)
    @GetMapping("/list/{projectTestsheetCasesId}")
    public AjaxResult list(@Validated PmsProjectIssuesSearchVo pmsProjectIssuesSearchVo, @ApiParam("执行测试用例ID") @PathVariable Long projectTestsheetCasesId) {
        PmsProjectTestsheetIssues selectedIssueQuery= new PmsProjectTestsheetIssues();
        selectedIssueQuery.setProjectTestsheetCasesId(projectTestsheetCasesId);
        List<Long> selectedIds = Optional.ofNullable(pmsProjectTestsheetIssuesService.selectPmsProjectTestsheetIssuesList(selectedIssueQuery)).orElse(Collections.emptyList()).stream()
                .map(PmsProjectTestsheetIssues::getProjectIssueId).collect(Collectors.toList());
        if (selectedIds.isEmpty()) {
            return success(new ArrayList<>());
        }
        pmsProjectIssuesSearchVo.setIds(StringUtils.join(selectedIds, ","));
        JSONObject result = pmsProjectIssuesService.selectPmsProjectIssuesList(pmsProjectIssuesSearchVo);
        return success(result);
    }

    /**
     * 新增测试单执行用例关联缺陷
     */
    @ApiOperation(value = "新增测试单执行用例关联缺陷")
    @RequiresPermissions("pms:pmsProjectTestsheet:edit")
    @Log(title = "测试单执行用例关联缺陷", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody PmsProjectTestsheetIssuesInputVo issuesInputVo)
    {
        return toAjax(pmsProjectTestsheetIssuesService.insertPmsProjectTestsheetIssuesVo(issuesInputVo));
    }

    /**
     * 批量新增测试单执行用例关联缺陷
     */
    @ApiOperation(value = "批量新增测试单执行用例关联缺陷")
    @RequiresPermissions("pms:pmsProjectTestsheet:edit")
    @Log(title = "批量新增测试单执行用例关联缺陷", businessType = BusinessType.INSERT)
    @PostMapping("/batchAdd")
    public AjaxResult batchAdd(@Validated @RequestBody PmsProjectTestsheetIssuesBatchInputVo batchInputVo)
    {
        return toAjax(pmsProjectTestsheetIssuesService.batchInsertPmsProjectTestsheetIssuesVo(batchInputVo));
    }

    /**
     * 查询与执行测试用例未关联缺陷
     */
    @RequiresPermissions(value = {"pms:pmsProject:show", "pms:pmsProject:showMe"}, logical = Logical.OR)
    @GetMapping("/unlink/{projectTestsheetCasesId}")
    @ApiOperation(value = "查询与执行测试用例未关联缺陷")
    public AjaxResult getIssueUnlinks(@Validated PmsProjectIssuesSearchVo pmsProjectIssuesSearchVo,
                                      @ApiParam("执行测试用例ID") @PathVariable Long projectTestsheetCasesId,
                                      @ApiParam("0:获取所有未被任何用例关联过的缺陷（默认），1:获取所有与当前用例未关联缺陷") Integer isAll) {
        PmsProjectTestsheetIssues selectedIssueQuery= new PmsProjectTestsheetIssues();
        selectedIssueQuery.setProjectTestsheetCasesId(projectTestsheetCasesId);
        List<Long> selectedIds = Optional.ofNullable(pmsProjectTestsheetIssuesService.selectPmsProjectTestsheetIssuesList(selectedIssueQuery)).orElse(Collections.emptyList()).stream()
                .map(PmsProjectTestsheetIssues::getProjectIssueId).collect(Collectors.toList());
        if (isAll == null || isAll != 1) {
            selectedIds.addAll(pmsProjectTestsheetIssuesService.selectAllDistinctIssueId());
        }
        pmsProjectIssuesSearchVo.setExcludeIds(StringUtils.join(selectedIds, ","));
        JSONObject result = pmsProjectIssuesService.selectPmsProjectIssuesList(pmsProjectIssuesSearchVo);
        return success(result);
    }


    /**
     * 删除测试单执行用例关联缺陷
     */
    @ApiOperation(value = "删除测试单执行用例关联缺陷")
    @RequiresPermissions("pms:pmsProjectTestsheet:edit")
    @Log(title = "测试单执行用例关联缺陷", businessType = BusinessType.DELETE)
	@DeleteMapping("/{projectTestsheetCasesId}/{ids}")
    public AjaxResult remove(@ApiParam("执行测试用例ID") @PathVariable Long projectTestsheetCasesId, @ApiParam("缺陷ID集合") @PathVariable Long[] ids)
    {
        return toAjax(pmsProjectTestsheetIssuesService.deleteByProjectTestsheetCasesIdAndIssueIds(projectTestsheetCasesId, ids));
    }
}
