package org.jeecg.modules.projectManagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.hibernate.validator.internal.util.Contracts;
import org.jeecg.common.aspect.annotation.Dict;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.modules.basedata.entity.*;
import org.jeecg.modules.basedata.mapper.FdPersonnelMapper;
import org.jeecg.modules.financeManage.service.IFdProjectReceivablesService;
import org.jeecg.modules.message.entity.MailAttacch;
import org.jeecg.modules.message.handle.ISendMsgHandle;
import org.jeecg.modules.message.handle.enums.SendMsgTypeEnum;
import org.jeecg.modules.projectManagement.mapper.FdContractMapper;
import org.jeecg.modules.projectManagement.entity.*;
import org.jeecg.modules.projectManagement.mapper.FdProjectQuotationTemplateItemMapper;
import org.jeecg.modules.basedata.service.*;
import org.jeecg.modules.projectManagement.mapper.FdProjectQuotationTemplateMapper;
import org.jeecg.modules.projectManagement.mapper.fdProjectQuotationFeeMapper;
import org.jeecg.modules.projectManagement.service.*;
import org.jeecg.modules.system.entity.SysDict;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDictService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @Description: 合同档案基本信息表
 * @author： jeecg-boot
 * @date： 2019-05-22
 * @version： V1.0
 */
@Service
@Transactional
public class FdContractServiceImpl extends ServiceImpl<FdContractMapper, FdContract> implements IFdContractService {

    @Resource
    FdContractMapper fdContractMapper;

    @Resource
    IFdContractService fdContractService;

    @Resource
    IFdContractBidpartyService fdContractBidpartyService;

    @Resource
    IFdProjectQuotationTemplateService fdProjectQuotationTemplateService;

    @Resource
    IFdQuotationTemplateService fdQuotationTemplateService;

    @Resource
    IFdContractDetailService fdContractDetailService;

    @Resource
    IFdContractCompoundService fdContractCompoundService;

    @Resource
    IFdContractContactsService fdContractContactsService;

    @Resource
    IFdProjectQuotationService fdProjectQuotationService;

    @Resource
    IFdProjectQuotationTemplateItemService fdProjectQuotationTemplateItemService;

    @Resource
    IFdContractProportionService fdContractProportionService;

    @Resource
    IFdContractClauseService fdContractClauseService;

    @Resource
    FdProjectQuotationTemplateItemMapper fdProjectQuotationTemplateItemMapper;

    @Resource
    FdProjectQuotationTemplateMapper fdProjectQuotationTemplateMapper;

    @Resource
    IFdCustomerContactsService iFdCustomerContactsService;

    @Resource
    IFdCustomerService iFdCustomerService;

    @Resource
    ISysDictService iSysDictService;

    @Resource
    IFdContractClassService iFdContractClassService;
    
    @Resource
    IFdMatrixTypeService iFdMatrixTypeService;

    @Resource
    IFdPersonnelService fdPersonnelService;

    @Resource
    FdPersonnelMapper fdPersonnelMapper;

    @Resource
    IFdProjectReceivablesService fdProjectReceivablesService;

    @Resource
    fdProjectQuotationFeeMapper fdProjectQuotationFeeMapper;

    @Resource
    IfdProjectQuotationFeeService ifdProjectQuotationFeeService;


    @Override
    public IPage<FdContract> findByPage(Page<FdContract> page, QueryWrapper<FdContract> queryWrapper) {
        return fdContractMapper.findByPage(page, queryWrapper);
    }

    /**
     * @return void
     * @Author gurui
     * @Description //TODO  添加 合同档案基本信息表 同时添加 合同申办方表,报价单模板表
     * @Date 10:43 2019/5/23
     * @Param [fdContract]
     **/
    @Override
    public void saveContract(FdContract fdContract) {


        fdContract.setDelFlag("0");
        fdContractService.save(fdContract);

        //采样添加合同id
        for (FdContractDetail fdContractDetail : fdContract.getContractDetailList()) {
            fdContractDetail.setContractId(fdContract.getId());
        }
        //化合物添加合同id
        int i = 1;
        for (FdContractCompound fdContractCompound : fdContract.getContractCompoundList()) {
            fdContractCompound.setSort(i);
            fdContractCompound.setContractId(fdContract.getId());
            i++;
        }

        //联系人添加合同id
        for (FdContractContacts fdContractContacts : fdContract.getContractContactsList()) {
            fdContractContacts.setContractId(fdContract.getId());
        }

        //批量新增采样
        fdContractDetailService.saveBatch(fdContract.getContractDetailList());
        //批量新增化合物
        fdContractCompoundService.saveBatch(fdContract.getContractCompoundList());
        //批量新增联系人
        fdContractContactsService.saveBatch(fdContract.getContractContactsList());


        if (fdContract.getContractBidpartyList() != null) {
            for (FdContractBidparty fdContractBidparty : fdContract.getContractBidpartyList()) {
                FdContractBidparty fdContractBidparty1 = fdContractBidpartyService.getById(fdContractBidparty);
                if (fdContractBidparty1 != null) {
                    fdContractBidparty.setContractId(fdContract.getId());
                    fdContractBidpartyService.save(fdContractBidparty);
                }
            }
        }
        if (fdContract.getProjectQuotationTemplateList() != null) {
            for (FdProjectQuotationTemplate fdProjectQuotationTemplate : fdContract.getProjectQuotationTemplateList()) {
                FdProjectQuotationTemplate fdProjectQuotationTemplate1 = fdProjectQuotationTemplateService.getById(fdProjectQuotationTemplate);
                if (fdProjectQuotationTemplate1 != null) {
                    fdProjectQuotationTemplate.setQuotationId(fdContract.getId());
                    fdProjectQuotationTemplateService.save(fdProjectQuotationTemplate);
                }
            }
        }

    }

    /**
     * @return void
     * @Author gurui
     * @Description //TODO 修改 合同档案基本信息表 同时修改 合同申办方表,报价单模板表
     * @Date 11:11 2019/5/23
     * @Param [fdContract]
     **/
    @Override
    public void updateContract(FdContract fdContract) {
        fdContractService.updateContract(fdContract);
        //根据合同id查询合同申办方表
        LambdaQueryWrapper<FdContractBidparty> queryBidparty = new LambdaQueryWrapper<>();
        queryBidparty.eq(FdContractBidparty::getContractId, fdContract.getId()).eq(FdContractBidparty::getDelFlag, "0");
        List<FdContractBidparty> bidpartyList = fdContractBidpartyService.list(queryBidparty);
        if (fdContract.getContractBidpartyList() != null) {
            for (FdContractBidparty bidparty : bidpartyList) {
                for (FdContractBidparty bidparty1 : fdContract.getContractBidpartyList()) {
                    //将查询出来的ID赋给传入值,根据ID修改
                    bidparty1.setId(bidparty.getId());
                    fdContractBidpartyService.updateById(bidparty1);
                }
            }
        }
        //根据来源报价单id查询项目报价选择的模板对照表
        LambdaQueryWrapper<FdProjectQuotationTemplate> queryProjectQuotationTemplate = new LambdaQueryWrapper<>();
        queryProjectQuotationTemplate.eq(FdProjectQuotationTemplate::getId, fdContract.getQuotationId()).eq(FdProjectQuotationTemplate::getDelFlag, "0");
        List<FdProjectQuotationTemplate> projectQuotationTemplateList = fdProjectQuotationTemplateService.list(queryProjectQuotationTemplate);
        if (fdContract.getProjectQuotationTemplateList() != null) {
            for (FdProjectQuotationTemplate fdProjectQuotationTemplate : projectQuotationTemplateList) {
                for (FdProjectQuotationTemplate fdProjectQuotationTemplate1 : fdContract.getProjectQuotationTemplateList()) {
                    //将查询出来的ID赋给传入值,根据ID修改
                    fdProjectQuotationTemplate1.setId(fdProjectQuotationTemplate.getId());
                    fdProjectQuotationTemplateService.updateById(fdProjectQuotationTemplate1);
                }
            }
        }

    }

    /**
     * @return void
     * @Author gurui
     * @Description //TODO 删除 合同档案基本信息表 同时删除 合同申办方表,报价单模板表
     * @Date 11:34 2019/5/23
     * @Param [ids]
     **/
    @Override
    public void deleteContract(String ids) {
        //获得要删除的ids
        List list = Arrays.asList(ids.split(","));
        FdContract fdContract = null;
        for (int i = 0; i < list.size(); i++) {
            fdContract = new FdContract();
            fdContract.setId(list.get(i).toString());
            //删除合同申办方表
            LambdaQueryWrapper<FdContractBidparty> queryBidParty = new LambdaQueryWrapper<>();
            queryBidParty.eq(FdContractBidparty::getContractId, fdContract.getId());
            List<FdContractBidparty> bidpartyList = fdContractBidpartyService.list(queryBidParty);
            for (FdContractBidparty bidparty : bidpartyList) {
                bidparty.setDelFlag(CommonConstant.DEL_FLAG_1.toString());
                fdContractBidpartyService.updateById(bidparty);
            }
            //删除报价单模板表
            LambdaQueryWrapper<FdProjectQuotationTemplate> queryTemplate = new LambdaQueryWrapper<>();
            queryTemplate.eq(FdProjectQuotationTemplate::getQuotationId, fdContract.getQuotationId());
            List<FdProjectQuotationTemplate> templateList = fdProjectQuotationTemplateService.list(queryTemplate);
            for (FdProjectQuotationTemplate template : templateList) {
                template.setDelFlag(CommonConstant.DEL_FLAG_1.toString());
                fdProjectQuotationTemplateService.updateById(template);
            }
            fdContract.setDelFlag(CommonConstant.DEL_FLAG_1.toString());
            fdContractService.updateById(fdContract);
        }
    }


    @Override
    public List<FdQuotationTemplate> findQuotationTemplate(String quotationId) {
        return fdContractMapper.findQuotationTemplate(quotationId);
    }


    //合同档案的 添加
    public void saveAll(FdContract fdContract) {
        //根据来源报价单号查询项目报价表
        // FdProjectQuotation fdProjectQuotation = fdProjectQuotationService.getById(fdContract.getQuotationId());
        //项目报价单id
        String quotationId = fdContract.getQuotationId();
        //合同id
        String contractId = fdContract.getId();
        //改为已保存合同
        fdContract.setIsSave("1");
        if (fdContract.getId() == "" || fdContract.getId() == null) {
            //新增报表
            fdContract.setDelFlag("0");

            //判断最终金额是否为空 为空则默认为报价总金额
            if (!StringUtils.isNotBlank(fdContract.getFinalTotalAmount())) {
                fdContract.setFinalTotalAmount(fdContract.getTotalAmount());
            }
            fdContractService.save(fdContract);
        } else {
            if(fdContract.getContractTemplateItemList().size()>0){
                //批量修改项目报价单对照明细
                fdProjectQuotationTemplateItemMapper.updateTemplateItemBatch(fdContract.getContractTemplateItemList());
            }
            if(fdContract.getProjectQuotationTemplateList()!=null&&fdContract.getProjectQuotationTemplateList().size()>0){
                //批量修改项目报价模板
                fdProjectQuotationTemplateMapper.updateTotleBatch(fdContract.getProjectQuotationTemplateList());
            }
            if(fdContract.getFdProjectQuotationFeeList()!=null&& fdContract.getFdProjectQuotationFeeList().size()>0){
                //批量修改费用单数据
                fdProjectQuotationFeeMapper.updateSubtotalBatch(fdContract.getFdProjectQuotationFeeList());
            }
            // fdProjectQuotationTemplateItemService.updateBatchById(fdContract.getContractTemplateItemList());
            //修改报表-
            fdContractService.updateById(fdContract);
            //批量删除对照明细
            // LambdaQueryWrapper<FdContractDetail> queryDetail = new LambdaQueryWrapper<>();
            // queryDetail.eq(FdContractDetail::getContractId, contractId);
            // fdContractDetailService.remove(queryDetail);
            //批量删除化合物
             LambdaQueryWrapper<FdContractCompound> queryCompound = new LambdaQueryWrapper<>();
             queryCompound.eq(FdContractCompound::getContractId, contractId);
             queryCompound.eq(FdContractCompound::getDelFlag,"0");
            // fdContractCompoundService.remove(queryCompound);
            FdContractCompound fdContractCompound=new FdContractCompound();
            fdContractCompound.setDelFlag("1");
            //修改化合物删除标记
            fdContractCompoundService.update(fdContractCompound,queryCompound);
            //批量删除联系人
            LambdaQueryWrapper<FdContractContacts> queryContacts = new LambdaQueryWrapper<>();
            queryContacts.eq(FdContractContacts::getContractId, contractId);
            queryContacts.eq(FdContractContacts::getDelFlag,"0");
            // fdContractContactsService.remove(queryContacts);
            //需修改的合同联系人的值
            FdContractContacts fdContractContacts=new FdContractContacts();
            fdContractContacts.setDelFlag("1");
            fdContractContactsService.update(fdContractContacts,queryContacts);

            //项目对照
            // LambdaQueryWrapper<FdProjectQuotationTemplate> queryTemolate = new LambdaQueryWrapper<>();
            // queryTemolate.eq(FdProjectQuotationTemplate::getQuotationId, quotationId);
            // fdProjectQuotationTemplateService.remove(queryTemolate);
            //比例设置
            LambdaQueryWrapper<FdContractProportion> queryProportion = new LambdaQueryWrapper<>();
            queryProportion.eq(FdContractProportion::getContractId, contractId);
            fdContractProportionService.remove(queryProportion);

            //合同收款条款表
            LambdaQueryWrapper<FdContractClause> queryClause = new LambdaQueryWrapper<>();
            queryClause.eq(FdContractClause::getContractId, contractId);
            queryClause.eq(FdContractClause::getDelFlag, "0");
            // fdContractClauseService.remove(queryClause);
            //需修改合同收款条的值
            FdContractClause fdContractClause=new FdContractClause();
            fdContractClause.setDelFlag("1");
            fdContractClauseService.update(fdContractClause,queryClause);

            //申办方
            // LambdaQueryWrapper<FdContractBidparty> queryBidparty = new LambdaQueryWrapper<>();
            // queryBidparty.eq(FdContractBidparty::getContractId,contractId);
            // fdContractBidpartyService.remove(queryBidparty);

        }

        //对照明细对象
        // for (FdContractDetail fdContractDetail : fdContract.getContractDetailList()) {
        //     fdContractDetail.setContractId(fdContract.getId());
        // }
        //化合物
        // int i = 1;
        // for (FdContractCompound fdContractCompound : fdContract.getContractCompoundList()) {
        //     fdContractCompound.setSort(i);
        //     fdContractCompound.setContractId(fdContract.getId());
        //     i++;
        // }
        //联系人
        // for (FdContractContacts fdContractContacts : fdContract.getContractContactsList()) {
        //     fdContractContacts.setContractId(fdContract.getId());
        // }
        //项目报价单对照明细添加报表id
        //  for (FdProjectQuotationTemplateItem fdProjectQuotationTemplateItem : fdProjectQuotation.getQuotationTemplateItemList()) {
        //      //判断利润中心 和 负责人 是否为空
        //      if (fdProjectQuotationTemplateItem.getProfitCenter() != null && fdProjectQuotationTemplateItem.getMaster() != null) {
        //          //不为空则添加数据
        //          fdProjectQuotationTemplateItem.setQuotationId(fdProjectQuotation.getId());
        //      }
        //  }

//        for (FdProjectQuotationTemplateItem fdProjectQuotationTemplateItem:fdContract.getContractTemplateItemList()){
//            fdProjectQuotationTemplateItem.set
//        }


        // if (fdContract.getProjectQuotationTemplateList()==null){
        //     //项目报价单对照集合
        //     List<FdProjectQuotationTemplate> fdProjectQuotationTemplateList = new ArrayList<>();
        //     String quotationTemplateId = "";//用于判断相等
        //     //从对照明细取模板id
        //     for (FdProjectQuotationTemplateItem fdProjectQuotationTemplateItem : fdContract.getContractTemplateItemList()) {
        //         String quotationTemplateId2 = fdProjectQuotationTemplateItem.getProjectQuotationTemplateId();
        //         if (!quotationTemplateId.equals(quotationTemplateId2)) {//存对照对象
        //             //项目报价单对照对象
        //             FdProjectQuotationTemplate temp = new FdProjectQuotationTemplate();
        //             temp.setQuotationTemplateId(quotationTemplateId2);//模板id
        //             temp.setQuotationId(fdContract.getQuotationId());
        //             System.out.println(fdContract.getContractTemplateItemList());
        //             System.out.println(quotationTemplateId2);
        //             System.out.println(fdContract.getQuotationId());
        //             fdProjectQuotationTemplateList.add(temp);
        //             quotationTemplateId = quotationTemplateId2;
        //         }
        //     }
        //     //项目对照
        //     fdProjectQuotationTemplateService.saveBatch(fdProjectQuotationTemplateList);
        // }
        //所选模板添加
        // if (fdContract.getProjectQuotationTemplateList() != null) {
        //     for (FdProjectQuotationTemplate fdProjectQuotationTemplate : fdContract.getProjectQuotationTemplateList()) {
        //         fdProjectQuotationTemplate.setQuotationId(fdContract.getQuotationId());
        //     }
        //     fdProjectQuotationTemplateService.saveBatch(fdContract.getProjectQuotationTemplateList());
        // }

        // for (FdContractProportion fdContractProportion : fdContract.getContractProportionList()) {
        //     if (fdContractProportion.getContractId().equals(fdContract.getId())) {
        //         if (fdContractProportion.getProportionItem().equals("临床项目")) {
        //             fdContractProportion.setProportion(listFee11(fdContract.getQuotationId()));
        //         }
        //         if (fdContractProportion.getProportionItem().equals("生物分析")) {
        //             fdContractProportion.setProportion(listFee22(fdContract.getQuotationId()));
        //         }
        //     }
        // }
        if (fdContract.getContractProportionList() != null) {
            for (FdContractProportion fdContractProportion : fdContract.getContractProportionList()) {
                fdContractProportion.setId(null);
                fdContractProportion.setContractId(fdContract.getId());
            }
            //比例设置
            fdContractProportionService.saveBatch(fdContract.getContractProportionList());
        }
        //联系人不为空
        if(!fdContract.getContractContactsList().isEmpty()&&fdContract.getContractContactsList().size()>0){
            Integer sort=1;
            for(FdContractContacts fdContractContacts:fdContract.getContractContactsList()){
                fdContractContacts.setId(null);
                fdContractContacts.setContractId(fdContract.getId());
                fdContractContacts.setSort(sort);
                sort++;
            }
            fdContractContactsService.saveBatch(fdContract.getContractContactsList());
        }

        //化合物
        if(fdContract.getContractCompoundList()!=null&& fdContract.getContractCompoundList().size()>0){
            int i = 1;
            for (FdContractCompound fdContractCompound : fdContract.getContractCompoundList()) {
                fdContractCompound.setId(null);
                fdContractCompound.setSort(i);
                fdContractCompound.setContractId(fdContract.getId());
                i++;
            }
            fdContractCompoundService.saveBatch(fdContract.getContractCompoundList());
        }



        //收款条款表 添加合同id
        if (fdContract.getContractClauseList() != null) {
            int sort = 1;
            for (FdContractClause fdContractClause : fdContract.getContractClauseList()) {
                fdContractClause.setId(null);
                fdContractClause.setContractId(fdContract.getId());
                fdContractClause.setSort(sort);
                sort++;
            }
            //收款条款表
            fdContractClauseService.saveBatch(fdContract.getContractClauseList());
        }

        // //申办方
        // for (FdContractBidparty fdContractBidparty:fdContract.getContractBidpartyList()){
        //     fdContractBidparty.setContractId(fdContract.getId());
        // }

        //对照明细
        // fdContractDetailService.saveBatch(fdContract.getContractDetailList());
        //化合物
        // fdContractCompoundService.saveBatch(fdContract.getContractCompoundList());
        //联系人
        // fdContractContactsService.saveBatch(fdContract.getContractContactsList());
        //项目报价单对照明细
        // fdProjectQuotationTemplateItemService.saveBatch(fdProjectQuotation.getQuotationTemplateItemList());


        //申办方
        // fdContractBidpartyService.saveBatch(fdContract.getContractBidpartyList());

        //写回申办方，跟新报价中最终申办方
        FdProjectQuotation fdProjectQuotation=new FdProjectQuotation();
        fdProjectQuotation.setSponsorName(fdContract.getSponsorName());
        fdProjectQuotation.setContractId(fdContract.getId());
        fdProjectQuotationService.updateSponsorName(fdProjectQuotation);
    }


    //根据来源报价id 获取模板类型为临床项目的在总费用中的比例
    public String listFee11(String id) {
        //fee1为临床项目费用,fee2为生物分析费用
        int fee1 = 0;
        int fee2 = 0;
        //根据来源合同id查询项目报价单里的数据
        List<FdProjectQuotationTemplateItem> list = fdProjectQuotationTemplateItemService.getByQuotationId1(id);
        //遍历项目报价单里的数据
        for (FdProjectQuotationTemplateItem fdProjectQuotationTemplateItem : list) {
            //获得项目报价单模板id
            String id1 = fdProjectQuotationTemplateItem.getProjectQuotationTemplateId();
            //根据报价单模板id获取模板类型
            FdQuotationTemplate quotationTemplate = fdQuotationTemplateService.getById(id1);
            String type = quotationTemplate.getType();
            //判断当模板类型为临床项目的时候
            if (type.equals("1") || type.equals("3") || type.equals("4")) {
                if (fdProjectQuotationTemplateItem.getFee() != null) {
                    //获取临床项目的费用
                    fee1 += fee1 + Integer.parseInt(fdProjectQuotationTemplateItem.getFee());
                }
            }
            //判断当模板类型为生物分析的时候
            if (type.equals("2") || type.equals("5")) {
                if (fdProjectQuotationTemplateItem.getFee() != null) {
                    //获取生物分析的费用
                    fee2 += fee2 + Integer.parseInt(fdProjectQuotationTemplateItem.getFee());
                }
            }
        }
        // 创建一个数值格式化对象
        NumberFormat numberFormat = NumberFormat.getInstance();
        // 设置精确到小数点后2位
        numberFormat.setMaximumFractionDigits(2);
        String fee = numberFormat.format((float) fee1 / (float) (fee2 + fee1) * 100) + "%";
        return fee;
    }

    //根据来源报价id 获取模板类型为生物分析的在总费用中的比例
    public String listFee22(String id) {
        ;
        //fee1为临床项目费用,fee2为生物分析费用
        int fee1 = 0;
        int fee2 = 0;
        //根据来源合同id查询项目报价单里的数据
        List<FdProjectQuotationTemplateItem> list = fdProjectQuotationTemplateItemService.getByQuotationId1(id);
        //遍历项目报价单里的数据
        for (FdProjectQuotationTemplateItem fdProjectQuotationTemplateItem : list) {
            //获得项目报价单模板id
            String id1 = fdProjectQuotationTemplateItem.getProjectQuotationTemplateId();
            //根据报价单模板id获取模板类型
            FdQuotationTemplate quotationTemplate = fdQuotationTemplateService.getById(id1);
            String type = quotationTemplate.getType();
            //判断当模板类型为临床项目的时候
            if (type.equals("1") || type.equals("3") || type.equals("4")) {
                if (fdProjectQuotationTemplateItem.getFee() != null) {
                    //获取临床项目的费用
                    fee1 += fee1 + Integer.parseInt(fdProjectQuotationTemplateItem.getFee());
                }
            }
            //判断当模板类型为生物分析的时候
            if (type.equals("2") || type.equals("5")) {
                if (fdProjectQuotationTemplateItem.getFee() != null) {
                    //获取生物分析的费用
                    fee2 += fee2 + Integer.parseInt(fdProjectQuotationTemplateItem.getFee());
                }
            }
        }
        // 创建一个数值格式化对象
        NumberFormat numberFormat = NumberFormat.getInstance();
        // 设置精确到小数点后2位
        numberFormat.setMaximumFractionDigits(2);
        String fee = numberFormat.format((float) fee2 / (float) (fee2 + fee1) * 100) + "%";
        return fee;
    }


    /***
     * @Title:根据多个合同id修改状态为2（关闭）
     * @Description:TODO
     * @param ids
     * @return java.util.Map<java.lang.String ,   java.lang.Object>
     * @exception
     * @author 陈创
     * @date 2019/6/5 9:32
     * @updatehistory:
     *   2019/6/5 9:32 批量修改
     */
    @Override
    public Map<String, Object> closeBatch(List<String> ids) {
        Map<String, Object> map = new HashMap<>();
        String succ = " ";//可关闭
        String closed = " ";//已关闭
        //根据多个id查询报价对象集合
        List<FdContract> contractList = fdContractMapper.selectBatchIds(ids);

        //修改
        if (contractList == null || contractList.isEmpty()) {
            closed += "未找到修改数据</br>";
        } else {
            //判断哪些可关闭哪些不可关闭
            for (FdContract fdContract : contractList) {
                if (fdContract.getStatus().equals("2")) {
                    closed += fdContract.getProjectName() + "，";
                } else {
                    succ += fdContract.getProjectName() + "，";
                }
            }
            //可关闭存在则操作数据库修改
            if (!succ.equals("")) {
                fdContractMapper.closeBatch(ids);
            }
        }
        //去掉最后一个"，"号
        closed = closed.substring(0, closed.length() - 1);
        succ = succ.substring(0, succ.length() - 1);
        //加关键词
        if (!succ.equals("")) {
            succ = succ + "关闭成功";
        }
        if (!closed.equals("")) {
            closed = "其中：" + closed + "已处关闭状态。<br>";
        }
        map.put("msg", succ + closed);
        return map;
    }

    /**
     * @return void
     * @Author gurui
     * @Description //TODO 根据id删除化合物
     * @Date 17:04 2019/6/13
     * @Param [id]
     **/
    @Override
    public void deleteCompound(String id) {
        //获得要删除的id
        List list = Arrays.asList(id.split(","));
        FdContract fdContract = new FdContract();
        for (int i = 0; i < list.size(); i++) {
            fdContract.setId(list.get(i).toString());
            // 获取化合物 删除
            FdContractCompound compound = new FdContractCompound();
            compound.setDelFlag("1");
            UpdateWrapper<FdContractCompound> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("contract_id", fdContract.getId());
            fdContractCompoundService.update(compound, updateWrapper);
        }

    }

    /**
     * @return void
     * @Author gurui
     * @Description //TODO 根据id删除联系人
     * @Date 17:04 2019/6/13
     * @Param [id]
     **/
    @Override
    public void deleteContracts(String id) {
        //获得要删除的id
        List list = Arrays.asList(id.split(","));
        FdContract contract = new FdContract();
        for (int i = 0; i < list.size(); i++) {
            contract.setId(list.get(i).toString());
            //获取联系人信息 删除
            FdContractContacts contacts = new FdContractContacts();
            contacts.setDelFlag("1");
            UpdateWrapper<FdContractContacts> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("contract_id", contract.getId());
            fdContractContactsService.update(contacts, updateWrapper);
        }
    }

    /**
     * @return java.util.Map<java.lang.String ,   java.lang.Object>
     * @Author gurui
     * @Description //TODO 弃审核数据 ,使其 状态为0
     * @Date 10:33 2019/6/28
     * @Param [ids]
     **/
    @Override
    public Map<String, Object> auditBatch(List<String> ids) {
        Map<String, Object> map = new HashMap<>();
        String unAudit = " ";//可审计
        String audit = " ";//已审计
        //根据多个id查询报价对象集合
        List<FdContract> contractList = fdContractMapper.selectBatchIds(ids);
        //修改
        if (contractList == null || contractList.isEmpty()) {
            audit += "未找到修改数据</br>";
        } else {
            //判断哪些可关闭哪些不可关闭
            for (FdContract fdContract : contractList) {
                if (fdContract.getStatus().equals("0")) {
                    audit += fdContract.getProjectName() + "，";
                } else {
                    unAudit += fdContract.getProjectName() + "，";
                }
            }
            //可关闭存在则操作数据库修改
            if (!unAudit.equals("")) {
                fdContractMapper.auditBatch(ids);
            }
        }
        //去掉最后一个"，"号
        audit = audit.substring(0, audit.length() - 1);
        unAudit = unAudit.substring(0, unAudit.length() - 1);
        //加关键词
        if (!unAudit.equals("")) {
            unAudit = unAudit + "弃审核成功";
        }
        if (!audit.equals("")) {
            audit = "其中:" + audit + "已处于未审核状态。<br> ";
        }
        map.put("msg", unAudit + audit);
        return map;
    }

    /**
     * @return java.util.Map<java.lang.String   ,   java.lang.Object>
     * @Author gurui
     * @Description //TODO 审核数据 ,使其 状态为1
     * @Date 10:42 2019/6/28
     * @Param [ids]
     **/
    @Override
    public Map<String, Object> reviewBatch(List<String> ids) {
        Map<String, Object> map = new HashMap<>();
        String unReview = " "; //未审核
        String review = " "; //已审核
        //根据多个id查询报价对象集合
        List<FdContract> contractList = fdContractMapper.selectBatchIds(ids);
        //修改
        if (contractList == null || contractList.isEmpty()) {
            review += "未找到修改数据</br>";
        } else {
            //判断哪些已审核哪些未审核
            for (FdContract fdContract : contractList) {
                if (fdContract.getStatus().equals("0")) {
                    unReview += fdContract.getProjectName() + ",";
                }
                if (fdContract.getStatus().equals("1")) {
                    review += fdContract.getProjectName() + ",";
                }
                if (fdContract.getStatus().equals("2")) {
                    throw new RuntimeException("已关闭！无法审核");
                }
                if (fdContract.getStatus().equals("3")) {
                    throw new RuntimeException("已转合同！无法审核");
                }
            }
            //去掉最后一个","号
            unReview = unReview.substring(0, unReview.length() - 1);
            review = review.substring(0, review.length() - 1);
            //操作数据库将未审核的修改成已审核
            if (!unReview.equals("")) {
                fdContractMapper.reviewBatch(ids);
            }
        }
        //加关键词
        if (!unReview.equals("")) {
            unReview = unReview + "审核成功";
        }
        if (!review.equals("")) {
            review = "其中：" + review + "已审核。<br>";
        }
        map.put("msg", unReview + review);
        return map;
    }

    @Override
    public List<FdContract> contractReport(String startDate, String endDate) {
        return fdContractMapper.contractReport(startDate, endDate);
    }

    /***
     * @Title:合同导出json
     * @Description:TODO
     * @param contractId
     * @return org.jeecg.modules.projectManagement.entity.FdContract
     * @exception
     * @author 陈创
     * @date 2019/9/16 11:04
     * @updatehistory:
     *   2019/9/16 11:04 新增
     */
    @Override
    public FdContract exportJson(String contractId) {
        //根据合同id获取的合同对象
        FdContract fdContract = fdContractMapper.selectById(contractId);

        //获取合同签署日期年、月、日
        Date signDate = fdContract.getSignDate();
        // Calendar ca = Calendar.getInstance();
        // ca.setTime(signDate);
        // int year = ca.get(Calendar.YEAR);//年份数值
        // int month = ca.get(Calendar.MONTH);//月
        // int day = ca.get(Calendar.DAY_OF_MONTH);//日
        String year = String.format("%tY", signDate);//年
        String month = String.format("%tm", signDate);//月
        String day = String.format("%td", signDate);//日
        fdContract.setYear(year);
        fdContract.setMonth(month);
        fdContract.setDay(day);

        //查询客户信息
        FdCustomer fdCustomer = iFdCustomerService.getById(fdContract.getPkCustomerId());
        fdCustomer.setAddress(fdContract.getCustomerAddress());
        fdContract.setFdCustomer(fdCustomer);
        fdContract.setCustomercName(fdCustomer.getName());

        //合同方信息
        List<Map<String, Object>> sysDictList = iSysDictService.queryDictItemsByCode("contract_square");
        if (!sysDictList.isEmpty() && sysDictList.size() > 0) {
            String contractParty = fdContract.getContractParty();
            //合同方value是否为空
            if (StringUtils.isNotBlank(contractParty)) {
                for (Map<String, Object> map : sysDictList) {
                    String value = map.get("value").toString();
                    if (contractParty.equals(value)) {
                        fdContract.setContractPartyName(map.get("text").toString());
                    }
                }
            }
        }

        //查询客户默认联系人信息
        LambdaQueryWrapper<FdCustomerContacts> query = new LambdaQueryWrapper<>();
        query.eq(FdCustomerContacts::getPkCustomerId, fdContract.getPkCustomerId());
        query.eq(FdCustomerContacts::getIsDefault, "1");
        //查询默认联系人
        List<FdCustomerContacts> fdCustomerContactsList = iFdCustomerContactsService.list(query);
        //添加合同对象
        for (FdCustomerContacts contacts : fdCustomerContactsList) {
            fdContract.setContactPsn(contacts.getContactPsn());
            fdContract.setContactTel(contacts.getContectTel());
            fdContract.setContactEmail(contacts.getEmail());
            fdContract.setContactAddress(contacts.getAddress());
        }

        //获取总受试人数和总样本数
        LambdaQueryWrapper<FdContractDetail> fdContractDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        fdContractDetailLambdaQueryWrapper.eq(FdContractDetail::getContractId, contractId);
        fdContractDetailLambdaQueryWrapper.eq(FdContractDetail::getDelFlag, "0");
        List<FdContractDetail> fdContractDetailList = fdContractDetailService.list(fdContractDetailLambdaQueryWrapper);
        if (!fdContractDetailList.isEmpty() && fdContractDetailList.size() > 0) {
            Integer subjectNumberTotal = 0;//计算总受试人数
            Integer totalNumTotal = 0;//计算总样本数
            Integer cleaningPeriodTotal = 0;//清洗天数
            Integer samplesPeriodTotal=0;//采样数/阶段
            for (FdContractDetail fdContractDetail : fdContractDetailList) {
                String subjectNumber = fdContractDetail.getSubjectNumber();
                String totalNum = fdContractDetail.getTotalNum();
                String cleaningPeriod = fdContractDetail.getCleaningPeriod();
                String samplesPeriod=fdContractDetail.getSamplesPeriod();
                //总受试人数
                if (StringUtils.isNotBlank(subjectNumber)&&isInteger(subjectNumber)) {
                    subjectNumberTotal += Integer.parseInt(subjectNumber);
                }
                //总样本数
                if (StringUtils.isNotBlank(totalNum)&&isInteger(totalNum)) {
                    totalNumTotal += Double.valueOf(totalNum).intValue();
                }
                //清洗天数
                if (StringUtils.isNotBlank(cleaningPeriod)&&isInteger(cleaningPeriod)) {
                    cleaningPeriodTotal += Integer.parseInt(cleaningPeriod);
                }
                //采样数/阶段
                if (StringUtils.isNotBlank(samplesPeriod)&&isInteger(samplesPeriod)) {
                    samplesPeriodTotal += Integer.parseInt(samplesPeriod);
                }
            }
            fdContract.setSubjectNumberTotal(subjectNumberTotal + "");
            fdContract.setTotalNumTotal(totalNumTotal + "");
            fdContract.setCleaningPeriodTotal(cleaningPeriodTotal+"");
            fdContract.setSamplesPeriodTotal(samplesPeriodTotal+"");
        }

        //付款节点
        LambdaQueryWrapper<FdContractClause> fdContractClauseLambdaQueryWrapper = new LambdaQueryWrapper<>();
        fdContractClauseLambdaQueryWrapper.eq(FdContractClause::getContractId, contractId);
        fdContractClauseLambdaQueryWrapper.eq(FdContractClause::getDelFlag, "0");
        fdContractClauseLambdaQueryWrapper.orderByAsc(FdContractClause::getSort);
        List<FdContractClause> fdContractClauseList = fdContractClauseService.list(fdContractClauseLambdaQueryWrapper);
        DecimalFormat df = new DecimalFormat(".00");
        for(FdContractClause fdContractClause:fdContractClauseList){
            double paymntPeercent=Double.parseDouble(fdContractClause.getPaymentPercent());
            double money=Double.parseDouble(fdContractClause.getMoney());
            fdContractClause.setPaymentPercent(df.format(paymntPeercent));
            fdContractClause.setMoney(df.format(money));
        }
        fdContract.setContractClauseList(fdContractClauseList);

        //获取全部化合物名称
        LambdaQueryWrapper<FdContractCompound> compoundLambdaQueryWrapper = new LambdaQueryWrapper<>();
        compoundLambdaQueryWrapper.eq(FdContractCompound::getContractId, contractId);
        compoundLambdaQueryWrapper.eq(FdContractCompound::getDelFlag, "0");
        compoundLambdaQueryWrapper.orderByAsc(FdContractCompound::getSort);
        List<FdContractCompound> fdContractCompoundList = fdContractCompoundService.list(compoundLambdaQueryWrapper);
        String compoundNameAll = "";//化合物名称全部
        if (!fdContractCompoundList.isEmpty() && fdContractCompoundList.size() > 0) {
            for (FdContractCompound fdContractCompound : fdContractCompoundList) {
                compoundNameAll += fdContractCompound.getCompound() + "、";
            }
        }
        fdContract.setCompoundNameAll(compoundNameAll);

        return fdContract;
    }

    /***
     * @Title:判断是否是数字
            * @Description:TODO
            * @param str
            * @return boolean
            * @exception
            * @author 陈创
            * @date 2019/11/21 18:09
            * @updatehistory:
     *   2019/11/21 18:09 新增
            */
    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    /***
     * @Title:合同导入
            * @Description:TODO
            * @param fdContract
            * @return void
            * @exception
            * @author 陈创
            * @date 2019/11/22 11:43
            * @updatehistory:
     *   2019/11/22 11:43 新增
            */
    @Override
    public void contractImport(FdContract fdContract) {

        //获取合同对应信息
        getContract(fdContract);
        //保存合同
        fdContractService.save(fdContract);

        //联系人处理
        List<FdContractContacts> fdContractContactsList=fdContract.getContractContactsList();
        if(!fdContractContactsList.isEmpty()&&fdContractContactsList.size()>0){
            Integer sort=1;
            for(FdContractContacts fdContractContacts:fdContractContactsList){
                fdContractContacts.setContractId(fdContract.getId());
                if(fdContractContacts.getIsDefault().equals("是")){
                    fdContractContacts.setIsDefault("1");
                }else{
                    fdContractContacts.setIsDefault("0");
                }
                fdContractContacts.setSort(sort);
                sort++;
            }
            fdContract.setContractContactsList(fdContractContactsList);
        }

        //付款节点字典数据
        List<Map<String, Object>> descriptionMap= iSysDictService.queryDictItemsByCode("description");
        //付款类型字典数据
        List<Map<String, Object>> typeMap= iSysDictService.queryDictItemsByCode("type");
        //合同付款节点集合
        List<FdContractClause> fdContractClauseList=fdContract.getContractClauseList();
        if(!fdContractClauseList.isEmpty()&&fdContractClauseList.size()>0){
            Integer sort=1;
            for(FdContractClause fdContractClause:fdContractClauseList){
                fdContractClause.setContractId(fdContract.getId());
                String descriptionName=fdContractClause.getDescriptionName();
                //获取付款描述id
                for(Map<String, Object> map:descriptionMap){
                    if(descriptionName.equals(map.get("text"))){
                        fdContractClause.setDescription(map.get("value").toString());
                    }
                }
                String typeName=fdContractClause.getTypeName();
                //付款节点类型
                for(Map<String, Object> map:typeMap){
                    if(typeName.equals(map.get("text"))){
                        fdContractClause.setType(map.get("value").toString());
                    }
                }
                fdContractClause.setSort(sort);
                sort++;
            }
        }

        //保存子表数据
        importSave(fdContract);

    }

    /***
     * @Title:根据导入json获取合同对应信息
            * @Description:TODO
            * @param fdContract
            * @return void
            * @exception 
            * @author 陈创
            * @date 2019/11/26 12:06
            * @updatehistory:
     *   2019/11/26 12:06 新增
            */
    public void getContract(FdContract fdContract){
        //合同方
        List<Map<String, Object>> contractSquareMap= iSysDictService.queryDictItemsByCode("contract_square");
        for(Map<String, Object> map:contractSquareMap){
            if(StringUtils.isNotBlank(fdContract.getContractPartyName())){
                if(map.get("text").equals(fdContract.getContractPartyName())){
                    fdContract.setContractParty(map.get("value").toString());
                }
            }
        }

        //申办方
        LambdaQueryWrapper<FdCustomer> customerLambdaQueryWrapper=new LambdaQueryWrapper<>();
        customerLambdaQueryWrapper.eq(FdCustomer::getDelFlag,"0");
        customerLambdaQueryWrapper.eq(FdCustomer::getName,fdContract.getBidParty());
        List<FdCustomer> fdCustomerList=iFdCustomerService.list(customerLambdaQueryWrapper);
        if(!fdCustomerList.isEmpty()&&fdCustomerList.size()>0){
            for(FdCustomer fdCustomer:fdCustomerList){
                if(fdContract.getBidParty().equals(fdCustomer.getName())){
                    fdContract.setPkCustomerId(fdCustomer.getId());
                }
            }
        }

        //报价id
        // LambdaQueryWrapper<FdProjectQuotation> fdProjectQuotationLambdaQueryWrapper=new LambdaQueryWrapper<>();
        // fdProjectQuotationLambdaQueryWrapper.eq(FdProjectQuotation::getDelFlag,"0");
        // fdProjectQuotationLambdaQueryWrapper.eq(FdProjectQuotation::getCode,fdContract.getSourceQuotationCode());
        // List<FdProjectQuotation> fdProjectQuotationList=fdProjectQuotationService.list(fdProjectQuotationLambdaQueryWrapper);
        // if(!fdProjectQuotationList.isEmpty()&&fdProjectQuotationList.size()>0){
        //     fdContract.setQuotationId(fdProjectQuotationList.get(0).getId());
        // }


        //合同类型
        LambdaQueryWrapper<FdContractClass> contractClassLambdaQueryWrapper=new LambdaQueryWrapper<>();
        contractClassLambdaQueryWrapper.eq(FdContractClass::getDelFlag,"0");
        contractClassLambdaQueryWrapper.eq(FdContractClass::getName,fdContract.getContractTypeName());
        List<FdContractClass> fdContractClassList=iFdContractClassService.list(contractClassLambdaQueryWrapper);
        if(!fdContractClassList.isEmpty()&&fdContractClassList.size()>0){
            for(FdContractClass fdContractClass:fdContractClassList){
                if(fdContract.getContractTypeName().equals(fdContractClass.getName())){
                    fdContract.setContractType(fdContractClass.getId());
                }
            }
        }

        //合同类型
        if(fdContract.getType().equals("大分子报价")){
            fdContract.setType("2");
        }else{
            fdContract.setType("1");
        }

        //申报
        List<Map<String, Object>> submissionMap= iSysDictService.queryDictItemsByCode("submission");
        for(Map<String, Object> map:submissionMap){
            if(StringUtils.isNotBlank(fdContract.getSubmission())){
                if(map.get("text").equals(fdContract.getSubmission())){
                    fdContract.setSubmission(map.get("value").toString());
                }
            }
        }

        //基质类型
        if(StringUtils.isNotBlank(fdContract.getMatrixTypeName())){
            //基质名称数组数据
            String[] matrixTypeNames=fdContract.getMatrixTypeName().split(",");
            //基质档案的对象集合数据
            LambdaQueryWrapper<FdMatrixType> fdMatrixTypeLambdaQueryWrapper=new LambdaQueryWrapper<>();
            fdMatrixTypeLambdaQueryWrapper.eq(FdMatrixType::getDelFlag,"0");
            List<FdMatrixType> fdMatrixTypeList=iFdMatrixTypeService.list(fdMatrixTypeLambdaQueryWrapper);
            String matrixTypeIds="";//存取基质的id
            if(!fdMatrixTypeList.isEmpty()&&fdMatrixTypeList.size()>0){
                //循环基质的名称
                for(String matrixTypeName:matrixTypeNames){
                    //循环基质档案集合
                    for(FdMatrixType fdMatrixType:fdMatrixTypeList){
                        //根据名称获取对应的基质id
                        if(matrixTypeName.equals(fdMatrixType.getName())){
                            if(StringUtils.isNotBlank(matrixTypeIds)){
                                matrixTypeIds+=","+fdMatrixType.getId();
                            }else{
                                matrixTypeIds=fdMatrixType.getId();
                            }
                        }
                    }
                }
            }
            fdContract.setNatrixType(matrixTypeIds);
        }

        fdContract.setQuotationId("无");
        fdContract.setIsSave("1");//已保存
        fdContract.setStatus("4");//已审核
        fdContract.setIsImport("1");//导入合同
    }
    
    /***
     * @Title:根据导入json获取合同子表数据以及保存子表数据
            * @Description:TODO
            * @param fdContract
            * @return void
            * @exception 
            * @author 陈创
            * @date 2019/11/26 12:06
            * @updatehistory:
     *   2019/11/26 12:06 新增
            */
    public void importSave(FdContract fdContract){
        //对照明细保存
        List<FdContractDetail> fdContractDetailList=fdContract.getContractDetailList();
        if(!fdContractDetailList.isEmpty()&&fdContractDetailList.size()>0){
            int sort=1;
            for(FdContractDetail fdContractDetail:fdContractDetailList){
                fdContractDetail.setContractId(fdContract.getId());
                fdContractDetail.setSort(sort);
                sort++;
            }
            fdContractDetailService.saveBatch(fdContractDetailList);
        }

        //化合物保存
        List<FdContractCompound> fdContractCompoundList=fdContract.getContractCompoundList();
        if(!fdContractCompoundList.isEmpty()&&fdContractCompoundList.size()>0){
            Integer sort=1;
            for(FdContractCompound fdContractCompound:fdContractCompoundList){
                fdContractCompound.setContractId(fdContract.getId());
                fdContractCompound.setSort(sort);
                sort++;
            }
            fdContractCompoundService.saveBatch(fdContractCompoundList);
        }

        //比例保存
        List<FdContractProportion> fdContractProportionList=fdContract.getContractProportionList();
        if(!fdContractProportionList.isEmpty()&&fdContractProportionList.size()>0){
            Integer sort=1;
            for(FdContractProportion fdContractProportion:fdContractProportionList){
                fdContractProportion.setContractId(fdContract.getId());
                fdContractProportion.setProportion(fdContractProportion.getProportion()+"%");
                fdContractProportion.setSort(sort);
                sort++;
            }
            fdContractProportionService.saveBatch(fdContractProportionList);
        }

        //联系人保存
        fdContractContactsService.saveBatch(fdContract.getContractContactsList());
        //付款节点保存
        fdContractClauseService.saveBatch(fdContract.getContractClauseList());

    }

    @Override
    public int updateStatusShared(List<String> list, String status) {
        //修改合同状态
        fdContractMapper.updateStatusShared(list,status);
        //如果是双签则修改报价的状态为已签订
        if(status.equals("1")){
            //查询修改的合同
            List<FdContract> fdContractList= fdContractMapper.selectBatchIds(list);
            List<String> quIds=new ArrayList<>();
            //获取与合同相关的报价
            for(FdContract fdContract:fdContractList){
                quIds.add(fdContract.getQuotationId());
            }
            //找到则修改报价信息
            if(quIds.size()>0){
                fdProjectQuotationService.updataStatusShared(quIds,"8");
            }
            //获取累计金额
            finalTotalAmountMain(fdContractList.get(0));
        }
        return 0;
    }


    /***
     * @Title:
            * @Description:TODO 累加有关联的报价 计算到主报价中
            * @param fdContract
            * @return void
            * @exception
            * @author 陈创
            * @date 2020/3/11 14:14
            * @updatehistory:
     *   2020/3/11 14:14 新增
            */
    public void finalTotalAmountMain(FdContract fdContract){
        FdContract fdContractJoinQuotation=fdContractMapper.joinQuotationByContract(fdContract);
        Integer relationStart=fdContractJoinQuotation.getRelationStart();//关联状态
        if(relationStart!=null){//是否为空
            if(relationStart==2||relationStart==3){//主报价以及关联报价状态才执行
                //查询当前关联号的报价
                List<FdContract> fdContractList=fdContractMapper.listByRelationCode(fdContractJoinQuotation);
                Double finalTotalAmountMain=0.00;//累计总金额
                if(!fdContractList.isEmpty()&&fdContractList.size()>0){
                    for(FdContract con:fdContractList){//把当前关联号的总金额加起来
                        if(StringUtils.isNotBlank(con.getFinalTotalAmount())){
                            finalTotalAmountMain+=Double.parseDouble(con.getFinalTotalAmount());
                        }
                    }
                }
                //根据关联号查询主报价合同
                LambdaQueryWrapper<FdContract> lambdaQueryWrapper=new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(FdContract::getCode,fdContractJoinQuotation.getRelationCode());
                lambdaQueryWrapper.eq(FdContract::getDelFlag,"0");
                List<FdContract> fdContractListMain=fdContractService.list(lambdaQueryWrapper);
                FdContract fdContractMain=fdContractListMain.get(0);//主报价对象
                fdContractMain.setFinalTotalAmountMain(finalTotalAmountMain+"");
                fdContractMapper.updateById(fdContractMain);//得到累计金额修改
            }
        }
    }

    @Override
    public void notificationPm(String givePerson,String contractId,List<String> receiverIds){
        FdContract fdContract=fdContractMapper.selectById(contractId);//合同对象
        String code=fdContract.getCode();//Q号
        String contractPartyName=iSysDictService.queryDictTextByKey("contract_square",fdContract.getContractParty());//合同方名称
        //客户档案对象
        FdCustomer fdCustomer=iFdCustomerService.getById(fdContract.getPkCustomerId());
        String customerName=fdCustomer.getName();//客户名称
        String projectName=fdContract.getProjectName();//项目名称
        FdPersonnel fdPersonnel=fdPersonnelService.getById(fdContract.getBusinessManager());
        String bdName="";
        if(fdPersonnel!=null){
            bdName=fdPersonnel.getName();//BD
        }
        //邮件内容
        String msg=code+"  "+contractPartyName+"  "+customerName+"  "+projectName+"  "+bdName+"  合同双签完毕! ---发送人："+givePerson;
        for(String per:receiverIds){
            // mailNotification(givePerson,per,"双签完成通知！",msg);
            fdProjectReceivablesService.noticeFinance(per,"双签完成通知！",msg);
        }
    }

    @Override
    public void peopleSendMsg(String givePerson, String personnel, String title, String msg) {
        //根据财务负责人id查询邮件地址
        FdPersonnel fdPersonnel=fdPersonnelService.getById(personnel);
        ISendMsgHandle sendMsgHandle = null;
        try {
            sendMsgHandle = (ISendMsgHandle) Class.forName(SendMsgTypeEnum.EMAIL.getImplClass()).newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //发起邮件通知
        try {
            sendMsgHandle.peopleSendMsg(givePerson,fdPersonnel.getEmail(),title, msg);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new RuntimeException("检查通知人员的邮箱是否有误");
        }
    }

    @Override
    public void emailEnclosureNotificationPm(FdContract fdContractObject){
        EmailEntity emailEntity=fdContractObject.getEmailEntity();//邮件信息对象
        FdContract fdContract=fdContractMapper.selectById(fdContractObject.getId());//合同对象
        String code=fdContract.getCode();//Q号
        String contractPartyName=iSysDictService.queryDictTextByKey("contract_square",fdContract.getContractParty());//合同方名称
        //客户档案对象
        FdCustomer fdCustomer=iFdCustomerService.getById(fdContract.getPkCustomerId());
        String customerName=fdCustomer.getName();//客户名称
        String projectName=fdContract.getProjectName();//项目名称
        FdPersonnel fdPersonnel=fdPersonnelService.getById(fdContract.getProjectManagerId());
        String bdName="";
        if(fdPersonnel!=null){
            bdName=fdPersonnel.getName();//BD
        }

        //根据收件人id查询邮箱以及相关信息
        LambdaQueryWrapper<FdPersonnel> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(FdPersonnel::getDelFlag,"0");
        lambdaQueryWrapper.in(FdPersonnel::getId,emailEntity.getReceiverList());
        List<FdPersonnel> fdPersonnelList=fdPersonnelMapper.selectList(lambdaQueryWrapper);
        // String receiverEmail ="";
        String[] res=new String[emailEntity.getReceiverList().size()];//存储收件人邮件
        int i=0;
        if(fdPersonnelList!=null&&fdPersonnelList.size()>0){
            for(FdPersonnel fdPersonnel1:fdPersonnelList){
                // receiverEmail+=fdPersonnel1.getEmail()+";";
                res[i]=fdPersonnel1.getEmail();//邮箱
                i++;
            }
        }

        //邮件内容
        String msg=code+"\n"+
                contractPartyName+"——"+customerName+"\n"+
                projectName+"\n\n" +
                "BD："+bdName+"\n" +
                "合同双签完毕!\n" +
                "---发送人："+emailEntity.getSenderName();
        sendMsgAndFileAndreceivers(res,code+"双签完成通知！",msg,emailEntity.getMailAttacchList());
    }


    /***
     * @Title:
            * @Description:TODO 发送邮件 可发送附件 多收件人
            * @param  personnelEmail, title, msg, attachs] 发送人邮箱、收件人邮箱、标题、内容、附件
            * @return void
            * @exception
            * @author 陈创
            * @date 2020/4/17 17:19
            * @updatehistory:
     *   2020/4/17 17:19 新增
            */
    public void sendMsgAndFileAndreceivers(String[] personnelEmail, String title, String msg, List<MailAttacch> attachs) {
        //根据人id查询邮件地址
        // FdPersonnel fdPersonnel=fdPersonnelService.getById(personnel);
        ISendMsgHandle sendMsgHandle = null;
        try {
            sendMsgHandle = (ISendMsgHandle) Class.forName(SendMsgTypeEnum.EMAIL.getImplClass()).newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //发起邮件通知
        try {
            sendMsgHandle.SendMsgAndFileAndreceivers(personnelEmail,title, msg,attachs);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new RuntimeException("检查通知人员的邮箱是否有误");
        }
    }

    @Override
    public FdContract getFdContractInformationByCid(FdContract fdContract) {


        return null;
    }

    @Override
    public List<FdContract> totalProportionContract(Date quotationDate, Date endDate, FdContract fdContract) {
        //获取制单人用户登录名
        // if(StringUtils.isNotBlank(fdProjectQuotationD.getCreateBy())){
        //     SysUser sysUser=sysUserMapper.getUserByPerId(fdProjectQuotationD.getCreateBy());
        //     fdProjectQuotationD.setCreateBy(sysUser.getUsername());
        // }

        System.out.println(endDate + "结束时间");
        List<FdContract> fdContractList = fdContractMapper.totalProportionContract(quotationDate, endDate,fdContract);
        double sum = 0.00;
        //  计算出总报表数
        for (FdContract fdContract1 : fdContractList) {
            sum += Double.parseDouble(fdContract1.getTranslate());
        }
        double percentage = 0.00;
        //  设置占比保留两位小数
        DecimalFormat df = new DecimalFormat("0.00");
        for (FdContract fdContract1 : fdContractList) {
            percentage = Double.parseDouble(fdContract1.getTranslate()) / sum * 100;
            fdContract1.setProportion(df.format(percentage));
        }
        return fdContractList;
    }

    @Override
    public IPage<FdContract> getReportPageContract(Page<FdContract> page, QueryWrapper<FdContract> queryWrapper) {
        return fdContractMapper.getReportPageContract(page,queryWrapper);
    }

    @Override
    public List<FdContract> getContractExport(FdContract fdContract) {
        //导出合同数据
        List<FdContract> contractList=fdContractMapper.getContractExport(fdContract,fdContract.getContractIdList());

        //合同类型
        LambdaQueryWrapper<FdContractClass> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(FdContractClass::getDelFlag,"0");
        List<FdContractClass> fdContractClassList=iFdContractClassService.list(lambdaQueryWrapper);

        if(contractList!=null){
            //循环合同
            for(FdContract fdContract1:contractList){
                String contractTypeName="";//合同类型名称
                //判断合同类型id是否为空
                if(StringUtils.isNotBlank(fdContract1.getContractType())){
                    //获取合同类型ids
                    String[] contractTypes=fdContract1.getContractType().split(",");
                    //循环id查找名称
                    for(String contractType:contractTypes){
                        //循环合同类型
                        for(FdContractClass fdContractClass:fdContractClassList){
                            //根据合同类型id找到对应合同类型名称
                            if(fdContractClass.getId().equals(contractType)){
                                if(contractTypeName.equals("")){
                                    contractTypeName=fdContractClass.getName();
                                }else{
                                    contractTypeName+="、"+fdContractClass.getName();
                                }
                            }
                        }
                    }
                    fdContract1.setContractTypeName(contractTypeName);
                }
            }
        }
        //获取相关模板的总金额
        getFdProjectQuotationFeeTotal(contractList);
        return contractList;
    }



    public void getFdProjectQuotationFeeTotal(List<FdContract> contractList){
        LambdaQueryWrapper<fdProjectQuotationFee> fdProjectQuotationFeeLambdaQueryWrapper=new LambdaQueryWrapper<>();
        fdProjectQuotationFeeLambdaQueryWrapper.eq(fdProjectQuotationFee::getDelFlag,"0");
        List<fdProjectQuotationFee> fdProjectQuotationFeeList=ifdProjectQuotationFeeService.list(fdProjectQuotationFeeLambdaQueryWrapper);
        if(fdProjectQuotationFeeList !=null && fdProjectQuotationFeeList.size()>0){
            for(FdContract fdContract:contractList){
                String quotationId=fdContract.getQuotationId();
                Double croTotal=0.00;//cro总额
                Double croCelevantTotal=0.00;//cro相关总额
                Double clinicalOperationTotal=0.00;//临床总额
                Double bioanalysisTotal=0.00;//生物分析总额
                Double bioanalysisConsumablesTotal=0.00;//生物分析耗材总额
                Double macromoleculeTotal=0.00;//大分子总金额
                List<fdProjectQuotationFee> fdProjectQuotationFeeList1=new ArrayList<>();//大分子总额
                for(fdProjectQuotationFee fee:fdProjectQuotationFeeList){
                    if(fee.getProjectQuotationId().equals(quotationId)){
                        //cro
                        if(fee.getFeeType().equals("1")){
                            //费用1
                            if(StringUtils.isNotBlank(fee.getFeeCategory1SubtotalC())){
                                croTotal+=Double.parseDouble(fee.getFeeCategory1SubtotalC());
                            }
                            //费用2
                            if(StringUtils.isNotBlank(fee.getFeeCategory2SubtotalC())){
                                croTotal+=Double.parseDouble(fee.getFeeCategory2SubtotalC());
                            }
                        }
                        //cro相关
                        if(fee.getFeeType().equals("3")){
                            //费用1
                            if(StringUtils.isNotBlank(fee.getFeeCategory1SubtotalC())){
                                croCelevantTotal+=Double.parseDouble(fee.getFeeCategory1SubtotalC());
                            }
                            //费用2
                            if(StringUtils.isNotBlank(fee.getFeeCategory2SubtotalC())){
                                croCelevantTotal+=Double.parseDouble(fee.getFeeCategory2SubtotalC());
                            }
                        }
                        //临床相关
                        if(fee.getFeeType().equals("4")){
                            //费用1
                            if(StringUtils.isNotBlank(fee.getFeeCategory1SubtotalC())){
                                clinicalOperationTotal+=Double.parseDouble(fee.getFeeCategory1SubtotalC());
                            }
                            //费用2
                            if(StringUtils.isNotBlank(fee.getFeeCategory2SubtotalC())){
                                clinicalOperationTotal+=Double.parseDouble(fee.getFeeCategory2SubtotalC());
                            }
                        }
                        //生物分析
                        if(fee.getFeeType().equals("2")){
                            //费用1
                            if(StringUtils.isNotBlank(fee.getFeeCategory1SubtotalC())){
                                bioanalysisTotal+=Double.parseDouble(fee.getFeeCategory1SubtotalC());
                            }
                            //费用2
                            if(StringUtils.isNotBlank(fee.getFeeCategory2SubtotalC())){
                                bioanalysisTotal+=Double.parseDouble(fee.getFeeCategory2SubtotalC());
                            }
                        }
                        //生物分析耗材
                        if(fee.getFeeType().equals("5")){
                            //费用1
                            if(StringUtils.isNotBlank(fee.getFeeCategory1SubtotalC())){
                                bioanalysisConsumablesTotal+=Double.parseDouble(fee.getFeeCategory1SubtotalC());
                            }
                            //费用2
                            if(StringUtils.isNotBlank(fee.getFeeCategory2SubtotalC())){
                                bioanalysisConsumablesTotal+=Double.parseDouble(fee.getFeeCategory2SubtotalC());
                            }
                        }
                        //大分子
                        if(fee.getFeeType().equals("6")){
                            //费用1
                            if(StringUtils.isNotBlank(fee.getFeeCategory1SubtotalC())){
                                macromoleculeTotal+=Double.parseDouble(fee.getFeeCategory1SubtotalC());
                            }
                        }
                    }

                }
                fdContract.setCroTotal(String.format("%.2f",croTotal));
                fdContract.setCroCelevantTotal(String.format("%.2f",croCelevantTotal));
                fdContract.setClinicalOperationTotal(String.format("%.2f",clinicalOperationTotal));
                fdContract.setBioanalysisTotal(String.format("%.2f",bioanalysisTotal));
                fdContract.setBioanalysisConsumablesTotal(String.format("%.2f",bioanalysisConsumablesTotal));
//                fdContract.setFdProjectQuotationFeeList(fdProjectQuotationFeeList1);
                fdContract.setMacromoleculeTotal(String.format("%.2f",macromoleculeTotal));
            }
        }
    }

    @Override
    public List<FdContract> getContractGroupById() {
        return fdContractMapper.getContractGroupById();
    }

    @Override
    public void updateDelById(FdContract fdContract) {
        //删除合同
        fdContract.setDelFlag("1");
        fdContractService.updateById(fdContract);
        //找到对应报价 把状态改为退回修改
        FdProjectQuotation fdProjectQuotation=fdProjectQuotationService.getById(fdContract.getQuotationId());
        fdProjectQuotation.setStatus("5");
        fdProjectQuotationService.updateById(fdProjectQuotation);
    }

}
