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.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.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@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;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean submitWbsTreeInContract(WbsTreeContractDTO pawDTO) {
        String wbsTreeIds = pawDTO.getWbsTreeIds();
        /*if (StringUtils.isEmpty(wbsTreeIds)) {
            throw new ServiceException("请选择需要关联的节点");
        }*/
        String[] ids = wbsTreeIds.split(",");
        List<String> idList1 = Arrays.asList(ids);
        List<String> idList2 = new ArrayList<>();
        List<WbsTreeContract> list = baseMapper.findAllNodeList2(pawDTO.getProjectId(), pawDTO.getContractId(), pawDTO.getWbsId());
        if (list.size() > 0) {
            for (WbsTreeContract wbsTreeContract : list) {
                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());
                for (String id : diffrent) {
                    //是否存在,否则新增
                    WbsTreeContract wbsTreeContract = baseMapper.selectByCondition2(id, pawDTO.getProjectId(), pawDTO.getContractId(), pawDTO.getWbsId());
                    if (wbsTreeContract != null) {
                        baseMapper.updateByCondition(id, pawDTO.getProjectId(), pawDTO.getContractId(), pawDTO.getWbsId());
                    } else {
                        WbsTreePrivate wbsTreePrivate = wbsTreePrivateMapper.selectByCondition(id, pawDTO.getWbsId(), pawDTO.getProjectId());
                        Integer wbsType = wbsInfo.getWbsType();
                        Long snowId = SnowFlakeUtil.getId();
                        if (wbsTreePrivate != null) {
                            wbsTreePrivate.setFullName(wbsTreePrivate.getDeptName());
                            //新增
                            baseMapper.insertWbsTreeContract1(snowId, wbsType, pawDTO.getContractId(), wbsTreePrivate);
                            WbsTreePrivate wbsTreePrivateParent = baseMapper.selectParent(wbsTreePrivate.getProjectId(), wbsTreePrivate.getWbsId(), wbsTreePrivate.getParentId());
                            //初始化施工台账
                            if (wbsTreePrivate.getDeptCategory() == 6) {
                                ConstructionLedger constructionLedger = new ConstructionLedger();
                                constructionLedger.setIsBeton(0);
                                constructionLedger.setWbsId(snowId);
                                constructionLedger.setSite(wbsTreePrivate.getDeptName());
                                constructionLedger.setStation(wbsTreePrivateParent.getDeptName());
                                constructionLedger.setContractId(Long.parseLong(pawDTO.getContractId()));
                                constructionLedgerFeign.initConstructionLedger(constructionLedger);
                            }
                        }
                    }
                }
            } else { //删除当前多余的合同段节点
                for (String id : diffrent) {
                    baseMapper.deleteByCondition(id, pawDTO.getWbsId(), pawDTO.getProjectId(), pawDTO.getContractId());
                }
            }
            return true;
        }
    }

    @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);
    }
}