package org.springblade.manager.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springblade.business.entity.ConstructionLedger;
import org.springblade.business.feign.ConstructionLedgerFeign;
import org.springblade.common.utils.SnowFlakeUtil;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.log.logger.BladeLogger;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.node.ForestNodeMerger;
import org.springblade.core.tool.utils.StringPool;
import org.springblade.manager.dto.WbsTreeContractDTO;
import org.springblade.manager.entity.WbsInfo;
import org.springblade.manager.entity.WbsTreeContract;
import org.springblade.manager.entity.WbsTreePrivate;
import org.springblade.manager.mapper.WbsInfoMapper;
import org.springblade.manager.mapper.WbsTreeContractMapper;
import org.springblade.manager.mapper.WbsTreePrivateMapper;
import org.springblade.manager.service.IWbsTreeContractService;
import org.springblade.manager.vo.WbsTreeContractTreeVO;
import org.springblade.manager.vo.WbsTreeContractTreeVO2;
import org.springblade.manager.vo.WbsTreeContractVO2;
import org.springblade.manager.vo.WbsTreeVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author liuyc
 */
@Service
@AllArgsConstructor
public class WbsTreeContractServiceImpl
        extends BaseServiceImpl<WbsTreeContractMapper, WbsTreeContract>
        implements IWbsTreeContractService {

    private final BladeLogger logger;
    private final WbsTreePrivateServiceImpl wbsTreePrivateService;
    private final ConstructionLedgerFeign constructionLedgerFeign;
    private final WbsTreePrivateMapper wbsTreePrivateMapper;
    private final WbsInfoMapper wbsInfoMapper;

    /**
     * 合同段wbs树保存
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean submitWbsTreeInContract(WbsTreeContractDTO pawDTO) {
        String wbsTreeIds = pawDTO.getWbsTreeIds();
        String[] ids = wbsTreeIds.split(",");
        List<String> idList = Arrays.asList(ids);
        List<String> idList1 = idList.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
        List<String> idList2 = new ArrayList<>();
        List<WbsTreeContract> list = baseMapper.findAllNodeList2(pawDTO.getProjectId(), pawDTO.getContractId(), pawDTO.getWbsId());
        if (list.size() > 0) {
            list.stream().forEach(wbsTreeContract -> {
                idList2.add(String.valueOf(wbsTreeContract.getId()));
            });
        }
        List<String> diffRent = getDiffrent(idList1, idList2);
        if (diffRent.size() == 0) {
            throw new ServiceException("未进行任何操作");
        } else {
            if (idList1.size() > idList2.size()) {
                WbsInfo wbsInfo = wbsInfoMapper.selectById(pawDTO.getWbsId());
                Integer wbsType = wbsInfo.getWbsType();
                List<List<WbsTreePrivate>> listWbsTreePrivate = new ArrayList<>();
                List<WbsTreeContract> listWbsTreeContract = new ArrayList<>();
                diffRent.stream().forEach(id -> {
                    //获取wbs私有树下节点+表
                    List<WbsTreePrivate> wbsTreePrivate = wbsTreePrivateMapper.selectByCondition(id, pawDTO.getWbsId(), pawDTO.getProjectId());
                    listWbsTreePrivate.add(wbsTreePrivate);
                });
                listWbsTreePrivate.stream().forEach(wbsTreePrivates -> {
                    wbsTreePrivates.stream().forEach(wbsTreePrivate -> {
                        WbsTreeContract wbsTreeContract = getWbsTreePrivate(wbsTreePrivate, pawDTO, wbsType);
                        listWbsTreeContract.add(wbsTreeContract);
                    });
                });
                this.saveBatch(listWbsTreeContract, 10000);
                //初始化施工台账
                listWbsTreeContract.stream().forEach(wbsTreeContract -> {
                    if (wbsTreeContract.getDeptCategory() == 6) {
                        ConstructionLedger constructionLedger = new ConstructionLedger();
                        constructionLedger.setIsBeton(0);
                        constructionLedger.setWbsId(wbsTreeContract.getPKeyId());
                        constructionLedger.setSite(wbsTreeContract.getDeptName());
                        constructionLedger.setStation(wbsTreeContract.getDeptName());
                        constructionLedger.setContractId(Long.parseLong(pawDTO.getContractId()));
                        constructionLedgerFeign.initConstructionLedger(constructionLedger);
                    }
                });
            } else {
                //删除
                ArrayList<Long> ids1 = new ArrayList<>();
                diffRent.stream().forEach(id -> {
                    ids1.add(Long.valueOf(id));
                });
                baseMapper.deleteBatch(ids1, pawDTO.getWbsId(), pawDTO.getProjectId(), pawDTO.getContractId());
            }
            return true;
        }
    }

    private WbsTreeContract getWbsTreePrivate(WbsTreePrivate wbsTree, WbsTreeContractDTO pawDTO, Integer wbsType) {
        WbsTreeContract wbsTreeContract = new WbsTreeContract();
        //数据初始化-施工合同
        Long snowId = SnowFlakeUtil.getId();
        wbsTreeContract.setPKeyId(snowId);
        wbsTreeContract.setId(wbsTree.getId());
        wbsTreeContract.setWbsId(pawDTO.getWbsId());
        wbsTreeContract.setWbsType(wbsType);
        wbsTreeContract.setProjectId(pawDTO.getProjectId());
        wbsTreeContract.setContractId(pawDTO.getContractId());
        wbsTreeContract.setContractType(pawDTO.getContractType());
        wbsTreeContract.setTenantId(wbsTree.getTenantId());
        wbsTreeContract.setParentId(wbsTree.getParentId());
        wbsTreeContract.setAncestors(wbsTree.getAncestors());
        //setDeptCategory = 1 施工合同
        wbsTreeContract.setDeptCategory(1);
        wbsTreeContract.setDeptName(wbsTree.getDeptName());
        wbsTreeContract.setFullName(wbsTree.getDeptName());
        wbsTreeContract.setSort(wbsTree.getSort());
        wbsTreeContract.setRemark(wbsTree.getRemark());
        wbsTreeContract.setType(wbsTree.getType());
        wbsTreeContract.setTableType(wbsTree.getTableType());
        wbsTreeContract.setStatus(wbsTree.getStatus());
        wbsTreeContract.setIsDeleted(wbsTree.getIsDeleted());
        wbsTreeContract.setUniqueCode(wbsTree.getUniqueCode());
        wbsTreeContract.setPartitionCode(wbsTree.getPartitionCode());
        wbsTreeContract.setIsConcrete(wbsTree.getIsConcrete());
        wbsTreeContract.setIsExpernode(wbsTree.getIsExpernode());
        wbsTreeContract.setTableOwner(wbsTree.getTableOwner());
        wbsTreeContract.setMajorDataType(wbsTree.getMajorDataType());
        wbsTreeContract.setInitTableName(wbsTree.getInitTableName());
        wbsTreeContract.setIsLinkTable(wbsTree.getIsLinkTable());
        return wbsTreeContract;
    }

    @Override
    public List<WbsTreeContract> findWbsTreeContract(String ids) {
        return baseMapper.selectList(Wrappers.<WbsTreeContract>query().lambda().eq(WbsTreeContract::getContractId, ids));
    }

    public static List<String> getDiffrent(List<String> list1, List<String> list2) {
        List<String> diff = new ArrayList<String>();
        List<String> maxList = list1;
        List<String> minList = list2;
        if (list2.size() > list1.size()) {
            maxList = list2;
            minList = list1;
        }
        Map<String, Integer> map = new HashMap<String, Integer>(maxList.size());
        for (String string : maxList) {
            map.put(string, 1);
        }
        for (String string : minList) {
            if (map.get(string) != null) {
                map.put(string, 2);
                continue;
            }
            diff.add(string);
        }
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            if (entry.getValue() == 1) {
                diff.add(entry.getKey());
            }
        }
        return diff;
    }

    private List<WbsTreeContract> findAllNodeList(String wbsTreeIds, String projectId, String contractId, String
            wbsId) {
        String[] ids = wbsTreeIds.split(",");
        List<Long> idList = new ArrayList<>();
        List<WbsTreeContract> list = new ArrayList<>();
        for (String id : ids) {
            idList.add(Long.valueOf(id));
            WbsTreeContract contract = baseMapper.selectByCondition(id, projectId, contractId, wbsId);
            list.add(contract);
        }
        return list;
    }

    @Override
    public List<WbsTreeContract> queryCurrentContractLogList(String contractId) {
        return this.baseMapper.queryCurrentContractLogList(contractId);
    }

    @Override
    public List<WbsTreeContractTreeVO> lazyTreeTwo(String contractIdRelation, Long parentId, Integer
            contractType, String contractId) {
        return ForestNodeMerger.merge(baseMapper.lazyTreeTwo(contractIdRelation, parentId, contractType, contractId));
    }

    @Override
    public List<WbsTreeContract> searchNodeAllTable(String primaryKeyId) {
        WbsTreeContract wbsTreeContract = baseMapper.selectOne(Wrappers.<WbsTreeContract>query().lambda()
                .eq(WbsTreeContract::getPKeyId, primaryKeyId));
        //获取当前节点下表单
        if (wbsTreeContract == null) {
            throw new ServiceException("未查询到数据");
        }
        if (StringUtils.isNotEmpty(wbsTreeContract.getContractIdRelation())) {
            //监理 业主
            List<WbsTreeContract> wbsTreeContracts = baseMapper.selectList(Wrappers.<WbsTreeContract>query().lambda()
                    .eq(WbsTreeContract::getProjectId, wbsTreeContract.getProjectId())
                    .eq(WbsTreeContract::getWbsId, wbsTreeContract.getWbsId())
                    .eq(WbsTreeContract::getContractId, wbsTreeContract.getContractId())
                    .eq(WbsTreeContract::getType, 2)
                    .eq(WbsTreeContract::getParentId, wbsTreeContract.getId())
                    .eq(WbsTreeContract::getContractIdRelation, wbsTreeContract.getContractIdRelation())
            );
            return wbsTreeContracts;
        } else {
            //施工
            List<WbsTreeContract> wbsTreeContracts = baseMapper.selectList(Wrappers.<WbsTreeContract>query().lambda()
                    .eq(WbsTreeContract::getProjectId, wbsTreeContract.getProjectId())
                    .eq(WbsTreeContract::getWbsId, wbsTreeContract.getWbsId())
                    .eq(WbsTreeContract::getContractId, wbsTreeContract.getContractId())
                    .eq(WbsTreeContract::getType, 2)
                    .eq(WbsTreeContract::getParentId, wbsTreeContract.getId())
            );
            return wbsTreeContracts;
        }
    }
}