package org.springblade.manager.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.cache.utils.CacheUtil;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.support.Kv;
import org.springblade.core.tool.utils.Func;
import org.springblade.manager.dto.WbsTreeDTO2;
import org.springblade.manager.dto.WbsTreePrivateDTO2;
import org.springblade.manager.entity.WbsTree;
import org.springblade.manager.entity.WbsTreeContract;
import org.springblade.manager.entity.WbsTreePrivate;
import org.springblade.manager.mapper.WbsTreeContractMapper;
import org.springblade.manager.mapper.WbsTreePrivateMapper;
import org.springblade.manager.service.IWbsTreePrivateService;
import org.springblade.manager.vo.WbsNodeTableVO;
import org.springblade.manager.vo.WbsTreePrivateVO;
import org.springblade.manager.vo.WbsTreeVO;
import org.springblade.manager.wrapper.WbsTreePrivateWrapper;
import org.springblade.manager.wrapper.WbsTreeWrapper;
import org.springblade.system.cache.DictCache;
import org.springblade.system.enums.DictEnum;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

import java.util.List;

import static org.springblade.core.cache.constant.CacheConstant.SYS_CACHE;

@RestController
@AllArgsConstructor
@RequestMapping("/wbsPrivate")
@Api(value = "项目级私有wbs动态库", tags = "项目级私有wbs动态库接口")
public class WbsTreePrivateController extends BladeController {

    private final IWbsTreePrivateService wbsTreePrivateService;
    private final WbsTreeContractMapper wbsTreeContractMapper;
    private final WbsTreePrivateMapper wbsTreePrivateMapper;

    /**
     * 私有库节点逻辑删除
     */
    @PostMapping("/remove")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "私有库节点逻辑删除", notes = "传入节点pKeyId")
    public R remove(@ApiParam(value = "主键id", required = true) @RequestParam String pKeyId) {
        //是否存在子节点、表单
        WbsTreePrivate wbsTreePrivate = wbsTreePrivateMapper.selectOne(Wrappers.<WbsTreePrivate>query().lambda()
                .eq(WbsTreePrivate::getPKeyId, pKeyId)
                .eq(WbsTreePrivate::getStatus, 1));
        /*List<WbsTreePrivate> wbsTreePrivate1 = wbsTreePrivateMapper.selectList(Wrappers.<WbsTreePrivate>query().lambda()
                .eq(WbsTreePrivate::getParentId, wbsTreePrivate.getId())
                .eq(WbsTreePrivate::getProjectId, wbsTreePrivate.getProjectId())
                .eq(WbsTreePrivate::getWbsId, wbsTreePrivate.getWbsId())
                .eq(WbsTreePrivate::getStatus, 1));
        if (wbsTreePrivate1.size() > 0) {
            return R.fail("当前节点下存在子节点或表单,删除失败");
        }*/
        //是否被合同段引用
        List<WbsTreeContract> wbsTreeContracts = wbsTreeContractMapper.selectList(Wrappers.<WbsTreeContract>query().lambda()
                .eq(WbsTreeContract::getStatus, 1)
                .eq(WbsTreeContract::getId, wbsTreePrivate.getId())
                .eq(WbsTreeContract::getProjectId, wbsTreePrivate.getProjectId())
                .eq(WbsTreeContract::getWbsId, wbsTreePrivate.getWbsId())
        );
        if (wbsTreeContracts.size() > 0) {
            return R.fail("当前节点已被项目合同段引用,删除失败");
        }
        if (wbsTreePrivateService.deleteLogicBypKeyId(pKeyId) > 0) {
            return R.success("删除成功");
        }
        return R.fail("删除失败");
    }


    /**
     * wbs私有库新增节点接口 同步合同段wbs库
     */
    @PostMapping("/submit")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "新增或修改节点", notes = "WbsTreePrivate")
    public R submit(@Valid @RequestBody WbsTreePrivate wbsTreePrivate) {
        if (wbsTreePrivateService.submit(wbsTreePrivate)) {
            CacheUtil.clear(SYS_CACHE);
            // 返回懒加载树更新节点所需字段
            Kv kv = Kv.create().set("id", String.valueOf(wbsTreePrivate.getId()));
            return R.data(kv);
        }
        return R.fail("操作失败");
    }

    /**
     * 查询当前节点下所有表单（根据节点ID查询当前表单）
     */
    @GetMapping("/findNodeTableByCondition")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "查询当前节点下所有元素表", notes = "传入父节点id、wbsId、projectId")
    public R<List<WbsNodeTableVO>> findNodeTableByCondition(@RequestParam("parentId") String parentId,
                                                            @RequestParam("wbsId") String wbsId,
                                                            @RequestParam("projectId") String projectId) {
        List<WbsNodeTableVO> rs = wbsTreePrivateService.selectByNodeTable(parentId, wbsId, projectId);
        if (!("").equals(rs) && rs.size() > 0) {
            return R.data(rs);
        }
        return R.fail(200, "未查询到数据");
    }


    @GetMapping("/removeTableByCondition")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "删除节点下的元素表", notes = "传入表单id、wbsId、projectId")
    public R removeTableByCondition(@RequestParam("id") String id,
                                    @RequestParam("wbsId") String wbsId,
                                    @RequestParam("projectId") String projectId) {
        //删除表单
        boolean restul = wbsTreePrivateService.removeTableByCondition(id, wbsId, projectId);
        if (restul) {
            return R.success("删除成功");
        }
        return R.fail("删除失败");
    }


    /**
     * wbs私有树懒加载获取项目私有节点树形结构
     */
    @GetMapping("/lazy-tree")
    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "项目级懒加载节点树形结构", notes = "传入wbsId，parentId，，项目id，请求头token")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "wbsId", value = "wbsId", required = true),
            @ApiImplicitParam(name = "parentId", value = "父级id", required = true),
            @ApiImplicitParam(name = "projectId", value = "项目id", required = true),
    })
    public R<List<WbsTreePrivateVO>> lazyTree(String wbsId, Long parentId, String projectId, BladeUser bladeUser, String tenantId) {
        List<WbsTreePrivateVO> tree = wbsTreePrivateService.lazyTree(wbsId, Func.toStrWithEmpty(tenantId, bladeUser.getTenantId()), parentId, projectId);
        if (tree != null && tree.size() > 0) {
            return R.data(tree);
        }
        return R.fail(200, "未查询到信息");
    }

    /**
     * 获取当前节点详情
     */

    @GetMapping("/detail")
    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "详情", notes = "传入主键id,wbsId,项目id,请求头token")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id", value = "节点id", required = true),
            @ApiImplicitParam(name = "wbsId", value = "wbsId", required = true),
            @ApiImplicitParam(name = "projectId", value = "项目id", required = true),
    })
    public R<WbsTreePrivateVO> detail(WbsTreePrivate wbsTree) {
        WbsTreePrivate detail = wbsTreePrivateService.getOne(Condition.getQueryWrapper(wbsTree));
        if (detail != null) {
            return R.data(WbsTreePrivateWrapper.build().entityVO(detail));
        }
        return R.fail(200, "未查询到信息");
    }


    /**
     * 查询当前节点所有同级节点
     */
    @ApiOperationSupport(order = 7)
    @ApiOperation(value = "查询当前节点所有同级节点", notes = "传入项目id、当前节点parentId")
    @RequestMapping(value = "/findWbsTreePrivateSameLevel", method = RequestMethod.GET)
    public R<List<WbsTreePrivateDTO2>> findWbsTreePrivateSameLevel(@RequestParam("projectId") String projectId,
                                                                   @RequestParam("parentId") String parentId,
                                                                   @RequestParam("wbsId") String wbsId) {
        List<WbsTreePrivateDTO2> trees = wbsTreePrivateService.findWbsTreePrivateSameLevel(projectId, parentId, wbsId);
        return R.data(trees);
    }

    /**
     * wbs树节点手动排序
     */
    @ApiOperationSupport(order = 8)
    @ApiOperation(value = "wbs私有树节点手动排序", notes = "WbsTreeDTO2集合,pKeyId=节点pKeyId")
    @RequestMapping(value = "/wbsTreePrivateSort", method = RequestMethod.POST)
    public R wbsTreePrivateSort(@RequestBody List<WbsTreePrivateDTO2> wbsTreeDTO) {
        boolean b = wbsTreePrivateService.wbsTreePrivateSort(wbsTreeDTO);
        return R.status(b);
    }


    /**
     * wbs树节点下表单手动排序
     */
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "wbs私有树表单手动排序", notes = "WbsTreeDTO2集合,pKeyId=表单pKeyId")
    @RequestMapping(value = "/wbsTreePrivateTableSort", method = RequestMethod.POST)
    public R wbsTreePrivateTableSort(@RequestBody List<WbsTreePrivateDTO2> wbsTreeDTO) {
        boolean b = wbsTreePrivateService.wbsTreePrivateTableSort(wbsTreeDTO);
        return R.status(b);
    }


}
