package com.bonus.material.settlement.service.impl;

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

import com.bonus.common.biz.domain.ProjectTreeBuild;
import com.bonus.common.biz.domain.ProjectTreeNode;
import com.bonus.common.biz.enums.TmTaskTypeEnum;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.basic.domain.BmProject;
import com.bonus.material.common.domain.dto.SelectDto;
import com.bonus.material.common.domain.vo.AgreementVo;
import com.bonus.material.countersign.domain.SignConfigVo;
import com.bonus.material.settlement.domain.SltAgreementApply;
import com.bonus.material.settlement.domain.SltAgreementReduce;
import com.bonus.material.settlement.domain.SltAgreementRelation;
import com.bonus.material.settlement.domain.vo.SltInfoVo;
import com.bonus.material.settlement.mapper.SltAgreementReduceMapper;
import com.bonus.material.task.domain.TmTask;
import com.bonus.material.task.mapper.TmTaskMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bonus.material.settlement.mapper.SltAgreementInfoMapper;
import com.bonus.material.settlement.domain.SltAgreementInfo;
import com.bonus.material.settlement.service.ISltAgreementInfoService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 结算信息Service业务层处理
 *
 * @author xsheng
 * @date 2024-10-16
 */
@Service
public class SltAgreementInfoServiceImpl implements ISltAgreementInfoService {
    @Autowired
    private SltAgreementInfoMapper sltAgreementInfoMapper;

    @Autowired
    private TmTaskMapper taskMapper;

    @Resource
    private SltAgreementReduceMapper sltAgreementRecudceMapper;

    /**
     * 查询结算信息
     *
     * @param id 结算信息主键
     * @return 结算信息
     */
    @Override
    public SltAgreementInfo selectSltAgreementInfoById(Long id) {
        return sltAgreementInfoMapper.selectSltAgreementInfoById(id);
    }

    /**
     * 查询结算信息列表
     *
     * @param sltAgreementInfo 结算信息
     * @return 结算信息
     */
    @Override
    public List<SltAgreementInfo> selectSltAgreementInfoList(SltAgreementInfo sltAgreementInfo) {
        return sltAgreementInfoMapper.selectSltAgreementInfoList(sltAgreementInfo);
    }

    @Override
    public List<SltAgreementInfo> getSltAgreementInfo4Project(SltAgreementInfo bean) {
        return sltAgreementInfoMapper.getSltAgreementInfo4Project(bean);
    }

    @Override
    public SltInfoVo getSltInfo(SltAgreementInfo info) {
        SltInfoVo sltInfoVo = new SltInfoVo();
        sltInfoVo.setUnitName(info.getUnitName());
        sltInfoVo.setProjectName(info.getProjectName());
//        sltInfoVo.setUnitName(list.get(0).getUnitName());
//        sltInfoVo.setProjectName(list.get(0).getProjectName());
        BigDecimal leaseCost = BigDecimal.valueOf(0.00);
        BigDecimal repairCost = BigDecimal.valueOf(0.00);
        BigDecimal scrapCost = BigDecimal.valueOf(0.00);
        BigDecimal loseCost = BigDecimal.valueOf(0.00);
        BigDecimal reducCost = BigDecimal.valueOf(0.00);
        //租赁费用列表
        List<SltAgreementInfo> leaseList = getLeaseList(info);
        //维修费用列表
        List<SltAgreementInfo> repairList = getRepairList(info);
        //报废费用列表
        List<SltAgreementInfo> scrapList = getScrapList(info);
        //丢失费用列表
        List<SltAgreementInfo> loseList = getLoseList(info);

        List<SltAgreementReduce> reductionList = getReductionList(info);
        sltInfoVo.setLeaseList(leaseList);
        sltInfoVo.setRepairList(repairList);
        sltInfoVo.setScrapList(scrapList);
        sltInfoVo.setLoseList(loseList);
        sltInfoVo.setReductionList(reductionList);
        for (SltAgreementInfo lease : leaseList) {
            if(lease.getCosts()!=null){
                leaseCost = leaseCost.add(lease.getCosts());
            }
        }
        for (SltAgreementInfo repair : repairList) {
            if(repair.getCosts()!=null && (repair.getPartType().equals("收费"))){
                repairCost = repairCost.add(repair.getCosts());
            }
        }
        for (SltAgreementInfo scrap : scrapList) {
            if(scrap.getCosts()!=null && (scrap.getPartType().equals("收费"))){
                scrapCost = scrapCost.add(scrap.getCosts());
            }
        }
        for (SltAgreementInfo lose : loseList) {
            if(lose.getCosts()!=null){
                loseCost = loseCost.add(lose.getCosts());
            }
        }
        for (SltAgreementReduce reduction : reductionList) {
            if(reduction.getReduceLeaseMoney()!=null){
                reducCost = reducCost.add(reduction.getReduceLeaseMoney());
            }
        }
        sltInfoVo.setLeaseCost(leaseCost);
        sltInfoVo.setRepairCost(repairCost);
        sltInfoVo.setScrapCost(scrapCost);
        sltInfoVo.setLoseCost(loseCost);
        sltInfoVo.setReductionCost(reducCost);
        List<SltAgreementRelation> relations = getRelations(leaseList, repairList, scrapList, loseList, info);
        sltInfoVo.setRelations(relations);
        return sltInfoVo;
    }

    @Override
    public List<SltAgreementApply> getSltExam(SltAgreementInfo bean) {
        return sltAgreementInfoMapper.getSltExam(bean);
    }

//    @Override
//    public SltInfoVo getSltExamInfo(SltAgreementApply apply) {
//        SltInfoVo sltInfoVo = new SltInfoVo();
//        List<SltAgreementInfo> list = new ArrayList<>();
//        String cost = sltAgreementInfoMapper.getCost(apply);
//        List<SltAgreementRelation> relations = sltAgreementInfoMapper.getRelations(apply);
//        sltInfoVo.setRelations(relations);
//        for (SltAgreementRelation relation : relations) {
//            SltAgreementInfo info = new SltAgreementInfo();
//            info.setAgreementId(Long.valueOf(relation.getAgreementId()));
//            list.add(info);
//        }
//        List<SltAgreementInfo> leaseList = getLeaseList(list);
//        List<SltAgreementInfo> repairList = getRepairList(list);
//        List<SltAgreementInfo> scrapList = getScrapList(list);
//        List<SltAgreementInfo> loseList = getLoseList(list);
//        sltInfoVo.setLeaseList(leaseList);
//        sltInfoVo.setRepairList(repairList);
//        sltInfoVo.setScrapList(scrapList);
//        sltInfoVo.setLoseList(loseList);
//        sltInfoVo.setCost(cost);
//        return sltInfoVo;
//    }

//    @Override
//    @Transactional
//    public int settlementReview(SltAgreementApply apply) {
//        Long userid = SecurityUtils.getLoginUser().getUserid();
//        apply.setAuditor(String.valueOf(userid));
//        int j;
//        if ("2".equals(apply.getStatus())) {
//            // 驳回
//            int i = sltAgreementInfoMapper.updateRelation(apply);
//            j = sltAgreementInfoMapper.updateApply(apply);
//        } else {
//            // 通过
//            int i = sltAgreementInfoMapper.updateRelation(apply);
//            if (i > 0) {
//                List<SltAgreementRelation> relations = sltAgreementInfoMapper.getRelations(apply);
//                List<SltAgreementInfo> infos = new ArrayList<>();
//                for (SltAgreementRelation bean : relations) {
//                    SltAgreementInfo info = new SltAgreementInfo();
//                    info.setAgreementId(Long.valueOf(bean.getAgreementId()));
//                    infos.add(info);
//                }
//                List<SltAgreementInfo> loseList = getLoseList(infos);
//                for (SltAgreementInfo agreementInfo : loseList) {
//                    if (agreementInfo.getMaId() != null) {
//                        agreementInfo.setStatus("103");
//                        sltAgreementInfoMapper.updateMaStatus(agreementInfo);
//                    }
//                }
//                j = sltAgreementInfoMapper.updateApply(apply);
//            } else {
//                throw new ServiceException("结算审核失败");
//                //throw new ServiceException(ExceptionDict.SETTLEMENT_REVIEW_ERROR_MSG,ExceptionDict.SETTLEMENT_REVIEW_ERROR);
//            }
//        }
//        return j;
//    }

    /**
     * 新增结算信息
     *
     * @param sltAgreementInfo 结算信息
     * @return 结果
     */
    @Override
    public int insertSltAgreementInfo(SltAgreementInfo sltAgreementInfo) {
        sltAgreementInfo.setCreateTime(DateUtils.getNowDate());
        try {
            return sltAgreementInfoMapper.insertSltAgreementInfo(sltAgreementInfo);
        } catch (Exception e) {
            throw new ServiceException("错误信息描述");
        }
    }

    /**
     * 修改结算信息
     *
     * @param sltAgreementInfo 结算信息
     * @return 结果
     */
    @Override
    public int updateSltAgreementInfo(SltAgreementInfo sltAgreementInfo) {
        sltAgreementInfo.setUpdateTime(DateUtils.getNowDate());
        try {
            return sltAgreementInfoMapper.updateSltAgreementInfo(sltAgreementInfo);
        } catch (Exception e) {
            throw new ServiceException("错误信息描述");
        }
    }

    /**
     * 批量删除结算信息
     *
     * @param ids 需要删除的结算信息主键
     * @return 结果
     */
    @Override
    public int deleteSltAgreementInfoByIds(Long[] ids) {
        return sltAgreementInfoMapper.deleteSltAgreementInfoByIds(ids);
    }

    /**
     * 删除结算信息信息
     *
     * @param id 结算信息主键
     * @return 结果
     */
    @Override
    public int deleteSltAgreementInfoById(Long id) {
        return sltAgreementInfoMapper.deleteSltAgreementInfoById(id);
    }

    public List<SltAgreementInfo> getLeaseList(SltAgreementInfo info) {
        List<SltAgreementInfo> leaseList = new ArrayList<>();

            List<SltAgreementInfo> oneOfList = sltAgreementInfoMapper.getLeaseList(info);
            leaseList.addAll(oneOfList);

        for (SltAgreementInfo bean : leaseList) {
            if (null == bean.getLeasePrice()) {
                bean.setLeasePrice(BigDecimal.valueOf(0.00));
            }else{
                bean.setLeasePrice(bean.getLeasePrice().setScale(2, BigDecimal.ROUND_HALF_UP));
            }
            if (null == bean.getNum()) {
                bean.setNum(BigDecimal.valueOf(0L));
            }
            if (null == bean.getLeaseDays()) {
                bean.setLeaseDay(0L);
            }
            BigDecimal leasePrice = bean.getLeasePrice();
            BigDecimal num = bean.getNum();
            BigDecimal leaseDays = new BigDecimal(bean.getLeaseDays());
            BigDecimal costs = leasePrice.multiply(num).multiply(leaseDays).setScale(2, BigDecimal.ROUND_HALF_UP);
            bean.setCosts(costs);
        }
        return leaseList;
    }

    public List<SltAgreementInfo> getRepairList(SltAgreementInfo info) {
        List<SltAgreementInfo> repairList = new ArrayList<>();
//        Integer taskType = TmTaskTypeEnum.TM_TASK_REPAIR.getTaskTypeId();
//        for (SltAgreementInfo bean : list) {
//            List<TmTask> taskList = taskMapper.getTaskList(bean, taskType);
//            if (null != taskList && !taskList.isEmpty()) {
//                List<SltAgreementInfo> repairDetailsList = sltAgreementInfoMapper.getRepairDetailsList(taskList);
//                repairList.addAll(repairDetailsList);
//            }
//        }

            List<TmTask> taskList = taskMapper.getTaskIdList(info);
            if (null!= taskList &&!taskList.isEmpty()) {
                List<SltAgreementInfo> repairDetailsList = sltAgreementInfoMapper.getRepairDetailsList(taskList);
                repairList.addAll(repairDetailsList);
            }

        return repairList;
    }

    public List<SltAgreementInfo> getScrapList(SltAgreementInfo info) {
        List<SltAgreementInfo> scrapList = new ArrayList<>();

            List<TmTask> taskList = taskMapper.getTaskIdList(info);
            if (null != taskList && !taskList.isEmpty()) {
                List<SltAgreementInfo> scrapDetailsList = sltAgreementInfoMapper.getScrapDetailsList(taskList);
                scrapList.addAll(scrapDetailsList);
            }

        return scrapList;
    }

    public List<SltAgreementInfo> getLoseList(SltAgreementInfo info) {
        List<SltAgreementInfo> loseList = new ArrayList<>();

            List<SltAgreementInfo> oneOfList = sltAgreementInfoMapper.getLoseList(info);
            loseList.addAll(oneOfList);

        for (SltAgreementInfo bean : loseList) {
            if (null == bean.getBuyPrice()) {
                bean.setBuyPrice(BigDecimal.valueOf(0.00));
            }
            if (null == bean.getNum()) {
                bean.setNum(BigDecimal.valueOf(0L));
            }
            BigDecimal buyPrice = bean.getBuyPrice();
            BigDecimal num = bean.getNum();
            // 原价 x 数量
            BigDecimal costs = buyPrice.multiply(num);
            //计算租赁费用
            bean.setCosts(costs);
        }
        return loseList;
    }

    private List<SltAgreementReduce> getReductionList(SltAgreementInfo info) {
        SltAgreementReduce bean =new SltAgreementReduce();
        bean.setAgreementId(info.getAgreementId());
        List<SltAgreementReduce> reductionList = sltAgreementRecudceMapper.getReductionList(bean);
        return reductionList;
    }

    private List<SltAgreementRelation> getRelations(List<SltAgreementInfo> leaseList, List<SltAgreementInfo> repairList,
                                                    List<SltAgreementInfo> scrapList, List<SltAgreementInfo> loseList,
                                                    SltAgreementInfo sltInfo) {
        List<SltAgreementRelation> relations = new ArrayList<>();
//        for (SltAgreementInfo info : list) {
        SltAgreementRelation relation = new SltAgreementRelation();
        BigDecimal loseCost = BigDecimal.ZERO;
        BigDecimal leaseCost = BigDecimal.ZERO;
        BigDecimal scrapCost = BigDecimal.ZERO;
        BigDecimal repairCost = BigDecimal.ZERO;
        for (SltAgreementInfo lease : leaseList) {
            if (lease.getAgreementId().equals(sltInfo.getAgreementId().toString())) {
                relation.setAgreementId(String.valueOf(lease.getAgreementId()));
                relation.setProjectName(lease.getProjectName());
                relation.setUnitName(lease.getUnitName());
                relation.setCompanyId(lease.getCompanyId());
                BigDecimal cost = lease.getCosts();
                leaseCost = leaseCost.add(cost);
            }
        }
        for (SltAgreementInfo repair : repairList) {
            if (repair.getAgreementId().equals(sltInfo.getAgreementId().toString())) {
                BigDecimal cost = repair.getCosts();
                repairCost = repairCost.add(cost);
            }
        }
        for (SltAgreementInfo scrap : scrapList) {
            if (scrap.getAgreementId().equals(sltInfo.getAgreementId().toString())) {
                BigDecimal cost = scrap.getCosts();
                scrapCost = scrapCost.add(cost);
            }
        }
        for (SltAgreementInfo lose : loseList) {
            if (lose.getAgreementId().equals(sltInfo.getAgreementId().toString())) {
                //TODO 上面已经set过值，这里为什么还要set值
                relation.setAgreementId(String.valueOf(lose.getAgreementId()));
                relation.setProjectName(lose.getProjectName());
                relation.setUnitName(lose.getUnitName());
                relation.setCompanyId(lose.getCompanyId());
                BigDecimal cost = lose.getCosts();
                loseCost = loseCost.add(cost);
            }
        }
        relation.setLeaseCost(leaseCost);
        relation.setRepairCost(repairCost);
        relation.setScrapCost(scrapCost);
        relation.setLoseCost(loseCost);
        relations.add(relation);
//    }
        return relations;
    }

    /**
     * 提交结算信息
     *
     * @param sltInfoVo 结算信息
     * @return 结果
     */
    @Override
    @Transactional
    public int submitCosts(SltInfoVo sltInfoVo) {
        try {
            if(sltInfoVo.getAgreementIds()!=null) {

                for (Long agreementId : sltInfoVo.getAgreementIds()) {
                    Long id = null;
                    sltInfoVo.setAgreementId(agreementId);
                    // 计算总成本
                    BigDecimal totalCost = BigDecimal.ZERO;
                    SltAgreementInfo info = new SltAgreementInfo();
                    info.setAgreementId(agreementId);

                    // 获取各项成本并累加
                    totalCost = totalCost.add(getLeaseList(info).stream()
                            .map(SltAgreementInfo::getCosts)
                            .filter(Objects::nonNull)
                            .reduce(BigDecimal.ZERO, BigDecimal::add));

                    totalCost = totalCost.add(getRepairList(info).stream()
                            .map(SltAgreementInfo::getCosts)
                            .filter(Objects::nonNull)
                            .reduce(BigDecimal.ZERO, BigDecimal::add));

                    totalCost = totalCost.add(getScrapList(info).stream()
                            .map(SltAgreementInfo::getCosts)
                            .filter(Objects::nonNull)
                            .reduce(BigDecimal.ZERO, BigDecimal::add));

                    totalCost = totalCost.add(getLoseList(info).stream()
                            .map(SltAgreementInfo::getCosts)
                            .filter(Objects::nonNull)
                            .reduce(BigDecimal.ZERO, BigDecimal::add));

                    totalCost = totalCost.subtract(getReductionList(info).stream()
                            .map(SltAgreementReduce::getLeaseMoney)
                            .filter(Objects::nonNull)
                            .reduce(BigDecimal.ZERO, BigDecimal::add));

                    // 设置总成本
                    sltInfoVo.setTotalCostAll(totalCost);
                    //查找是否驳回
                    int countReject = sltAgreementInfoMapper.getRejectCount(sltInfoVo);
                    if (countReject > 0) {
                        id = sltAgreementInfoMapper.getRejectId(sltInfoVo);
                        //修改
                        int countAgain = sltAgreementInfoMapper.updateRejectCount(sltInfoVo);
                        if (countAgain == 0) {
                            throw new ServiceException("slt_agreement_apply修改失败");
                        }
                        sltInfoVo.setUpdateTime(DateUtils.getNowDate());
                        sltInfoVo.setCreateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
                        int countTwo = sltAgreementInfoMapper.updateBmAgreementStatus(sltInfoVo);
                        if (countTwo != 1) {
                            throw new ServiceException("bm_agreement_info修改失败");
                        }
                    } else {
                        sltInfoVo.setCreateTime(DateUtils.getNowDate());
                        sltInfoVo.setCreateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
                        //新增
                        int countOne = sltAgreementInfoMapper.insertSltAgreementApply(sltInfoVo);
                        if (countOne != 1) {
                            throw new ServiceException("slt_agreement_apply新增失败");
                        }
                        // 插入成功后，sltInfoVo 的 id 属性将被自动设置为新生成的主键值
                        id = sltInfoVo.getId();
                        sltInfoVo.setUpdateTime(DateUtils.getNowDate());
                        int countTwo = sltAgreementInfoMapper.updateBmAgreementStatus(sltInfoVo);
                        if (countTwo != 1) {
                            throw new ServiceException("bm_agreement_info修改失败");
                        }
                    }
                    if (sltInfoVo.getLeaseList().size() > 0) {
                        List<SltAgreementInfo> filteredLeaseList = sltInfoVo.getLeaseList().stream()
                                .filter(lease -> lease.getAgreementId().equals(sltInfoVo.getAgreementId()))
                                .collect(Collectors.toList());
                        if (!filteredLeaseList.isEmpty()) {
                            sltAgreementInfoMapper.insertSltAgreementDetailLease(filteredLeaseList, id);
                        }

                    }
                    if (sltInfoVo.getRepairList().size() > 0) {
                        List<SltAgreementInfo> filteredRepairList = sltInfoVo.getRepairList().stream()
                                .filter(lease -> lease.getAgreementId().equals(sltInfoVo.getAgreementId()))
                                .collect(Collectors.toList());
                        if (!filteredRepairList.isEmpty()) {
                            sltAgreementInfoMapper.insertSltAgreementDetailRepair(filteredRepairList, id);
                        }
                    }
                    if (sltInfoVo.getScrapList().size() > 0) {
                        List<SltAgreementInfo> filteredScrapList = sltInfoVo.getScrapList().stream()
                                .filter(lease -> lease.getAgreementId().equals(sltInfoVo.getAgreementId()))
                                .collect(Collectors.toList());
                        if (!filteredScrapList.isEmpty()) {
                            sltAgreementInfoMapper.insertSltAgreementDetailScrap(filteredScrapList, id);
                        }
                    }
                    if (sltInfoVo.getLoseList().size() > 0) {
                        List<SltAgreementInfo> filteredLoseList = sltInfoVo.getLoseList().stream()
                                .filter(lease -> lease.getAgreementId().equals(sltInfoVo.getAgreementId()))
                                .collect(Collectors.toList());
                        if (!filteredLoseList.isEmpty()) {
                            sltAgreementInfoMapper.insertSltAgreementDetailLose(filteredLoseList, id);
                        }
                    }
                }


            }

            return 1;

        } catch (Exception e) {
            throw new ServiceException("错误信息描述");
        }
    }

    /**
     * 结算审批列表
     *
     * @param bean 结算信息
     * @return 结果
     */
    @Override
    public List<SltAgreementInfo> getSltList(SltAgreementInfo bean) {
        return sltAgreementInfoMapper.getSltList(bean);
    }

    /**
     * 进行结算审批
     *
     * @param sltAgreementApply 进行结算审批
     * @return 结果
     */
    @Override
    public AjaxResult costExamine(SltAgreementApply sltAgreementApply)
    {
        try {
            Long userid = SecurityUtils.getLoginUser().getUserid();
            sltAgreementApply.setAuditor(String.valueOf(userid));
            sltAgreementApply.setAuditTime(DateUtils.getNowDate());
            sltAgreementApply.setUpdateTime(DateUtils.getNowDate());
            if(sltAgreementApply.getStatus().equals("3")){
                //驳回
                int count = sltAgreementInfoMapper.costExame(sltAgreementApply);
                sltAgreementInfoMapper.costDeleteDetail(sltAgreementApply);
                if(count!= 1){
                    return AjaxResult.error("结算审批失败");
                }else{
                    int countTwo = sltAgreementInfoMapper.updateBmAgreementReject(sltAgreementApply);
                    if(countTwo!=1){
                        return AjaxResult.error("bm_agreement_info修改失败");
                    }
                    return AjaxResult.success();
                }
            }else{
                //通过
                int count = sltAgreementInfoMapper.costExame(sltAgreementApply);
                if(count != 1){
                    return AjaxResult.error("结算审批失败");
                }else{
                    return AjaxResult.success();
                }
            }
        } catch (Exception e) {
            return AjaxResult.error();
        }
    }

    @Override
    public SltInfoVo getSltRecordDetailsList(SltAgreementInfo info) {
        SltInfoVo sltInfoVo = new SltInfoVo();
        sltInfoVo.setUnitName(info.getUnitName());
        sltInfoVo.setProjectName(info.getProjectName());
        BigDecimal leaseCost = BigDecimal.valueOf(0.00);
        BigDecimal repairCost = BigDecimal.valueOf(0.00);
        BigDecimal scrapCost = BigDecimal.valueOf(0.00);
        BigDecimal loseCost = BigDecimal.valueOf(0.00);
        BigDecimal reductionCost = BigDecimal.valueOf(0.00);
        //租赁费用列表
        List<SltAgreementInfo> leaseList = getLeaseList(info);
        //维修费用列表
        List<SltAgreementInfo> repairList = getRepairList(info);
        //报废费用列表
        List<SltAgreementInfo> scrapList = getScrapList(info);
        //丢失费用列表
        List<SltAgreementInfo> loseList = getLoseList(info);
        //减免费用列表
        List<SltAgreementReduce> reductionList = getReductionList(info);
        sltInfoVo.setLeaseList(leaseList);
        sltInfoVo.setRepairList(repairList);
        sltInfoVo.setScrapList(scrapList);
        sltInfoVo.setLoseList(loseList);
        sltInfoVo.setReductionList(reductionList);

        for (SltAgreementInfo lease : leaseList) {
            if(lease.getCosts()!=null){
                leaseCost = leaseCost.add(lease.getCosts());
            }
        }
        for (SltAgreementInfo repair : repairList) {
            if(repair.getCosts()!=null && (repair.getPartType().equals("收费"))){
                repairCost = repairCost.add(repair.getCosts());
            }
        }
        for (SltAgreementInfo scrap : scrapList) {
            if(scrap.getCosts()!=null && (scrap.getPartType().equals("收费"))){
                scrapCost = scrapCost.add(scrap.getCosts());
            }
        }
        for (SltAgreementInfo lose : loseList) {
            if(lose.getCosts()!=null){
                loseCost = loseCost.add(lose.getCosts());
            }
        }

        for (SltAgreementReduce reduction : reductionList){
            if(reduction.getLeaseMoney()!=null){
                reductionCost = reductionCost.add(reduction.getLeaseMoney());
            }
        }
        sltInfoVo.setLeaseCost(leaseCost);
        sltInfoVo.setRepairCost(repairCost);
        sltInfoVo.setScrapCost(scrapCost);
        sltInfoVo.setLoseCost(loseCost);
        sltInfoVo.setReductionCost(reductionCost);
        List<SltAgreementRelation> relations = getRelations(leaseList, repairList, scrapList, loseList, info);
        //加上减免
        if (relations.size()>0){
            relations.get(0).setSubCost(reductionCost);
        }
        sltInfoVo.setRelations(relations);
        return sltInfoVo;
    }

    /**
     * 工程类型树
     * @param bmProject
     * @return
     */
    @Override
    public AjaxResult getProjectListByUnitIds(BmProject bmProject) {
        List<ProjectTreeNode> groupList = new ArrayList<>();
        List<ProjectTreeNode> list = new ArrayList<>();
        try {
            if(bmProject.getUnitIds()!=null){
                Map<Integer,Integer> map= new HashMap<>();
                for (int i = 0; i < bmProject.getUnitIds().length; i++) {
                    int id = bmProject.getUnitIds()[i];
                    int[] projectIds= sltAgreementInfoMapper.getProjectListByUnitIds(bmProject.getUnitIds()[i]);
                    Map<Integer,Integer> mapTemp=new HashMap<>();
                    for (int j = 0; j < projectIds.length; j++) {
                        mapTemp.put(projectIds[j],1);
                    }
                    mapTemp.forEach((k,v)->{
                        if(map.containsKey(k)){
                            map.put(Integer.valueOf(k),map.get(k)+v);
                        }else{
                            map.put(Integer.valueOf(k),v);
                        }
                    });
                }
                if(map.size()>0){
                    List<Integer> keys = new ArrayList<>();
                    for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
                        if (entry.getValue() == bmProject.getUnitIds().length) {
                            keys.add(entry.getKey());
                        }
                    }
                    for (Integer key : keys) {
                        List<ProjectTreeNode> listTemp = sltAgreementInfoMapper.getProjectList(key);
                        for (ProjectTreeNode node : listTemp) {
                            if (!list.contains(node)) {
                                list.add(node);
                            }
                        }
                    }
                }



            }
//            list = sltAgreementInfoMapper.getProjectListByUnitIds(bmProject);
            if (CollectionUtils.isNotEmpty(list)) {
                // 创建树形结构（数据集合作为参数）
                ProjectTreeBuild treeBuild = new ProjectTreeBuild(list);
                // 原查询结果转换树形结构
                groupList = treeBuild.buildTree();
            }
        } catch (Exception e) {
            return AjaxResult.error(e+"工程下拉树查询失败");
        }
        return AjaxResult.success(groupList);
    }


    @Override
    public AjaxResult getAgreementInfoById(SelectDto dto) {
       List<AgreementVo> vo = new ArrayList<>();
        try {
            List<AgreementVo> list = sltAgreementInfoMapper.getAgreementInfoById(dto.getUnitIds(), dto.getProjectId());
            if (CollectionUtils.isNotEmpty(list)) {
                vo = list;
            } else {
                return AjaxResult.error("未找到匹配的协议信息");
            }
        } catch (Exception e) {
            return AjaxResult.error(e+"协议查询失败");
        }
        return AjaxResult.success(vo);
    }
}
