package com.microservices.pms.project.controller;

import com.microservices.common.core.web.controller.BaseController;
import com.microservices.common.core.web.domain.AjaxResult;
import com.microservices.common.core.web.page.GenericsTableDataInfo;
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.product.domain.PmsProductModule;
import com.microservices.pms.product.domain.vo.TreeSelect;
import com.microservices.pms.product.service.IPmsProductModuleService;
import com.microservices.pms.project.domain.PmsProjectTestsheet;
import com.microservices.pms.project.domain.vo.*;
import com.microservices.pms.project.service.IPmsProjectTestsheetService;
import com.microservices.pms.utils.PmsConstants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
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.function.Predicate;

/**
 * 测试单Controller
 *
 * @author xxq
 * @date 2023-11-24
 */
@Api(tags = "项目管理-测试单")
@RestController
@RequestMapping("/{enterpriseIdentifier}/pmsProjectTestsheet")
@ApiImplicitParams({
        @ApiImplicitParam(name = "enterpriseIdentifier", value = "企业标识", paramType = "path", dataType = "String")
})
public class PmsProjectTestsheetController extends BaseController {
    @Autowired
    private IPmsProjectTestsheetService pmsProjectTestsheetService;

    @Autowired
    private IPmsProductModuleService pmsProductModuleService;

    /**
     * 查询测试单列表
     */
    @ApiOperation(value = "查询测试单列表")
    @RequiresPermissions(value = {"pms:pmsProject:show", "pms:pmsProject:showMe"}, logical = Logical.OR)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前记录起始索引", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页显示记录数", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "orderByColumn", value = "排序列（更新时间：updateTime，创建时间：createTime）", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "isAsc", value = "排序的方向desc或者asc,默认asc", paramType = "query", dataType = "String")
    })
    @GetMapping("/list")
    public GenericsTableDataInfo<PmsProjectTestsheetVo> list(@Validated PmsProjectTestsheetSearchVo searchVo) {
        return pmsProjectTestsheetService.selectPmsProjectTestsheetList(searchVo);
    }

    @RequiresPermissions(value = {"pms:pmsProject:show", "pms:pmsProject:showMe"}, logical = Logical.OR)
    @GetMapping("/treeList")
    @ApiOperation(value = "查测试单模块树状列表")
    public AjaxResult treeList(@Validated PmsProjectTestsheetModuleSearchVo pmsProjectTestsheetModuleSearchVo) {
        PmsProductModule pmsProductModule = pmsProjectTestsheetModuleSearchVo.toPmsProductModule();
        pmsProductModule.getParams().put("projectTestsheetId", pmsProjectTestsheetModuleSearchVo.getProjectTestsheetId());
        List<TreeSelect> treeSelectList = pmsProductModuleService.selectPmsProductModuleTreeList(pmsProductModule, PmsConstants.TESTSHEET_TAG_AND_MODULE_TYPE);
        List<TreeSelect> hasDataTree = this.filterData(treeSelectList, t -> Integer.parseInt(t.getData().toString()) > 0);
        return success(hasDataTree);
    }

    /**
     * 获取测试单详细信息
     */
    @ApiOperation(value = "查询测试单")
    @RequiresPermissions(value = {"pms:pmsProject:show", "pms:pmsProject:showMe"}, logical = Logical.OR)
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(pmsProjectTestsheetService.selectPmsProjectTestsheetByVoId(id));
    }

    /**
     * 新增测试单
     */
    @ApiOperation(value = "新增测试单")
    @RequiresPermissions("pms:pmsProjectTestsheet:add")
    @Log(title = "测试单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody PmsProjectTestsheetInputVo testsheetInputVo) {
        PmsProjectTestsheet pmsProjectTestsheet = new PmsProjectTestsheet();
        BeanUtils.copyProperties(testsheetInputVo, pmsProjectTestsheet);
        return toAjax(pmsProjectTestsheetService.insertPmsProjectTestsheet(pmsProjectTestsheet));
    }

    /**
     * 修改测试单
     */
    @ApiOperation(value = "修改测试单")
    @RequiresPermissions("pms:pmsProjectTestsheet:edit")
    @Log(title = "测试单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody PmsProjectTestsheetUpdateVo testsheetUpdateVo) {
        PmsProjectTestsheet pmsProjectTestsheet = new PmsProjectTestsheet();
        BeanUtils.copyProperties(testsheetUpdateVo, pmsProjectTestsheet);
        return toAjax(pmsProjectTestsheetService.updatePmsProjectTestsheet(pmsProjectTestsheet));
    }

    /**
     * 删除测试单
     */
    @ApiOperation(value = "删除测试单")
    @RequiresPermissions("pms:pmsProjectTestsheet:remove")
    @Log(title = "测试单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(pmsProjectTestsheetService.deletePmsProjectTestsheetByIds(ids));
    }

    private List<TreeSelect> filterData(List<TreeSelect> rows, Predicate<TreeSelect> predicate) {
        List<TreeSelect> newTreeSelectList = new ArrayList<>();
        Optional.ofNullable(rows).orElse(Collections.emptyList()).stream().filter(predicate).forEach(item->{
            item.setChildren(this.filterData(item.getChildren(), t -> Integer.parseInt(t.getData().toString()) > 0));
            newTreeSelectList.add(item);
        });
        return newTreeSelectList;
    }
}
