package org.springblade.business.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springblade.business.entity.ConstructionLedger;
import org.springblade.business.feignClient.ClientTreePublicCodeClientImpl;
import org.springblade.business.service.IConstructionLedgerService;
import org.springblade.business.vo.NeiYeLedgerVO;
import org.springblade.business.vo.NeiYeQueryVO;
import org.springblade.common.utils.CommonUtil;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.tool.api.R;
import org.springblade.manager.feign.WbsTreeContractClient;
import org.springblade.manager.vo.WbsTreeContractTreeVOS;
import org.springframework.web.bind.annotation.*;
import org.springblade.core.mp.support.Query;

import java.util.*;

@RestController
@AllArgsConstructor
@RequestMapping("/neiYeController")
@Api(tags = "内业台账")
public class NeiYeController {

    private final WbsTreeContractClient wbsTreeContractClient;

    private final IConstructionLedgerService constructionLedgerService;

    private final ClientTreePublicCodeClientImpl clientTreePublicCodeClient;

    /**
     * 获取内业台账列表
     * @return 内业台账列表
     */
    @PostMapping("/queryCurrentNodeNeiYeLedger")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "获取内业台账列表")
    public R<IPage<NeiYeLedgerVO>> queryCurrentNodeNeiYeLedger(@RequestBody NeiYeQueryVO queryVO){
        //获取当前合同段所有划分情况
        List<WbsTreeContractTreeVOS> contractNodeLIst = this.wbsTreeContractClient.queryContractWbsTreeAll(queryVO.getContractId(), 1, "");
        //形成Map
        Map<String,WbsTreeContractTreeVOS> vosMap = new HashMap<>();
        Map<String,String> vosParentMap = new HashMap<>();
        contractNodeLIst.forEach(vo -> {
            vosMap.put(vo.getId(), vo);
            if(vosParentMap.containsKey(vo.getParentId())){
                //存在，获取拼接
                vosParentMap.put(vo.getParentId(), vosParentMap.get(vo.getParentId()) + "," + vo.getId());
            } else {
                //不存在，新建
                vosParentMap.put(vo.getParentId(), vo.getId());
            }
        });

        //根据parentId获取其下所有子节点
        String clientId = queryVO.getParentId();
        clientId = this.getAllClientId(queryVO.getParentId(), clientId, vosParentMap);

        //结果数据
        List<NeiYeLedgerVO> result = new ArrayList<>();
        //循环节点集合,找到工序节点
        for(WbsTreeContractTreeVOS vos : contractNodeLIst){
            if(new Integer("6").equals(vos.getType())){
                if(clientId != null && !clientId.contains(vos.getId())){
                    continue;
                }

                //工序节点,递归获取父节点信息
                Map<String,String> map = new HashMap<>();
                this.foreachGetParent(map, vosMap, vos.getParentId());

                //目前先查询名称(暂时这么处理)
                if(StringUtils.isNotEmpty(queryVO.getQueryStr()) && !(map.get("unitProject").contains(queryVO.getQueryStr()) || map.get("partProject").contains(queryVO.getQueryStr()) || map.get("subentryProject").contains(queryVO.getQueryStr()) || vos.getTitle().contains(queryVO.getQueryStr()))){
                    //不符合查询条件，跳过
                    continue;
                }

                //获取当前工序的施工台账信息
                Map<String,Object> queryMap = new HashMap<>();
                queryMap.put("wbs_id",vos.getPrimaryKeyId());
                List<ConstructionLedger> ledgers = this.constructionLedgerService.listByMap(queryMap);
                if(ledgers != null && ledgers.size() > 0){
                    ConstructionLedger ledger = ledgers.get(0);
                    if(ledger.getSiteStartTime() != null && ledger.getSiteEndTime() != null){
                        //获取施工起止时间
                        map.put("siteStartToEndTime", DateUtil.format(ledger.getSiteStartTime(), "yyyy-MM-dd") + " ~ " + DateUtil.format(ledger.getSiteEndTime(), "yyyy-MM-dd"));
                    }
                    if(ledger.getDetectionStartTime() != null && ledger.getDetectionEndTime() != null){
                        //获取检测起止时间
                        map.put("detectionStartToEndTime", DateUtil.format(ledger.getDetectionStartTime(), "yyyy-MM-dd") + " ~ " + DateUtil.format(ledger.getDetectionEndTime(), "yyyy-MM-dd"));
                    }
                }
                //todo 当前缺少流程状态、是否关联评定、是否关联试验 =================================
                //新增列表数据
                result.add(new NeiYeLedgerVO(map.get("unitProject"), map.get("partProject"), map.get("subentryProject"), vos.getTitle(), map.get("siteStartToEndTime"), map.get("detectionStartToEndTime"), "1", "false", "false"));
            }
        }
        //根据query的分页信息分组
        if(result.size() != 0){
            List<List<NeiYeLedgerVO>> groupList = CommonUtil.getBatchSize(result, queryVO.getSize());

            //转换为page信息
            Query query = new Query();
            query.setCurrent(queryVO.getCurrent());
            query.setSize(queryVO.getSize());
            IPage<NeiYeLedgerVO> page = Condition.getPage(query);
            page.setTotal(result.size());
            page.setRecords(groupList.get(queryVO.getCurrent() == 0 ? 0 : queryVO.getCurrent() - 1));
            return R.data(page);
        }

        return R.data(null);
    }



    /**
     * 获取指定节点下的所有子节点
     * @param parentId 父节点
     * @param clientId 子节点ID串
     * @param vosParentMap 数据map
     * @return clientId
     */
    private String getAllClientId(String parentId, String clientId, Map<String,String> vosParentMap){
        if(vosParentMap.containsKey(parentId)){
            //获取其下所有子节点
            String clientIds = vosParentMap.get(parentId);
            if(StringUtils.isNotEmpty(clientIds)){
                String[] clientIdArray = clientIds.split(",");
                for(String id : clientIdArray){
                    clientId = this.getAllClientId(id, clientId, vosParentMap);
                }
                clientId += "," + clientIds;
            }
        }
        return clientId;
    }

    /**
     * 递归获取父节点信息
     * @param resultMap 结果集合
     * @param vosMap 所有节点信息
     * @param parentId 父节点
     */
    private void foreachGetParent(Map<String,String> resultMap, Map<String,WbsTreeContractTreeVOS> vosMap, String parentId){
        if(vosMap.containsKey(parentId) || !"0".equals(parentId.trim())){
            //存在父节点信息，获取
            WbsTreeContractTreeVOS vos = vosMap.get(parentId);
            if(new Integer("1").equals(vos.getType())){
                //类型属于1则为单位工程
                resultMap.put("unitProject", vos.getTitle());
            } else if(Arrays.asList("2,3".split(",")).contains(String.valueOf(vos.getType()))){
                //类型属于2和3则为分部工程和子分部工程
                if(resultMap.containsKey("partProject")){
                    //存在
                    resultMap.put("partProject", vos.getTitle() + "/" + resultMap.get("partProject"));
                } else {
                    //不存在
                    resultMap.put("partProject", vos.getTitle());
                }
            } else if(Arrays.asList("4,5".split(",")).contains(String.valueOf(vos.getType()))){
                //类型属于2和3则为分项工程和子分项工程
                if(resultMap.containsKey("subentryProject")){
                    //存在
                    resultMap.put("subentryProject", vos.getTitle() + "/" + resultMap.get("subentryProject"));
                } else {
                    //不存在
                    resultMap.put("subentryProject", vos.getTitle());
                }
            }
            this.foreachGetParent(resultMap, vosMap, vos.getParentId());
        }
    }

    /**
     * 获取当前合同段的划分树
     * @param wbsType 查询类型，1为质检类型划分
     * @return 结果
     */
    @GetMapping("/queryContractWbsTreeByContractIdAndType")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "获取当前合同段的划分树")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "wbsType", value = "数据类型，目前质检为1"),
            @ApiImplicitParam(name = "parentId", value = "父节点，为空则查询第一级节点"),
            @ApiImplicitParam(name = "contractId", value = "合同段ID", required = true)
    })
    public R<List<WbsTreeContractTreeVOS>> queryContractWbsTreeByContractIdAndType(@RequestParam Integer wbsType, @RequestParam String parentId, @RequestParam String contractId){
        List<WbsTreeContractTreeVOS> rootTreeNode;
        if(StringUtils.isEmpty(parentId)){
            //为空，说明初始化
            //获取根节点
            rootTreeNode = this.clientTreePublicCodeClient.queryContractWbsTreeByContractIdAndType(contractId, 1, "0");
        } else {
            //不为空，获取其下子节点
            rootTreeNode = this.wbsTreeContractClient.queryContractWbsTreeByContractIdAndType(contractId, 1, parentId);
        }
        return R.data(rootTreeNode);
    }

}
