111
k94314517
2024-03-05 0b161bd2fa0b448c8824815904355ad245287f01
server/service/src/main/java/com/doumee/service/business/impl/ApplyChangeServiceImpl.java
@@ -1,25 +1,53 @@
package com.doumee.service.business.impl;
import com.alibaba.fastjson.JSONObject;
import com.doumee.biz.system.SystemDictDataBiz;
import com.doumee.core.annotation.excel.ExcelExporter;
import com.doumee.core.constants.ResponseStatus;
import com.doumee.core.exception.BusinessException;
import com.doumee.core.model.LoginUserInfo;
import com.doumee.core.model.PageData;
import com.doumee.core.model.PageWrap;
import com.doumee.core.utils.Constants;
import com.doumee.core.utils.DateUtil;
import com.doumee.core.utils.Utils;
import com.doumee.dao.business.ApplyChangeMapper;
import com.doumee.dao.business.model.ApplyChange;
import com.doumee.dao.business.*;
import com.doumee.dao.business.dto.ApplyChangeCyclePriceDTO;
import com.doumee.dao.business.dto.ApplyChangeOptDTO;
import com.doumee.dao.business.dto.CountCyclePriceDTO;
import com.doumee.dao.business.dto.InsuranceApplyOptDTO;
import com.doumee.dao.business.join.*;
import com.doumee.dao.business.model.*;
import com.doumee.dao.business.vo.CountCyclePriceVO;
import com.doumee.dao.system.model.SystemUser;
import com.doumee.service.business.ApplyChangeService;
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 com.doumee.service.business.third.SignService;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.*;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
 * 加减保换厂申请信息表Service实现
 * @author 江蹄蹄
 * @date 2024/01/15 15:07
 * @date 2024/01/16 10:03
 */
@Service
public class ApplyChangeServiceImpl implements ApplyChangeService {
@@ -27,10 +55,1281 @@
    @Autowired
    private ApplyChangeMapper applyChangeMapper;
    @Autowired
    private DuSolutionJoinMapper duSolutionJoinMapper;
    @Autowired
    private InsuranceApplyMapper insuranceApplyMapper;
    @Autowired
    private CompanySolutionMapper companySolutionMapper;
    @Autowired
    private ApplyChangeJoinMapper applyChangeJoinMapper;
    @Autowired
    private SystemDictDataBiz systemDictDataBiz;
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private SignService signService;
    @Autowired
    private ApplyChagneDetailJoinMapper applyChagneDetailJoinMapper;
    @Autowired
    private ApplyDetailJoinMapper applyDetailJoinMapper;
    @Autowired
    private MemberInsuranceJoinMapper memberInsuranceJoinMapper;
    @Autowired
    private ApplyChangeDetailJoinMapper applyChangeDetailJoinMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private MultifileMapper multifileMapper;
    @Autowired
    private DuSolutionMapper duSolutionMapper;
    @Autowired
    private DuWorktypeMapper duWorktypeMapper;
    @Autowired
    private ApplyLogMapper applyLogMapper;
    @Value("${debug_model}")
    private boolean debugModel;
    @Autowired
    private ApplyLogJoinMapper applyLogJoinMapper;
    @Autowired
    private SolutionsMapper solutionsMapper;
    @Autowired
    private NoticesMapper noticesMapper;
    /**
     * 平台退回投保
     * @param param
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class,BusinessException.class})
    public Integer back(ApplyChange param) {
        if(param.getId() == null ||StringUtils.isBlank(param.getCheckInfo())){
            throw  new BusinessException(ResponseStatus.BAD_REQUEST);
        }
        ApplyChange model = applyChangeMapper.selectById(param.getId());
        if(model == null ||!Constants.equalsInteger(model.getIsdeleted(),Constants.ZERO)){
            throw  new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        InsuranceApply insuranceApply = insuranceApplyMapper.selectById(model.getApplyId());
        if(Objects.isNull(insuranceApply)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        if(insuranceApply.getIsdeleted().equals(Constants.ONE)){
            throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(),"数据已删除,无法进行该操作");
        }
        Solutions solutions = solutionsMapper.selectById(insuranceApply.getSolutionId());
        if(Objects.isNull(solutions)){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"未查询到方案信息");
        }
        if(
//                Constants.equalsInteger(model.getStatus(),Constants.ApplyChangeStatus.UPLOAD.getKey())
//                ||Constants.equalsInteger(model.getStatus(),Constants.ApplyChangeStatus.SIGNATURE.getKey())
//                ||
                Constants.equalsInteger(model.getStatus(),Constants.ApplyChangeStatus.APPROVE.getKey())){
            //已提交和已完成状态不支持审核不通过
            throw  new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"对不起,该申请状态已流转,当前不支持该操作~");
        }
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        ApplyChange update = new ApplyChange();
        update.setEditDate(new Date());
        update.setEditor(user.getId());
        update.setStatus(Constants.ApplyChangeStatus.PLATFORM_AGREE.getKey());
        update.setCheckDate(update.getEditDate());
        update.setCheckInfo(param.getCheckInfo());
        update.setCheckUserId(user.getId());
        update.setId(model.getId());
        applyChangeMapper.updateById(update);
        //存储待办信息
        Constants.NoticeObjectType noticeObjectType = Constants.NoticeObjectType.APPLY_CHANGE;
        if(model.getType().equals(Constants.ONE)){
            noticeObjectType = Constants.NoticeObjectType.CHANGE_FACTORY;
        }
        //删除其他待办
        noticesMapper.delete(new QueryWrapper<Notices>().lambda().eq(Notices::getObjType,noticeObjectType.getKey()).eq(Notices::getObjId,model.getId()));
        Notices notices = new Notices(noticeObjectType,Constants.ONE,model.getId(),solutions.getName(),
                insuranceApply.getCompanyId(), Constants.NoticeType.FOUR);
        noticesMapper.insert(notices);
        Constants.ApplyLogType applyLogType = Constants.ApplyLogType.CA_PLATFORM_CHECK_PASS_NO;
        String info =applyLogType.getInfo();
        info = info.replace("${param}", update.getCheckInfo());
        ApplyLog log = new ApplyLog(update,applyLogType.getName(),info,update.getId(),applyLogType.getKey(), JSONObject.toJSONString(model), JSONObject.toJSONString(update));
        applyLogMapper.insert(log);
        return  1;
    }
    @Override
    @Transactional(rollbackFor = {Exception.class,BusinessException.class})
    public Integer uploadPidan(ApplyChange param) {
        if(param.getId() == null
                || param.getValidCode() == null
                || param.getApplyStartTime() == null
                || param.getPidanFile() == null
                ||StringUtils.isBlank( param.getPidanFile().getFileurl())
                ||StringUtils.isBlank( param.getPidanFile() .getName())){
            throw  new BusinessException(ResponseStatus.BAD_REQUEST);
        }
        ApplyChange model = applyChangeMapper.selectById(param.getId());
        if(model == null ||!Constants.equalsInteger(model.getIsdeleted(),Constants.ZERO)){
            throw  new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        if(!Constants.equalsInteger(model.getStatus(),Constants.ApplyChangeStatus.SIGNATURE.getKey())){
            throw  new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"对不起,该申请状态已流转,当前不支持该操作~");
        }
        InsuranceApply insuranceApply = insuranceApplyMapper.selectById(model.getApplyId());
        if(Objects.isNull(insuranceApply)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"未查询到保单信息");
        }
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        ApplyChange update = new ApplyChange();
        update.setEditDate(new Date());
        update.setEditor(user.getId());
        update.setStatus(Constants.ApplyChangeStatus.APPROVE.getKey());
        update.setCheckDate(update.getEditDate());
        update.setCheckInfo(param.getCheckInfo());
        update.setApplyId(model.getApplyId());
        update.setCheckUserId(user.getId());
        update.setId(model.getId());
        update.setValidCode(param.getValidCode());
        update.setApplyStartTime(param.getApplyStartTime());
        update.setCode(model.getCode());
        param.getPidanFile().setIsdeleted(Constants.ZERO);
        param.getPidanFile().setCreator(user.getId());
        param.getPidanFile().setObjId(update.getId());
        param.getPidanFile().setCreateDate(update.getEditDate());
        param.getPidanFile().setObjType(Constants.MultiFile.CA_PD_PDF.getKey());
        param.getPidanFile().setType(Constants.TWO);
        multifileMapper.insert(param.getPidanFile());
        update.setApplyId(model.getApplyId());
        if(Constants.equalsInteger(model.getType(),Constants.ZERO)){
            //如果是加减保申请 处理加减保明细数据
            dealDetailsValidTime(update,insuranceApply);
        }else{
            //如果是换厂申请 处理明细数据
            dealDetailsDUdata(update,insuranceApply);
        }
        applyChangeMapper.updateById(update);
//        if(1==1){
//            throw new BusinessException(ResponseStatus.DATA_EMPTY);
//        }
        Constants.ApplyLogType applyLogType = Constants.ApplyLogType.CA_PLATFORM_APPROVE;
        String info = "";
        if(model.getValidTime()!=null && model.getValidTime().getTime()/1000!= param.getApplyStartTime().getTime()/1000){
            info =applyLogType.getInfo();
            info = info.replace("${param1}",DateUtil.getPlusTime2(model.getValidTime()));
            info = info.replace("${param2}",DateUtil.getPlusTime2(param.getApplyStartTime()));
        }
        ApplyLog log = new ApplyLog(update,applyLogType.getName(), info,update.getId(),applyLogType.getKey(),JSONObject.toJSONString(model), JSONObject.toJSONString(update));
        applyLogMapper.insert(log);
        return  1;
    }
    @Override
    @Transactional(rollbackFor = {Exception.class,BusinessException.class})
    public     Integer editPidan(ApplyChange param) {
        if(param.getId() == null
                || param.getValidCode() == null
                || param.getPidanFile() == null
                || param.getCheckInfo() == null
                ||StringUtils.isBlank( param.getPidanFile().getFileurl())
                ||StringUtils.isBlank( param.getPidanFile() .getName())){
            throw  new BusinessException(ResponseStatus.BAD_REQUEST);
        }
        ApplyChange model = applyChangeMapper.selectById(param.getId());
        if(model == null ||!Constants.equalsInteger(model.getIsdeleted(),Constants.ZERO)){
            throw  new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        if(!Constants.equalsInteger(model.getStatus(),Constants.ApplyChangeStatus.APPROVE.getKey())){
            throw  new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"对不起,该申请当前不支持该操作~");
        }
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        ApplyChange update = new ApplyChange();
        update.setEditDate(new Date());
        update.setEditor(user.getId());
        update.setCheckDate(update.getEditDate());
        update.setCheckInfo(param.getCheckInfo());
        update.setCheckUserId(user.getId());
        update.setId(model.getId());
        update.setValidCode(param.getValidCode());
        applyChangeMapper.updateById(update);
        //修改员工保单记录
        memberInsuranceJoinMapper.update(null,new UpdateWrapper<MemberInsurance>()
                .lambda()
                .set(MemberInsurance::getPdCode,param.getValidCode())
                .eq(MemberInsurance::getRelationType,Constants.ONE)
                .eq(MemberInsurance::getApplyChangeId,model.getId())
        );
        //删除原有的保单信息
        multifileMapper.delete(new UpdateWrapper<Multifile>().lambda()
                .set(Multifile::getIsdeleted,Constants.ZERO)
                .eq(Multifile::getIsdeleted,Constants.ZERO)
                .eq(Multifile::getObjId,update.getId())
                .eq(Multifile::getObjType,Constants.MultiFile.CA_PD_PDF.getKey())
        );
        param.getPidanFile().setIsdeleted(Constants.ZERO);
        param.getPidanFile().setObjId(update.getId());
        param.getPidanFile().setCreator(user.getId());
        param.getPidanFile().setCreateDate(update.getEditDate());
        param.getPidanFile().setObjType(Constants.MultiFile.CA_PD_PDF.getKey());
        param.getPidanFile().setType(Constants.TWO);
        multifileMapper.insert(param.getPidanFile());
        Constants.ApplyLogType applyLogType = Constants.ApplyLogType.CA_PALTFORM_EDIT_PIDAN;
        String info =  applyLogType.getInfo();
        info = info.replace("${param}",param.getCheckInfo());
        ApplyLog log = new ApplyLog(update,applyLogType.getName(), info,update.getId(),applyLogType.getKey(),JSONObject.toJSONString(model), JSONObject.toJSONString(update));
        applyLogMapper.insert(log);
        return  1;
    }
    /**
     * 处理加减保明细数据
     * @param update
     */
    private void dealDetailsDUdata(ApplyChange update,InsuranceApply insuranceApply) {
        List<ApplyChagneDetail> detailList = applyChagneDetailJoinMapper.selectJoinList(ApplyChagneDetail.class,
                new MPJLambdaWrapper<ApplyChagneDetail>()
                        .selectAll(ApplyChagneDetail.class)
                        .selectAs(Solutions::getTimeUnit,ApplyChagneDetail::getSolutionTimeUnit)
                        .selectAs(Solutions::getPrice,ApplyChagneDetail::getSolutionPrice)
                        .selectAs(Solutions::getId,ApplyChagneDetail::getSolutionId)
                        .selectAs(Solutions::getName,ApplyChagneDetail::getSolutionsName)
                        .selectAs(Worktype::getName,ApplyChagneDetail::getWorkTypeName)
                        .selectAs(DispatchUnit::getName,ApplyChagneDetail::getDuName)
                        .selectAs(Member::getIdcardNo,ApplyChagneDetail::getIdcardNo)
                        .selectAs(Member::getName, ApplyChagneDetail::getMemberName)
                        .selectAs(InsuranceApply::getCode,ApplyChagneDetail::getApplyCode)
                        .leftJoin(Member.class, Member::getId, ApplyChagneDetail::getMemberId)
                        .leftJoin(ApplyChange.class, ApplyChange::getId, ApplyChagneDetail::getApplyChangeId)
                      .leftJoin(InsuranceApply.class, InsuranceApply::getId, ApplyChange::getApplyId)
                      .leftJoin(Solutions.class, Solutions::getId, InsuranceApply::getSolutionId)
                    .leftJoin(Worktype.class,Worktype::getId,ApplyChagneDetail::getWorktypeId)
                    .leftJoin(DispatchUnit.class,DispatchUnit::getId,ApplyChagneDetail::getDuId)
                  .eq(ApplyChagneDetail::getApplyChangeId,update.getId())
                  .eq(ApplyChagneDetail::getIsdeleted,Constants.ZERO) );
        if(detailList ==null || detailList.size()==0){
            return;
        }
        //实际批单生效日期
        Date applyStartTime = DateUtil.getMontageDate(update.getApplyStartTime(),1);
        for(ApplyChagneDetail detail : detailList){
            //查询减保人员是否存在 冲突的 保单明细数据
            if(applyDetailJoinMapper.selectCount(new QueryWrapper<ApplyDetail>()
                    .lambda()
                    .eq(ApplyDetail::getApplyId,update.getApplyId())
                    .eq(ApplyDetail::getIdcardNo,detail.getIdcardNo())
                    .le(ApplyDetail::getStartTime,applyStartTime)
                    .ge(ApplyDetail::getEndTime,applyStartTime)
            )<=Constants.ZERO){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "当前保单下,换厂人员【" + detail.getMemberName() + "】未查询到符合批单日期的数据");
            }
            //查询员工是在主单下 是否存在生效中的数据
            ApplyDetail oldModel = applyDetailJoinMapper.selectOne(new QueryWrapper<ApplyDetail>().lambda()
                    .eq(ApplyDetail::getApplyId, update.getApplyId())
                    .eq(ApplyDetail::getMemberId, detail.getMemberId())
                    .le(ApplyDetail::getStartTime,applyStartTime)
                    .ge(ApplyDetail::getEndTime,applyStartTime)
                    .orderByDesc(ApplyDetail::getCreateDate)
                    .last("limit 1"));
            if(oldModel == null  ){
                throw  new BusinessException(ResponseStatus.SERVER_ERROR.getCode(),"对不起,用户【"+detail.getMemberName()+"】原保单信息有误,批单日期未在保单日期内!");
            }
            Date endDate = oldModel.getEndTime();
            //如果实际批单日期 和 原记录日期相等 则直接修改记录派遣单位与工种信息
            if(applyStartTime.compareTo(oldModel.getStartTime())!=Constants.ZERO){
                //当前日期大于批单日期 需要回滚数据实际数据
                Boolean flag = DateUtil.getMontageDate(new Date(),2).compareTo(DateUtil.getMontageDate(update.getApplyStartTime(),2))>0;
                //换厂后历史记录的费用 fee
                Integer days = DateUtil.daysBetweenDates(DateUtil.getMontageDate(update.getApplyStartTime(),3),DateUtil.getMontageDate(oldModel.getStartTime(),1))+1;
                BigDecimal oldFee = this.getApplyPrice(update.getApplyId(),days);
                BigDecimal fee = oldModel.getFee();
                BigDecimal oldCurrentFee = oldModel.getCurrentFee();
                applyDetailJoinMapper.update(null, new UpdateWrapper<ApplyDetail>().lambda()
                        .set(ApplyDetail::getEditor,update.getEditor())
                        .set(ApplyDetail::getEditDate,update.getEditDate())
                        .set(ApplyDetail::getEndTime,DateUtil.getMontageDate(update.getApplyStartTime(),3))
                        .set(ApplyDetail::getFee,oldFee)
                        .set(flag,ApplyDetail::getCurrentFee,oldFee)
                        .eq(ApplyDetail::getId,oldModel.getId())
                );
                //修改 员工投保明细记录 历史数据
                memberInsuranceJoinMapper.update(null,new UpdateWrapper<MemberInsurance>().lambda()
                        .set(MemberInsurance::getEndTime,update.getApplyStartTime())
                        .set(MemberInsurance::getFee,oldFee)
                        .eq(MemberInsurance::getRelationId,oldModel.getId())
                );
                ApplyDetail applyDetail = new ApplyDetail();
                applyDetail.setApplyId(oldModel.getApplyId());
                applyDetail.setCreateDate(new Date());
                applyDetail.setCreator(update.getEditor());
                applyDetail.setMemberId(oldModel.getMemberId());
                applyDetail.setIdcardNo(detail.getIdcardNo());
                applyDetail.setSex(Constants.getSexByIdCard(detail.getIdcardNo()));
                applyDetail.setMemberName(detail.getMemberName());
                applyDetail.setStartTime(DateUtil.getMontageDate(update.getApplyStartTime(),1));
                applyDetail.setEndTime(endDate);
                applyDetail.setDuId(detail.getDuId());
                applyDetail.setWorktypeId(detail.getWorktypeId());
                applyDetail.setIdcardNo(oldModel.getIdcardNo());
                applyDetail.setFee(fee.subtract(oldFee));
                applyDetail.setIsdeleted(Constants.ZERO);
                if(flag){
                    applyDetail.setCurrentFee(oldCurrentFee.multiply(oldFee));
                }else{
                    applyDetail.setCurrentFee(BigDecimal.ZERO);
                }
                applyDetail.setSex(oldModel.getSex());
                applyDetail.setMemberName(oldModel.getMemberName());
                applyDetail.setFromId(detail.getId());
                applyDetailJoinMapper.insert(applyDetail);
                MemberInsurance memberInsurance = new MemberInsurance(applyDetail,update.getId());
                memberInsurance.setSolutionId(detail.getSolutionId());
                memberInsurance.setWorktypeName(detail.getWorkTypeName());
                memberInsurance.setDuName(detail.getDuName());
                memberInsurance.setApplyChangeId(detail.getApplyChangeId());
                memberInsurance.setSolutionName(detail.getSolutionsName());
                memberInsurance.setPdCode(update.getValidCode());
                memberInsurance.setBdCode(insuranceApply.getCode());
                memberInsurance.setRelationType(Constants.ONE);
                memberInsuranceJoinMapper.insert(memberInsurance);
            }else{
                applyDetailJoinMapper.update(null, new UpdateWrapper<ApplyDetail>().lambda()
                        .set(ApplyDetail::getEditor,update.getEditor())
                        .set(ApplyDetail::getEditDate,update.getEditDate())
                        .set(ApplyDetail::getDuId,detail.getDuId())
                        .set(ApplyDetail::getWorktypeId,detail.getWorktypeId())
                        .eq(ApplyDetail::getId,oldModel.getId())
                );
                //员工投保明细记录 历史数据
                memberInsuranceJoinMapper.update(null,new UpdateWrapper<MemberInsurance>().lambda()
                        .set(MemberInsurance::getDuId,detail.getDuId())
                        .set(MemberInsurance::getDuName,detail.getDuName())
                        .set(MemberInsurance::getWorktypeId,detail.getWorktypeId())
                        .set(MemberInsurance::getWorktypeName,detail.getWorkTypeName())
                        .eq(MemberInsurance::getRelationId,oldModel.getId())
                );
            }
            Member member = memberMapper.selectById(detail.getMemberId());
            if(Objects.isNull(member)){
                throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"未查询到员工数据");
            }
            member.setApplyId(update.getApplyId());
            member.setDuId(detail.getDuId());
            member.setWorktypeId(detail.getWorktypeId());
            member.setStartTime(detail.getStartTime());
            member.setEndTime(detail.getEndTime());
            memberMapper.updateById(member);
            applyChangeDetailJoinMapper.update(null,new UpdateWrapper<ApplyChagneDetail>().lambda()
                    .set(ApplyChagneDetail::getStartTime,DateUtil.getMontageDate(update.getApplyStartTime(), 1))
                    .eq(ApplyChagneDetail::getId,detail.getId())
            );
        }
    }
    /**
     * 处理加减保明细数据
     * @param update
     */
    private void dealDetailsValidTime(ApplyChange update,InsuranceApply insuranceApply) {
        List<ApplyChagneDetail> detailList = applyChagneDetailJoinMapper.selectJoinList(ApplyChagneDetail.class,
                new MPJLambdaWrapper<ApplyChagneDetail>()
                        .selectAll(ApplyChagneDetail.class)
                        .selectAs(Member::getIdcardNo,ApplyChagneDetail::getIdcardNo)
                        .selectAs(Solutions::getTimeUnit, ApplyChagneDetail::getSolutionTimeUnit)
                        .selectAs(Solutions::getPrice, ApplyChagneDetail::getSolutionPrice)
                        .selectAs(Worktype::getName, ApplyChagneDetail::getWorkTypeName)
                        .selectAs(DispatchUnit::getName, ApplyChagneDetail::getDuName)
                        .selectAs(Member::getName, ApplyChagneDetail::getMemberName)
                        .selectAs(Solutions::getName,ApplyChagneDetail::getSolutionsName)
                        .selectAs(InsuranceApply::getCode,ApplyChagneDetail::getApplyCode)
                        .leftJoin(ApplyChange.class, ApplyChange::getId, ApplyChagneDetail::getApplyChangeId)
                        .leftJoin(Member.class, Member::getId, ApplyChagneDetail::getMemberId)
                        .leftJoin(InsuranceApply.class, InsuranceApply::getId, ApplyChange::getApplyId)
                        .leftJoin(Solutions.class, Solutions::getId, InsuranceApply::getSolutionId)
                        .leftJoin(Worktype.class, Worktype::getId, ApplyChagneDetail::getWorktypeId)
                        .leftJoin(DispatchUnit.class, DispatchUnit::getId, ApplyChagneDetail::getDuId)
                        .eq(ApplyChagneDetail::getApplyChangeId, update.getId())
                        .eq(ApplyChagneDetail::getIsdeleted, Constants.ZERO));
        if (detailList == null || detailList.size() == 0) {
            return;
        }
        List<ApplyDetail> addList = new ArrayList<>();
        List<Integer> reduceMembers = new ArrayList<>();
        BigDecimal totalFee = new BigDecimal(0);
        BigDecimal currentFee = new BigDecimal(0);
        //投保记录 加保数据加入新数据  减保数据 修改老数据
        List<MemberInsurance> memberInsuranceList = new ArrayList<>();
        //加保业务 使用的加保金额
        ApplyChangeCyclePriceDTO applyChangeCyclePriceDTO_add = new ApplyChangeCyclePriceDTO();
        applyChangeCyclePriceDTO_add.setApplyId(update.getApplyId());
        applyChangeCyclePriceDTO_add.setValidTime(DateUtil.getMontageDate(update.getApplyStartTime(), 1));
        //加保 添加的金额
        CountCyclePriceVO countCyclePriceVO_add = this.getChangeCountCyclePriceVO(applyChangeCyclePriceDTO_add);
        Solutions solutions = solutionsMapper.selectById(insuranceApply.getSolutionId());
        if(Objects.isNull(solutions)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"未查询到保险方案");
        }
        if(solutions.getDataType().equals(Constants.ONE)){
            solutions = solutionsMapper.selectOne(new QueryWrapper<Solutions>().lambda().eq(Solutions::getBaseId,solutions.getBaseId()).eq(Solutions::getDataType,Constants.TWO).last("limit 1"));
            if(Objects.isNull(solutions)){
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"未查询到方案最新版本信息");
            }
        }
        for (ApplyChagneDetail detail : detailList) {
            Member member = memberMapper.selectById(detail.getMemberId());
            if(Objects.isNull(member)){
                throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"未查询到员工数据");
            }
            if (Constants.equalsInteger(detail.getType(), Constants.ZERO)) {
                //查询加保人员是否存在 冲突的 保单明细数据
                if(applyDetailJoinMapper.selectCount(new QueryWrapper<ApplyDetail>()
                        .lambda()
                        .eq(ApplyDetail::getApplyId,update.getApplyId())
                        .eq(ApplyDetail::getIdcardNo,detail.getIdcardNo())
                        .le(ApplyDetail::getStartTime,DateUtil.getMontageDate(update.getApplyStartTime(),1))
                        .ge(ApplyDetail::getEndTime,DateUtil.getMontageDate(detail.getEndTime(),2))
                )>Constants.ZERO){
                    throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "当前保单下,加保人员【" + detail.getMemberName() + "】存在日期冲突的数据");
                }
                //加保
                ApplyDetail add = new ApplyDetail();
                add.setApplyId(update.getApplyId());
                add.setValidCode(update.getValidCode());
                add.setFee(detail.getFee());
                add.setIsdeleted(Constants.ZERO);
                add.setCreator(update.getEditor());
                add.setCreateDate(update.getEditDate());
                add.setMemberId(detail.getMemberId());
                add.setMemberName(detail.getMemberName());
                add.setWorktypeId(detail.getWorktypeId());
                add.setIsdeleted(Constants.ZERO);
                add.setIdcardNo(detail.getIdcardNo());
                add.setSex(Constants.getSexByIdCard(detail.getIdcardNo()));
                add.setMemberName(detail.getMemberName());
                add.setDuId(detail.getDuId());
                add.setStartTime(update.getApplyStartTime());
                add.setStartTime(DateUtil.getMontageDate(update.getApplyStartTime(), 1));
                add.setEndTime(DateUtil.getMontageDate(detail.getEndTime(), 2));
                add.setFee(countCyclePriceVO_add.getCyclePrice());
                if(new Date().compareTo(DateUtil.getMontageDate(detail.getStartTime(), 2))>=0){
                    Integer days = DateUtil.daysBetweenDates(DateUtil.getMontageDate(new Date(), 2), detail.getStartTime()) + 1;
                    //如果已已产生费用,计算已已产生费用
                    add.setCurrentFee(this.getApplyPrice(update.getApplyId(), days));
                }else{
                    add.setCurrentFee(BigDecimal.ZERO);
                }
                applyDetailJoinMapper.insert(add);
                totalFee = totalFee.add(add.getFee());
                currentFee = currentFee.add(add.getCurrentFee());
                MemberInsurance memberInsurance = new MemberInsurance(detail, update, update.getEditor(), add.getId(),solutions.getId());
                memberInsurance.setStartTime(add.getStartTime());
                memberInsurance.setEndTime(add.getEndTime());
                memberInsurance.setRelationType(Constants.ONE);
                memberInsuranceList.add(memberInsurance);
                applyChangeDetailJoinMapper.update(null,new UpdateWrapper<ApplyChagneDetail>().lambda()
                        .set(ApplyChagneDetail::getFee,add.getFee())
                        .set(ApplyChagneDetail::getStartTime,DateUtil.getMontageDate(update.getApplyStartTime(), 1))
                        .eq(ApplyChagneDetail::getId,detail.getId())
                );
            } else {
                    //减保操作
                    //查询员工是在主单下 是否存在生效中的数据
                    ApplyDetail oldModel = applyDetailJoinMapper.selectOne(new QueryWrapper<ApplyDetail>().lambda()
                            .eq(ApplyDetail::getApplyId, update.getApplyId())
                            .eq(ApplyDetail::getMemberId, detail.getMemberId())
                            .orderByDesc(ApplyDetail::getCreateDate)
                            .last("limit 1"));
                    if (oldModel == null || oldModel.getStartTime() == null || oldModel.getStartTime().getTime() > update.getApplyStartTime().getTime()) {
                        throw new BusinessException(ResponseStatus.SERVER_ERROR.getCode(), "对不起,用户【" + detail.getMemberName() + "】原保单信息有误,当前申请不支持减保处理!");
                    }
                    //减保业务 使用的减保金额
                    ApplyChangeCyclePriceDTO applyChangeCyclePriceDTO_reduce = new ApplyChangeCyclePriceDTO();
                    applyChangeCyclePriceDTO_reduce.setApplyId(update.getApplyId());
                    applyChangeCyclePriceDTO_reduce.setValidTime(DateUtil.getMontageDate(update.getApplyStartTime(), 2));
                    //减保 需要减少的金额 即 退保需要退回的费用
                    CountCyclePriceVO countCyclePriceVO_reduce = this.getChangeCountCyclePriceVO(applyChangeCyclePriceDTO_reduce);
                    BigDecimal updateFee = countCyclePriceVO_reduce.getCyclePrice().multiply(new BigDecimal(-1));
                    //当审批时间 大于 申请的时间时 计算实际减少金额 因为已扣金额会大于 应扣金额
                    BigDecimal updateCurrentFee = BigDecimal.ZERO;
                    if (DateUtil.daysBetweenDates(DateUtil.getMontageDate(new Date(), 2),update.getApplyStartTime()) > 0) {
                        applyChangeCyclePriceDTO_reduce.setValidTime(DateUtil.getMontageDate(new Date(), 2));
                        //获取 大于审批日期导致 多减的金额
                        CountCyclePriceVO timeoutCountCyclePriceVOReduce = this.getChangeCountCyclePriceVO(applyChangeCyclePriceDTO_reduce);
                        updateCurrentFee = timeoutCountCyclePriceVOReduce.getCyclePrice().subtract(countCyclePriceVO_reduce.getCyclePrice());
                    }
                    applyDetailJoinMapper.update(null, new UpdateWrapper<ApplyDetail>().lambda()
                            .setSql(" fee = ifnull(fee,0)+" + updateFee)
                            .setSql(" current_fee = " + updateCurrentFee)
                            .set(insuranceApply.getStartTime().compareTo(update.getApplyStartTime())!=0,ApplyDetail::getEndTime, DateUtil.getMontageDate(update.getApplyStartTime(), 3))
                            .set(insuranceApply.getStartTime().compareTo(update.getApplyStartTime())==0,ApplyDetail::getEndTime, DateUtil.getMontageDate(update.getApplyStartTime(), 2))
                            .set(ApplyDetail::getEditor, update.getEditor())
                            .set(ApplyDetail::getEditDate, update.getEditDate())
                            .eq(ApplyDetail::getId, oldModel.getId())
                    );
                    totalFee = totalFee.add(updateFee);
                    currentFee = currentFee.add(updateCurrentFee);
                    //修改 员工投保明细记录 历史数据
                    memberInsuranceJoinMapper.update(null, new UpdateWrapper<MemberInsurance>().lambda()
                            .setSql(" fee = ifnull(fee,0)+" + updateFee)
                            .set(insuranceApply.getStartTime().compareTo(update.getApplyStartTime())!=0,MemberInsurance::getEndTime,DateUtil.getMontageDate(update.getApplyStartTime(), 3))
                            .set(insuranceApply.getStartTime().compareTo(update.getApplyStartTime())==0,MemberInsurance::getEndTime,DateUtil.getMontageDate(update.getApplyStartTime(), 2))
                            .set(MemberInsurance::getStartTime, update.getApplyStartTime())
                            .eq(MemberInsurance::getRelationId, oldModel.getId())
                    );
                    //修改业务明细行数据实际批单日期
                    applyChangeDetailJoinMapper.update(null,new UpdateWrapper<ApplyChagneDetail>().lambda()
                            .set(ApplyChagneDetail::getFee,updateFee)
                            .set(ApplyChagneDetail::getEndTime,DateUtil.getMontageDate(update.getApplyStartTime(), 3))
                            .eq(ApplyChagneDetail::getId,detail.getId())
                    );
            }
            member.setApplyId(update.getApplyId());
            member.setDuId(detail.getDuId());
            member.setWorktypeId(detail.getWorktypeId());
            member.setStartTime(detail.getStartTime());
            member.setEndTime(detail.getEndTime());
            memberMapper.updateById(member);
            if (memberInsuranceList != null && memberInsuranceList.size() > 0) {
                memberInsuranceJoinMapper.insertBatchSomeColumn(memberInsuranceList);
            }
        }
        if (totalFee.compareTo(new BigDecimal(0)) != 0) {
            //如果保单金额发生编码,更新总保单金额
            insuranceApplyMapper.update(null, new UpdateWrapper<InsuranceApply>().lambda()
                    .setSql(" fee = ifnull(fee,0)+" + totalFee)
                    .setSql(" current_fee = ifnull(current_fee,0)+" + currentFee)
                    .set(InsuranceApply::getEditor, update.getEditor())
                    .set(InsuranceApply::getEditDate, update.getEditDate())
                    .eq(InsuranceApply::getId, update.getApplyId())
            );
            update.setFee(totalFee);
        }
    }
    /**
     * 平台退回投保
     * @param param
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class,BusinessException.class})
    public Integer dealBackApply(ApplyChange param) {
        if(param.getId() == null ||StringUtils.isBlank(param.getCheckInfo())){
            throw  new BusinessException(ResponseStatus.BAD_REQUEST);
        }
        ApplyChange model = applyChangeMapper.selectById(param.getId());
        if(model == null ||!Constants.equalsInteger(model.getIsdeleted(),Constants.ZERO)){
            throw  new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        InsuranceApply insuranceApply = insuranceApplyMapper.selectById(model.getApplyId());
        if(Objects.isNull(insuranceApply)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        if(insuranceApply.getIsdeleted().equals(Constants.ONE)){
            throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(),"数据已删除,无法进行该操作");
        }
        Solutions solutions = solutionsMapper.selectById(insuranceApply.getSolutionId());
        if(Objects.isNull(solutions)){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"未查询到方案信息");
        }
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        Constants.ApplyLogType applyLogType = null;
        String info = "";
        ApplyChange update = new ApplyChange();
        Constants.NoticeType noticeType = Constants.NoticeType.FOUR;
        if(param.getDealBackApply() ==1){
            //如果是驳回,只能可驳回已签章状态下的退回申请状态进行操作
            if(!(Constants.equalsInteger(model.getStatus(),Constants.ApplyChangeStatus.RETURN_APPLY_SIGNATURE.getKey())
                    ||Constants.equalsInteger(model.getStatus(),Constants.ApplyChangeStatus.RETURN_APPLY_UPLOAD.getKey()))
            ){
                throw  new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"对不起,该申请状态已流转,当前不支持该操作~");
            }
            if(Constants.equalsInteger(model.getStatus(),Constants.ApplyChangeStatus.RETURN_APPLY_SIGNATURE.getKey())){
                update.setStatus(Constants.ApplyChangeStatus.SIGNATURE.getKey());
            }else {
                update.setStatus(Constants.ApplyChangeStatus.UPLOAD.getKey());
            }
            applyLogType = Constants.ApplyLogType.CA_PALTFORM_REFUSE_APPLY;
            info = applyLogType.getInfo();
            info = info.replace("${param}", param.getCheckInfo());
            noticeType = Constants.NoticeType.FIVE;
        }else{
            //如果是同意,两种申请退回状态都可操作
            if(!(Constants.equalsInteger(model.getStatus(),Constants.ApplyChangeStatus.RETURN_APPLY_SIGNATURE.getKey())
                    ||Constants.equalsInteger(model.getStatus(),Constants.ApplyChangeStatus.RETURN_APPLY_UPLOAD.getKey()))){
                throw  new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"对不起,该申请状态已流转,当前不支持该操作~");
            }
            update.setStatus(Constants.ApplyChangeStatus.PLATFORM_AGREE.getKey());
            applyLogType = Constants.ApplyLogType.CA_PLATFORM_AGREE_BACK_APPLY;
        }
        update.setEditDate(new Date());
        update.setEditor(user.getId());
        //同意退回,直接回到最初状态,如果驳回退回申请,则保单状态回到待上传保险单
        update.setCheckDate(update.getEditDate());
        update.setCheckInfo(param.getCheckInfo());
        update.setCheckUserId(user.getId());
        update.setId(model.getId());
        applyChangeMapper.updateById(update);
        //存储待办信息
        Constants.NoticeObjectType noticeObjectType = Constants.NoticeObjectType.APPLY_CHANGE;
        if(model.getType().equals(Constants.ONE)){
            noticeObjectType = Constants.NoticeObjectType.CHANGE_FACTORY;
        }
        //删除其他待办
        noticesMapper.delete(new QueryWrapper<Notices>().lambda().eq(Notices::getObjType,noticeObjectType.getKey()).eq(Notices::getObjId,model.getId()));
        Notices notices = new Notices(noticeObjectType,Constants.ONE,model.getId(),solutions.getName(),
                insuranceApply.getCompanyId(), noticeType);
        noticesMapper.insert(notices);
        ApplyLog log = new ApplyLog(update,applyLogType.getName(),info,update.getId(),applyLogType.getKey(),JSONObject.toJSONString(model), JSONObject.toJSONString(update));
        applyLogMapper.insert(log);
        return  1;
    }
    @Override
    @Transactional(rollbackFor = {Exception.class,BusinessException.class})
    public Integer create(ApplyChange applyChange) {
        if (Objects.isNull(applyChange)
                || Objects.isNull(applyChange.getApplyId())
                || Objects.isNull(applyChange.getValidTime())
                || Objects.isNull(applyChange.getType())
                || !(applyChange.getType().equals(Constants.ZERO) || applyChange.getType().equals(Constants.ONE))
        ) {
            throw new BusinessException(ResponseStatus.BAD_REQUEST);
        }
        LoginUserInfo loginUserInfo = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if (!loginUserInfo.getType().equals(Constants.ONE)) {
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "用户类型错误:非企业用户无法进行该操作");
        }
        InsuranceApply insuranceApply = insuranceApplyMapper.selectById(applyChange.getApplyId());
        if (Objects.isNull(insuranceApply)) {
            throw new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        if (!Constants.equalsInteger(insuranceApply.getStatus(),Constants.InsuranceApplyStatus.UPLOAD_INSURANCE.getKey())) {
            throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(), "保单状态错误");
        }
        if (DateUtil.compareDate(insuranceApply.getEndTime(),new Date()) >= Constants.ZERO
        ) {
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "保单已过保,无法进行该操作");
        }
        Solutions solutions = solutionsMapper.selectById(insuranceApply.getSolutionId());
        if(Objects.isNull(solutions)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"未查询到保险方案");
        }
        if(solutions.getDataType().equals(Constants.ONE)){
            solutions = solutionsMapper.selectOne(new QueryWrapper<Solutions>().lambda().eq(Solutions::getBaseId,solutions.getBaseId()).eq(Solutions::getDataType,Constants.TWO).last("limit 1"));
            if(Objects.isNull(solutions)){
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"未查询到方案最新版本信息");
            }
        }
        CompanySolution companySolution = companySolutionMapper.selectOne(new QueryWrapper<CompanySolution>().lambda()
                .eq(CompanySolution::getCompanyId,loginUserInfo.getCompanyId())
                .eq(CompanySolution::getSolutionBaseId,solutions.getBaseId())
                .eq(CompanySolution::getIsdeleted,Constants.ZERO)
                .last(" limit 1 ")
        );
        if(Objects.isNull(companySolution)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"未查询到企业分配保险方案信息");
        }
        //申请时间必须处于保单的时间范围内
        if (!(DateUtil.compareDate( insuranceApply.getStartTime(),applyChange.getValidTime()) >= Constants.ZERO
                && DateUtil.compareDate( applyChange.getValidTime(),insuranceApply.getEndTime()) >= Constants.ZERO)) {
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "申请日期未处于保单日期内,无法进行该操作");
        }
        //查询保单下是否存在进行中的加减保/换厂单据
        if(applyChangeMapper.selectCount(new QueryWrapper<ApplyChange>().lambda()
                .eq(ApplyChange::getApplyId,insuranceApply.getId())
                .notIn(ApplyChange::getStatus,Constants.ApplyChangeStatus.APPROVE.getKey(),Constants.ApplyChangeStatus.CLOSE.getKey())
        )>Constants.ZERO){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "存在进行中的加减保/换厂申请");
        };
        applyChange.setCreateDate(new Date());
        applyChange.setCreator(loginUserInfo.getId());
        applyChange.setEditor(loginUserInfo.getId());
        applyChange.setEditDate(new Date());
        applyChange.setIsdeleted(Constants.ZERO);
        applyChange.setApplyStartTime(applyChange.getValidTime());
        applyChange.setStatus(Constants.ZERO);
        applyChangeMapper.insert(applyChange);
        BigDecimal fee  = this.dealApplyChangeData(applyChange,insuranceApply,companySolution,solutions,loginUserInfo,BigDecimal.ZERO);
        ApplyChange applyChangeFee = new ApplyChange();
        applyChangeFee.setId(applyChange.getId());
        applyChangeFee.setFee(fee);
        applyChangeMapper.updateById(applyChangeFee);
        Constants.ApplyLogType applyLogType = Constants.ApplyLogType.CA_COMPANY_COMMIT;
        ApplyLog log = new ApplyLog(applyChange,applyLogType.getName(),"",applyChange.getId(),applyLogType.getKey(), null, null);
        applyLogMapper.insert(log);
        return applyChange.getId();
    }
    @Override
    @Transactional(rollbackFor = {Exception.class,BusinessException.class})
    public Integer update(ApplyChange applyChange) {
        if (Objects.isNull(applyChange)
                || Objects.isNull(applyChange.getId())
                || Objects.isNull(applyChange.getApplyId())
                || Objects.isNull(applyChange.getValidTime())
                || Objects.isNull(applyChange.getType())
                || !(applyChange.getType().equals(Constants.ZERO) || applyChange.getType().equals(Constants.ONE))
        ) {
            throw new BusinessException(ResponseStatus.BAD_REQUEST);
        }
        LoginUserInfo loginUserInfo = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if (!loginUserInfo.getType().equals(Constants.ONE)) {
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "用户类型错误:非企业用户无法进行该操作");
        }
        ApplyChange dbApplyChange = applyChangeMapper.selectById(applyChange.getId());
        if(Objects.isNull(dbApplyChange)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        if(! (dbApplyChange.getStatus().equals(Constants.ApplyChangeStatus.PLATFORM_AGREE.getKey())
        || dbApplyChange.getStatus().equals(Constants.ApplyChangeStatus.PALTFORM_CHECK_PASS_NO.getKey()) )
        ){
            throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(), "业务保申请单状态错误");
        }
        InsuranceApply insuranceApply = insuranceApplyMapper.selectById(applyChange.getApplyId());
        if (Objects.isNull(insuranceApply)) {
            throw new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        if (!Constants.equalsInteger(insuranceApply.getStatus(),Constants.InsuranceApplyStatus.UPLOAD_INSURANCE.getKey())) {
            throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(), "保单状态错误");
        }
        if (DateUtil.compareDate(insuranceApply.getEndTime(),new Date()) >= Constants.ZERO
        ) {
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "保单已过保,无法进行该操作");
        }
        Solutions solutions = solutionsMapper.selectById(insuranceApply.getSolutionId());
        if(Objects.isNull(solutions)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"未查询到保险方案");
        }
        if(solutions.getDataType().equals(Constants.ONE)){
            solutions = solutionsMapper.selectOne(new QueryWrapper<Solutions>().lambda().eq(Solutions::getBaseId,solutions.getBaseId()).eq(Solutions::getDataType,Constants.TWO).last("limit 1"));
            if(Objects.isNull(solutions)){
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"未查询到方案最新版本信息");
            }
        }
        CompanySolution companySolution = companySolutionMapper.selectOne(new QueryWrapper<CompanySolution>().lambda()
                .eq(CompanySolution::getCompanyId,loginUserInfo.getCompanyId())
                .eq(CompanySolution::getSolutionBaseId,solutions.getBaseId())
                .eq(CompanySolution::getIsdeleted,Constants.ZERO)
                .last(" limit 1 ")
        );
        if(Objects.isNull(companySolution)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"未查询到企业分配保险方案信息");
        }
        //申请时间必须处于保单的时间范围内
        if (!(DateUtil.compareDate( insuranceApply.getStartTime(),applyChange.getValidTime()) >= Constants.ZERO
                && DateUtil.compareDate( applyChange.getValidTime(),insuranceApply.getEndTime()) >= Constants.ZERO)) {
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "申请日期未处于保单日期内,无法进行该操作");
        }
        //查询保单下是否存在进行中的加减保/换厂单据
        if(applyChangeMapper.selectCount(new QueryWrapper<ApplyChange>().lambda()
                .eq(ApplyChange::getApplyId,insuranceApply.getId())
                .ne(ApplyChange::getId,applyChange.getId())
                .notIn(ApplyChange::getStatus,Constants.ApplyChangeStatus.APPROVE.getKey(),Constants.ApplyChangeStatus.CLOSE.getKey())
        )>Constants.ZERO){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "存在进行中的加减保/换厂申请");
        };
        applyChange.setEditDate(new Date());
        applyChange.setEditor(loginUserInfo.getId());
        applyChange.setApplyStartTime(applyChange.getValidTime());
        applyChange.setStatus(Constants.ZERO);
        //删除历史数据
        applyChagneDetailJoinMapper.delete(new QueryWrapper<ApplyChagneDetail>().lambda().eq(ApplyChagneDetail::getApplyChangeId,applyChange.getId()));
        BigDecimal fee = this.dealApplyChangeData(applyChange,insuranceApply,companySolution,solutions,loginUserInfo,BigDecimal.ZERO);
        applyChange.setFee(fee);
        applyChangeMapper.updateById(applyChange);
        Constants.ApplyLogType applyLogType = Constants.ApplyLogType.CA_UPLOAD_AGAIN;
        String info =applyLogType.getInfo();
        info = info.replace("${param}", "");
        ApplyLog log = new ApplyLog(applyChange,applyLogType.getName(),info,applyChange.getId(),applyLogType.getKey(), null, null);
        applyLogMapper.insert(log);
        return applyChange.getId();
    }
    public BigDecimal dealApplyChangeData(ApplyChange applyChange,InsuranceApply insuranceApply,CompanySolution companySolution,Solutions solutions,LoginUserInfo loginUserInfo,BigDecimal fee){
        //查询保险方案下的所有派遣单位
        List<DuSolution>  duSolutionList = duSolutionJoinMapper.selectJoinList(DuSolution.class,new MPJLambdaWrapper<DuSolution>()
                .selectAll(DuSolution.class)
                .innerJoin(DispatchUnit.class,DispatchUnit::getId,DuSolution::getDispatchUnitId)
                .eq(DispatchUnit::getCompanyId,insuranceApply.getCompanyId())
                .eq(DispatchUnit::getIsdeleted,Constants.ZERO)
                .eq(DispatchUnit::getUnitStatus,Constants.ONE)
                .eq(DuSolution::getIsdeleted,Constants.ZERO)
                .eq(DuSolution::getStatus,Constants.ONE)
                .eq(DuSolution::getSolutionId,companySolution.getSolutionId()));
        if(!CollectionUtils.isNotEmpty(duSolutionList)){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(),"数据异常:保险方案下未查询到派遣单位");
        }
        //查询所有派遣单位下的工种
        List<Integer> duSolutionIdList = duSolutionList.stream().map(i->i.getId()).collect(Collectors.toList());
        List<DuWorktype> duWorktypeList = duWorktypeMapper.selectList(new QueryWrapper<DuWorktype>().lambda()
                .eq(DuWorktype::getIsdeleted,Constants.ZERO)
                .eq(DuWorktype::getStatus,Constants.ONE)
                .in(DuWorktype::getDuSolutionId,duSolutionIdList));
        if (!CollectionUtils.isNotEmpty(duWorktypeList)) {
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "数据异常:保险方案下未查询到工种信息");
        }
        ApplyChangeCyclePriceDTO applyChangeCyclePriceDTO = new ApplyChangeCyclePriceDTO();
        applyChangeCyclePriceDTO.setApplyId(insuranceApply.getId());
        //加保数据
        List<ApplyChagneDetail> addDetailList = applyChange.getAddDetailList();
        if (CollectionUtils.isNotEmpty(addDetailList)) {
            if(companySolution.getCanAdd().equals(Constants.ZERO)){
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "该企业分配保险方案无法进行加保");
            }
            //验证是否存在重复数据
            List<String> idcarNo = addDetailList.stream().map(m->m.getIdcardNo()).collect(Collectors.toList());
            Set<String> set = new HashSet<>(idcarNo);
            if(idcarNo.size() != set.size()){
                throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(),"对不起,人员录入数据存在相同数据!");
            }
            //加保明细数据 计算金额  根据批单时间 计算
            applyChangeCyclePriceDTO.setValidTime(DateUtil.getMontageDate(applyChange.getValidTime(),1));
            CountCyclePriceVO countCyclePriceVO =  this.getChangeCountCyclePriceVO(applyChangeCyclePriceDTO);
            BigDecimal detailFee = countCyclePriceVO.getCyclePrice();
            this.addChangeDetail(applyChange,addDetailList,duWorktypeList,duSolutionList,insuranceApply,solutions,loginUserInfo,detailFee);
            fee = addDetailList.stream().map(ApplyChagneDetail::getFee).reduce(BigDecimal.ZERO,BigDecimal::add);
        }
        //减保数据
        List<ApplyChagneDetail> delDetailList = applyChange.getDelDetailList();
        if (CollectionUtils.isNotEmpty(delDetailList)) {
            //验证是否存在重复数据
            List<String> idcarNo = delDetailList.stream().map(m->m.getIdcardNo()).collect(Collectors.toList());
            Set<String> set = new HashSet<>(idcarNo);
            if(idcarNo.size() != set.size()){
                throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(),"对不起,人员录入数据存在相同数据!");
            }
            if(companySolution.getCanReduce().equals(Constants.ZERO)){
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "该企业分配保险方案无法进行减保");
            }
            //减保明细数据 计算金额  根据批单时间 前一天 计算
            applyChangeCyclePriceDTO.setValidTime(DateUtil.getMontageDate(applyChange.getValidTime(),2));
            CountCyclePriceVO countCyclePriceVO =  this.getChangeCountCyclePriceVO(applyChangeCyclePriceDTO);
            BigDecimal detailFee = countCyclePriceVO.getCyclePrice();
            this.delChangeDetail(applyChange,delDetailList,insuranceApply,solutions,loginUserInfo,detailFee,applyChangeCyclePriceDTO.getValidTime());
            fee = fee.add(delDetailList.stream().map(ApplyChagneDetail::getFee).reduce(BigDecimal.ZERO,BigDecimal::add));
        }
        //换厂业务
        List<ApplyChagneDetail> changeDetailList = applyChange.getChangeDetailList();
        if (CollectionUtils.isNotEmpty(changeDetailList)) {
            this.changeDetail(applyChange,changeDetailList,duWorktypeList,duSolutionList,loginUserInfo);
        }
        return fee;
    }
    public void saveApplyLog(ApplyChange applyChange,Constants.ApplyLogType applyLogType,String content){
        LoginUserInfo loginUserInfo = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        ApplyLog applyLog = new ApplyLog();
        applyLog.setCreateDate(new Date());
        applyLog.setCreator(loginUserInfo.getId());
        applyLog.setIsdeleted(Constants.ZERO);
        applyLog.setApplyId(applyChange.getApplyId());
        applyLog.setTitle(applyLogType.getName());
        if(StringUtils.isNotBlank(content)){
            applyLog.setContent(applyLogType.getInfo().replace("${param}",content));
        }
        applyLog.setObjType(applyLogType.getKey());
        applyLog.setObjId( applyChange.getId());
        applyLog.setStatus(applyChange.getStatus());
        applyLogMapper.insert(applyLog);
    }
    /**
     * 减保数据处理
     * @param applyChange
     * @param delDetailList
     * @param loginUserInfo
     */
    public void delChangeDetail(ApplyChange applyChange ,List<ApplyChagneDetail> delDetailList,InsuranceApply insuranceApply,Solutions solutions,
                                LoginUserInfo loginUserInfo,BigDecimal detailFee,Date endTime){
        for (ApplyChagneDetail applyChagneDetail : delDetailList) {
            if (Objects.isNull(applyChagneDetail.getMemberId())) {
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "减保人员【" + applyChagneDetail.getMemberName() + "】必填项缺失");
            }
            //查询减保人员是否存在 冲突的 保单明细数据
            if(applyDetailJoinMapper.selectCount(new QueryWrapper<ApplyDetail>()
                    .lambda()
                    .eq(ApplyDetail::getApplyId,applyChange.getApplyId())
                    .eq(ApplyDetail::getIdcardNo,applyChagneDetail.getIdcardNo())
                    .le(ApplyDetail::getStartTime,DateUtil.getMontageDate(applyChange.getApplyStartTime(),1))
                    .ge(ApplyDetail::getEndTime,DateUtil.getMontageDate(applyChange.getApplyStartTime(),3))
            )<=Constants.ZERO){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "当前保单下,减保人员【" + applyChagneDetail.getMemberName() + "】未查询到符合批单日期的数据");
            }
            Member member = memberMapper.selectById(applyChagneDetail.getMemberId());
            if (Objects.isNull(member)) {
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "减保人员【" + applyChagneDetail.getMemberName() + "】未查询到系统人员信息");
            }
            //查询员工是否存在  0待签署 1已签章 的此类业务保数据 同一主单下
            if (applyChagneDetailJoinMapper.selectJoinCount(
                    new MPJLambdaWrapper<ApplyChagneDetail>()
                            .leftJoin(ApplyChange.class, ApplyChange::getId, ApplyChagneDetail::getApplyChangeId)
                            .eq(ApplyChange::getApplyId,applyChange.getApplyId())
                            .eq(ApplyChagneDetail::getMemberId, applyChagneDetail.getMemberId())
                            .in(ApplyChange::getStatus, Constants.ZERO, Constants.ONE)
            ) > Constants.ZERO) {
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "减保人员【" + applyChagneDetail.getMemberName() + "】存在申请中的加减保/换厂单据");
            }
            //查询员工是在主单下 是否存在生效中的数据
            List<ApplyDetail> applyDetailList = applyDetailJoinMapper.selectList(new QueryWrapper<ApplyDetail>().lambda()
                    .eq(ApplyDetail::getApplyId, applyChange.getApplyId())
                    .eq(ApplyDetail::getMemberId, applyChagneDetail.getMemberId())
                    .le(ApplyDetail::getStartTime,DateUtil.getMontageDate(applyChange.getApplyStartTime(),1))
                    .ge(ApplyDetail::getEndTime,DateUtil.getMontageDate(applyChange.getApplyStartTime(),3))
                    .orderByDesc(ApplyDetail::getCreateDate));
            if (applyDetailList.size() > Constants.ONE) {
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "减保人员【" + applyChagneDetail.getMemberName() + "】保单信息异常,存在多条数据");
            }
            ApplyDetail applyDetail = applyDetailList.get(Constants.ZERO);
            if (applyChange.getValidTime().compareTo(applyDetail.getEndTime()) > 0) {
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "减保人员【" + applyChagneDetail.getMemberName() + "】保单保障日期至:【" + applyDetail.getEndTime() + "】无法通过本次申请");
            }
            applyChagneDetail.setCreateDate(new Date());
            applyChagneDetail.setCreator(loginUserInfo.getId());
            applyChagneDetail.setIsdeleted(Constants.ZERO);
            applyChagneDetail.setApplyChangeId(applyChange.getId());
            applyChagneDetail.setType(Constants.ONE);
            applyChagneDetail.setStartTime(applyDetail.getStartTime());
            applyChagneDetail.setEndTime(endTime);
            member.setApplyId(insuranceApply.getId());
            member.setDuId(applyChagneDetail.getDuId());
            member.setWorktypeId(applyChagneDetail.getWorktypeId());
            member.setStartTime(applyChagneDetail.getStartTime());
            member.setEndTime(applyChagneDetail.getEndTime());
            memberMapper.updateById(member);
            applyChagneDetail.setFee( detailFee.multiply(new BigDecimal(-1)));
            applyChagneDetailJoinMapper.insert(applyChagneDetail);
        }
    }
    /**
     * 加保数据处理
     * @param applyChange
     * @param addDetailList
     * @param duWorktypeList
     * @param duSolutionList
     * @param loginUserInfo
     */
    public void addChangeDetail(ApplyChange applyChange ,List<ApplyChagneDetail> addDetailList,
                                List<DuWorktype> duWorktypeList,List<DuSolution> duSolutionList,
                                InsuranceApply insuranceApply,Solutions solutions,LoginUserInfo loginUserInfo,BigDecimal detailFee){
        for (ApplyChagneDetail applyChagneDetail : addDetailList) {
            if (    Objects.isNull(applyChagneDetail.getDuId())
                    || Objects.isNull(applyChagneDetail.getWorktypeId())
                    || StringUtils.isBlank(applyChagneDetail.getIdcardNo())
            ) {
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "加保人员【" + applyChagneDetail.getMemberName() + "】必填项缺失");
            }
            //查询加保人员是否存在 冲突的 保单明细数据
            if(applyDetailJoinMapper.selectCount(new QueryWrapper<ApplyDetail>()
                    .lambda()
                    .eq(ApplyDetail::getApplyId,applyChange.getApplyId())
                    .eq(ApplyDetail::getIdcardNo,applyChagneDetail.getIdcardNo())
                    .le(ApplyDetail::getStartTime,DateUtil.getMontageDate(applyChange.getApplyStartTime(),1))
                            .ge(ApplyDetail::getEndTime,DateUtil.getMontageDate(insuranceApply.getEndTime(),2))
                    //.ge(ApplyDetail::getEndTime,DateUtil.getMontageDate(applyChange.getApplyStartTime(),3))
            )>Constants.ZERO){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "当前保单下,加保人员【" + applyChagneDetail.getMemberName() + "】存在日期冲突的数据");
            }
            applyChagneDetail.setCreateDate(new Date());
            applyChagneDetail.setCreator(loginUserInfo.getId());
            applyChagneDetail.setIsdeleted(Constants.ZERO);
            applyChagneDetail.setApplyChangeId(applyChange.getId());
            applyChagneDetail.setStartTime(DateUtil.getMontageDate(applyChange.getApplyStartTime(),1));
            applyChagneDetail.setEndTime(DateUtil.getMontageDate(insuranceApply.getEndTime(),2));
            applyChagneDetail.setType(Constants.ZERO);
            Member member = new Member();
            if(Objects.isNull(applyChagneDetail.getMemberId())){
                //查询是否存在该用户
                member = memberMapper.selectOne(new QueryWrapper<Member>().lambda()
                        .eq(Member::getCompanyId,insuranceApply.getCompanyId())
                        .eq(Member::getIsdeleted,Constants.ZERO)
                        .eq(Member::getIdcardNo,applyChagneDetail.getIdcardNo())
                        .last(" limit 1")
                );
                if(Objects.isNull(member)){
                    member = new Member();
                    member.setCreateDate(new Date());
                    member.setCreator(loginUserInfo.getId());
                    member.setIsdeleted(Constants.ZERO);
                    member.setName(applyChagneDetail.getMemberName());
                    member.setCompanyId(insuranceApply.getCompanyId());
                    member.setSex(Constants.getSexByIdCard(applyChagneDetail.getIdcardNo()));
                    member.setIdcardNo(applyChagneDetail.getIdcardNo());
                    member.setApplyId(insuranceApply.getId());
                    member.setDuId(applyChagneDetail.getDuId());
                    member.setWorktypeId(applyChagneDetail.getWorktypeId());
                    member.setStartTime(applyChagneDetail.getStartTime());
                    member.setEndTime(applyChagneDetail.getEndTime());
                    memberMapper.insert(member);
                }else{
                    member.setApplyId(insuranceApply.getId());
                    member.setDuId(applyChagneDetail.getDuId());
                    member.setWorktypeId(applyChagneDetail.getWorktypeId());
                    member.setStartTime(applyChagneDetail.getStartTime());
                    member.setEndTime(applyChagneDetail.getEndTime());
                    memberMapper.updateById(member);
                }
            }else{
                member = memberMapper.selectById(applyChagneDetail.getMemberId());
                if(Objects.isNull(member)){
                    throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "加保人员【" + applyChagneDetail.getMemberName() + "】未查询到系统人员信息");
                }
                member.setApplyId(insuranceApply.getId());
                member.setDuId(applyChagneDetail.getDuId());
                member.setWorktypeId(applyChagneDetail.getWorktypeId());
                member.setStartTime(applyChagneDetail.getStartTime());
                member.setEndTime(applyChagneDetail.getEndTime());
                memberMapper.updateById(member);
            }
            //根据员工身份证进行判断年龄
            long age = Constants.getAgeByIdCard(member.getIdcardNo());
            if(Objects.isNull(age)
                    || age > solutions.getMaxAge()
                    || age < solutions.getMinAge()){
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"【"+applyChagneDetail.getMemberName()+"】员工年龄超出方案配置 方案配置【"+solutions.getMinAge()+" - "+solutions.getMaxAge()+"】存在异常数据!");
            }
            //查询员工是否存在  0待签署 1已签章 的此类业务保数据 同一主单下
            if (applyChagneDetailJoinMapper.selectJoinCount(
                    new MPJLambdaWrapper<ApplyChagneDetail>()
                            .leftJoin(ApplyChange.class, ApplyChange::getId, ApplyChagneDetail::getApplyChangeId)
                            .eq(ApplyChagneDetail::getMemberId, applyChagneDetail.getMemberId())
                            .eq(ApplyChange::getApplyId,applyChange.getApplyId())
                            .in(ApplyChange::getStatus, Constants.ZERO, Constants.ONE)
            ) > Constants.ZERO) {
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "加保人员【" + applyChagneDetail.getMemberName() + "】存在申请中的加减保/换厂单据");
            }
            //查询员工是在主单下 是否存在生效中的数据
            if(!Objects.isNull(applyChagneDetail.getMemberId())){
                if (applyDetailJoinMapper.selectCount(new QueryWrapper<ApplyDetail>().lambda()
                        .eq(ApplyDetail::getApplyId, applyChange.getApplyId())
                        .eq(ApplyDetail::getMemberId, applyChagneDetail.getMemberId())
                        .le(ApplyDetail::getStartTime, "now()")
                        .ge(ApplyDetail::getEndTime, "now()")
                ) > Constants.ZERO) {
                    throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "加保人员【" + applyChagneDetail.getMemberName() + "】存在保障中的保单信息,无法进行加保");
                }
            }
            //验证派遣单位信息 与工种信息 是否存在
            if (duSolutionList.stream().filter(d -> d.getDispatchUnitId().equals(applyChagneDetail.getDuId())).collect(Collectors.toList()).size() <= Constants.ZERO) {
                throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(), "【" + applyChagneDetail.getMemberName() + "】员工派遣单位未查询到!");
            }
            if (duWorktypeList.stream().filter(d ->  d.getWorkTypeId().equals(applyChagneDetail.getWorktypeId()))
                    .collect(Collectors.toList()).size() <= Constants.ZERO) {
                throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(), "【" + applyChagneDetail.getMemberName() + "】员工工种信息未查询到!");
            }
            applyChagneDetail.setMemberId(member.getId());
            applyChagneDetail.setFee(detailFee);
            applyChagneDetailJoinMapper.insert(applyChagneDetail);
        }
    }
    /**
     * 换厂业务
     * @param applyChange
     * @param duWorktypeList
     * @param duSolutionList
     * @param changeDetailList
     * @param loginUserInfo
     */
    public void changeDetail(ApplyChange applyChange ,List<ApplyChagneDetail> changeDetailList,List<DuWorktype> duWorktypeList,List<DuSolution> duSolutionList,LoginUserInfo loginUserInfo){
        for (ApplyChagneDetail applyChagneDetail : changeDetailList) {
            if (Objects.isNull(applyChagneDetail.getMemberId())
                    || Objects.isNull(applyChagneDetail.getOldDuId())
                    || Objects.isNull(applyChagneDetail.getOldWorktypeId())
                    || Objects.isNull(applyChagneDetail.getDuId())
                    || Objects.isNull(applyChagneDetail.getWorktypeId())
            ) {
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "换厂人员【" + applyChagneDetail.getMemberName() + "】必填项缺失");
            }
            //查询换厂人员是否存在  有效的保单明细数据
            if(applyDetailJoinMapper.selectCount(new QueryWrapper<ApplyDetail>()
                    .lambda()
                    .eq(ApplyDetail::getApplyId,applyChange.getApplyId())
                    .eq(ApplyDetail::getIdcardNo,applyChagneDetail.getIdcardNo())
                    .le(ApplyDetail::getStartTime,DateUtil.getMontageDate(applyChange.getApplyStartTime(),1))
                    .ge(ApplyDetail::getEndTime,DateUtil.getMontageDate(applyChange.getApplyStartTime(),1))
            )<=Constants.ZERO){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "当前保单下,换厂人员【" + applyChagneDetail.getMemberName() + "】未查询到符合批单日期的数据");
            }
            Member member = memberMapper.selectById(applyChagneDetail.getMemberId());
            if (Objects.isNull(member)) {
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "换厂人员【" + applyChagneDetail.getMemberName() + "】未查询到系统人员信息");
            }
            //查询员工是否存在  0待签署 1已签章 的此类业务保数据 同一主单下
            if (applyChagneDetailJoinMapper.selectJoinCount(
                    new MPJLambdaWrapper<ApplyChagneDetail>()
                            .leftJoin(ApplyChange.class, ApplyChange::getId, ApplyChagneDetail::getApplyChangeId)
                            .eq(ApplyChagneDetail::getMemberId, applyChagneDetail.getMemberId())
                            .eq(ApplyChange::getApplyId, applyChange.getApplyId())
                            .in(ApplyChange::getStatus, Constants.ZERO, Constants.ONE)
            ) > Constants.ZERO) {
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "换厂人员【" + applyChagneDetail.getMemberName() + "】存在申请中的加减保/换厂单据");
            }
            //查询员工是在主单下 是否存在生效中的数据
            List<ApplyDetail>  applyDetailList = applyDetailJoinMapper.selectList(new QueryWrapper<ApplyDetail>().lambda()
                    .eq(ApplyDetail::getApplyId, applyChange.getApplyId())
                    .eq(ApplyDetail::getMemberId, applyChagneDetail.getMemberId())
                    .le(ApplyDetail::getStartTime,DateUtil.getMontageDate(applyChange.getApplyStartTime(),1))
                    .ge(ApplyDetail::getEndTime,DateUtil.getMontageDate(applyChange.getApplyStartTime(),1)));
            if(applyDetailList.size()>Constants.ONE){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "换厂人员【" + applyChagneDetail.getMemberName() + "】保单信息异常,存在多条数据");
            }else if(applyDetailList.size()==Constants.ZERO){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "换厂人员【" + applyChagneDetail.getMemberName() + "】未查询到投保记录");
            }
            ApplyDetail applyDetail = applyDetailList.get(Constants.ZERO);
            if(applyChange.getValidTime().compareTo( applyDetail.getEndTime())>0){
                throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "换厂人员【" + applyChagneDetail.getMemberName() + "】保单保障日期至:【"+DateUtil.getDate(applyDetail.getEndTime(),"yyyy-MM-dd HH:mm:ss")+"】无法通过本次申请");
            }
            //验证派遣单位信息 与工种信息 是否存在
            if (duSolutionList.stream().filter(d -> d.getDispatchUnitId().equals(applyChagneDetail.getDuId())).collect(Collectors.toList()).size() <= Constants.ZERO) {
                throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(), "换厂人员【" + applyChagneDetail.getMemberName() + "】员工派遣单位未查询到!");
            }
            if (duWorktypeList.stream().filter(d ->  d.getWorkTypeId().equals(applyChagneDetail.getWorktypeId()))
                    .collect(Collectors.toList()).size() <= Constants.ZERO) {
                throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(), "换厂人员【" + applyChagneDetail.getMemberName() + "】员工工种信息未查询到!");
            }
            if(applyChagneDetail.getOldDuId().equals(applyChagneDetail.getDuId())
            && applyChagneDetail.getOldWorktypeId().equals(applyChagneDetail.getWorktypeId())){
                throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(), "换厂人员【" + applyChagneDetail.getMemberName() + "】换厂数据相同!");
            }
            applyChagneDetail.setCreateDate(new Date());
            applyChagneDetail.setCreator(loginUserInfo.getId());
            applyChagneDetail.setIsdeleted(Constants.ZERO);
            applyChagneDetail.setApplyChangeId(applyChange.getId());
            applyChagneDetail.setType(Constants.TWO);
            applyChagneDetail.setStartTime(applyDetail.getStartTime());
            applyChagneDetail.setEndTime(applyDetail.getEndTime());
            applyChagneDetailJoinMapper.insert(applyChagneDetail);
            member.setApplyId(applyChange.getApplyId());
            member.setDuId(applyChagneDetail.getDuId());
            member.setWorktypeId(applyChagneDetail.getWorktypeId());
            member.setStartTime(applyChagneDetail.getStartTime());
            member.setEndTime(applyChagneDetail.getEndTime());
            memberMapper.updateById(member);
        }
    }
    @Override
@@ -87,57 +1386,28 @@
    @Override
    public PageData<ApplyChange> findPage(PageWrap<ApplyChange> pageWrap) {
        IPage<ApplyChange> page = new Page<>(pageWrap.getPage(), pageWrap.getCapacity());
        QueryWrapper<ApplyChange> queryWrapper = new QueryWrapper<>();
        MPJLambdaWrapper<ApplyChange> queryWrapper = new MPJLambdaWrapper<>();
        Utils.MP.blankToNull(pageWrap.getModel());
        if (pageWrap.getModel().getId() != null) {
            queryWrapper.lambda().eq(ApplyChange::getId, pageWrap.getModel().getId());
        }
        if (pageWrap.getModel().getCreator() != null) {
            queryWrapper.lambda().eq(ApplyChange::getCreator, pageWrap.getModel().getCreator());
        }
        if (pageWrap.getModel().getCreateDate() != null) {
            queryWrapper.lambda().ge(ApplyChange::getCreateDate, Utils.Date.getStart(pageWrap.getModel().getCreateDate()));
            queryWrapper.lambda().le(ApplyChange::getCreateDate, Utils.Date.getEnd(pageWrap.getModel().getCreateDate()));
        }
        if (pageWrap.getModel().getEditor() != null) {
            queryWrapper.lambda().eq(ApplyChange::getEditor, pageWrap.getModel().getEditor());
        }
        if (pageWrap.getModel().getEditDate() != null) {
            queryWrapper.lambda().ge(ApplyChange::getEditDate, Utils.Date.getStart(pageWrap.getModel().getEditDate()));
            queryWrapper.lambda().le(ApplyChange::getEditDate, Utils.Date.getEnd(pageWrap.getModel().getEditDate()));
        }
        if (pageWrap.getModel().getIsdeleted() != null) {
            queryWrapper.lambda().eq(ApplyChange::getIsdeleted, pageWrap.getModel().getIsdeleted());
        }
        if (pageWrap.getModel().getRemark() != null) {
            queryWrapper.lambda().eq(ApplyChange::getRemark, pageWrap.getModel().getRemark());
        }
        if (pageWrap.getModel().getSortnum() != null) {
            queryWrapper.lambda().eq(ApplyChange::getSortnum, pageWrap.getModel().getSortnum());
        }
        if (pageWrap.getModel().getApplyId() != null) {
            queryWrapper.lambda().eq(ApplyChange::getApplyId, pageWrap.getModel().getApplyId());
        }
        if (pageWrap.getModel().getCode() != null) {
            queryWrapper.lambda().eq(ApplyChange::getCode, pageWrap.getModel().getCode());
        }
        if (pageWrap.getModel().getApplyStartTime() != null) {
            queryWrapper.lambda().ge(ApplyChange::getApplyStartTime, Utils.Date.getStart(pageWrap.getModel().getApplyStartTime()));
            queryWrapper.lambda().le(ApplyChange::getApplyStartTime, Utils.Date.getEnd(pageWrap.getModel().getApplyStartTime()));
        }
        if (pageWrap.getModel().getStatus() != null) {
            queryWrapper.lambda().eq(ApplyChange::getStatus, pageWrap.getModel().getStatus());
        }
        if (pageWrap.getModel().getValidTime() != null) {
            queryWrapper.lambda().ge(ApplyChange::getValidTime, Utils.Date.getStart(pageWrap.getModel().getValidTime()));
            queryWrapper.lambda().le(ApplyChange::getValidTime, Utils.Date.getEnd(pageWrap.getModel().getValidTime()));
        }
        if (pageWrap.getModel().getValidCode() != null) {
            queryWrapper.lambda().eq(ApplyChange::getValidCode, pageWrap.getModel().getValidCode());
        }
        if (pageWrap.getModel().getType() != null) {
            queryWrapper.lambda().eq(ApplyChange::getType, pageWrap.getModel().getType());
        }
        ApplyChange model = pageWrap.getModel() ;
        queryWrapper
                .selectAll(ApplyChange.class)
                .selectAs(InsuranceApply::getCode,ApplyChange::getApplyCode)
                .select("( select count(1) from apply_chagne_detail ad where t.id = ad.APPLY_CHANGE_ID and ad.TYPE = 0  )",ApplyChange::getAddNum)
                .select("( select count(1) from apply_chagne_detail ad where t.id = ad.APPLY_CHANGE_ID and ad.TYPE = 1  )",ApplyChange::getDelNum)
                .select("( select count(1) from apply_chagne_detail ad where t.id = ad.APPLY_CHANGE_ID and ad.TYPE = 2  )",ApplyChange::getChangeNum)
                .select("( select ifnull(sum(ad.FEE),0) from apply_chagne_detail ad where t.id = ad.APPLY_CHANGE_ID  )",ApplyChange::getChangeMoney)
                .leftJoin(InsuranceApply.class,InsuranceApply::getId,ApplyChange::getApplyId)
                .leftJoin(Solutions.class,Solutions::getId,InsuranceApply::getSolutionId)
                .eq(!Objects.isNull(model.getType()),ApplyChange::getType,model.getType())
                .eq(!Objects.isNull(model.getStatus())&&!model.getStatus().equals(Constants.ApplyChangeStatus.RETURN_APPLY_UPLOAD.getKey()),ApplyChange::getStatus,model.getStatus())
                .in(!Objects.isNull(model.getStatus())&&model.getStatus().equals(Constants.ApplyChangeStatus.RETURN_APPLY_UPLOAD.getKey()),ApplyChange::getStatus,
                        Constants.ApplyChangeStatus.RETURN_APPLY_UPLOAD.getKey(),
                        Constants.ApplyChangeStatus.RETURN_APPLY_SIGNATURE.getKey())
                .eq(!Objects.isNull(model.getCompanyId()),InsuranceApply::getCompanyId,model.getCompanyId())
                .eq(!Objects.isNull(model.getSolutionsId()),ApplyChange::getSolutionsId,model.getSolutionsId())
                .ge(StringUtils.isNotBlank(model.getCreateDateS()),ApplyChange::getCreateDate, model.getCreateDateS()+" 00:00:00" )
                .le(StringUtils.isNotBlank(model.getCreateDateE()),ApplyChange::getCreateDate, model.getCreateDateE()+" 23:59:59" );
        for(PageWrap.SortData sortData: pageWrap.getSorts()) {
            if (sortData.getDirection().equalsIgnoreCase(PageWrap.DESC)) {
                queryWrapper.orderByDesc(sortData.getProperty());
@@ -145,7 +1415,8 @@
                queryWrapper.orderByAsc(sortData.getProperty());
            }
        }
        return PageData.from(applyChangeMapper.selectPage(page, queryWrapper));
        PageData<ApplyChange> pageData = PageData.from(applyChangeJoinMapper.selectJoinPage(page,ApplyChange.class, queryWrapper));
        return pageData;
    }
    @Override
@@ -153,4 +1424,484 @@
        QueryWrapper<ApplyChange> wrapper = new QueryWrapper<>(applyChange);
        return applyChangeMapper.selectCount(wrapper);
    }
    @Override
    public PageData<ApplyChange> findPageForCompany(PageWrap<ApplyChange> pageWrap) {
        IPage<ApplyChange> page = new Page<>(pageWrap.getPage(), pageWrap.getCapacity());
        MPJLambdaWrapper<ApplyChange> queryWrapper = new MPJLambdaWrapper<>();
        Utils.MP.blankToNull(pageWrap.getModel());
        ApplyChange model = pageWrap.getModel() ;
        queryWrapper
                .selectAll(ApplyChange.class)
                .selectAs(InsuranceApply::getCode,ApplyChange::getApplyCode)
                .selectAs(Solutions::getName,ApplyChange::getSolutionsName)
                .selectAs(Company::getName,ApplyChange::getCompanyName)
                .select("( select count(1) from apply_chagne_detail ad where t.id = ad.APPLY_CHANGE_ID and ad.TYPE = 0  )",ApplyChange::getAddNum)
                .select("( select count(1) from apply_chagne_detail ad where t.id = ad.APPLY_CHANGE_ID and ad.TYPE = 1  )",ApplyChange::getDelNum)
                .select("( select count(1) from apply_chagne_detail ad where t.id = ad.APPLY_CHANGE_ID and ad.TYPE = 2  )",ApplyChange::getChangeNum)
                .select("( select ifnull(sum(ad.FEE),0) from apply_chagne_detail ad where t.id = ad.APPLY_CHANGE_ID  )",ApplyChange::getChangeMoney)
                .leftJoin(InsuranceApply.class,InsuranceApply::getId,ApplyChange::getApplyId)
                .leftJoin(Solutions.class,Solutions::getId,InsuranceApply::getSolutionId)
                .leftJoin(Company.class,Company::getId,InsuranceApply::getCompanyId)
                .eq(!Objects.isNull(model.getType()),ApplyChange::getType,model.getType())
                .eq(!Objects.isNull(model.getStatus())&&!model.getStatus().equals(Constants.ApplyChangeStatus.RETURN_APPLY_UPLOAD.getKey()),ApplyChange::getStatus,model.getStatus())
                .in(!Objects.isNull(model.getStatus())&&model.getStatus().equals(Constants.ApplyChangeStatus.RETURN_APPLY_UPLOAD.getKey()),ApplyChange::getStatus,
                        Constants.ApplyChangeStatus.RETURN_APPLY_UPLOAD.getKey(),
                        Constants.ApplyChangeStatus.RETURN_APPLY_SIGNATURE.getKey())
//                .eq(!Objects.isNull(model.getCompanyId()),InsuranceApply::getCompanyId,model.getCompanyId())
//                .eq(!Objects.isNull(model.getSolutionsId()),ApplyChange::getSolutionsId,model.getSolutionsId())
                .eq(!Objects.isNull(model.getApplyId()),ApplyChange::getApplyId,model.getApplyId())
                .eq(!Objects.isNull(model.getBaseSolutionsId()),Solutions::getBaseId,model.getBaseSolutionsId())
                .ge(StringUtils.isNotBlank(model.getCreateDateS()),ApplyChange::getCreateDate, model.getCreateDateS()+" 00:00:00" )
                .le(StringUtils.isNotBlank(model.getCreateDateE()),ApplyChange::getCreateDate, model.getCreateDateE()+" 23:59:59" );
        LoginUserInfo loginUserInfo =(LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        //企业人员查看本企业数据
        if(loginUserInfo.getType().equals(Constants.ONE)){
            queryWrapper.eq(InsuranceApply::getCompanyId, loginUserInfo.getCompanyId());
        }else{
            if(loginUserInfo.getCompanyIdList()!=null && loginUserInfo.getCompanyIdList().size()>0){
                queryWrapper.in(InsuranceApply::getCompanyId, loginUserInfo.getCompanyIdList());
            }else{
                queryWrapper.eq(InsuranceApply::getCompanyId, -1);
            }
            queryWrapper.eq(pageWrap.getModel().getCompanyId()!=null,InsuranceApply::getCompanyId, pageWrap.getModel().getCompanyId());
        }
        queryWrapper.orderByDesc(ApplyDetail::getCreateDate);
//        for(PageWrap.SortData sortData: pageWrap.getSorts()) {
//            if (sortData.getDirection().equalsIgnoreCase(PageWrap.DESC)) {
//                queryWrapper.orderByDesc(sortData.getProperty());
//            } else {
//                queryWrapper.orderByAsc(sortData.getProperty());
//            }
//        }
        PageData<ApplyChange> pageData = PageData.from(applyChangeJoinMapper.selectJoinPage(page,ApplyChange.class, queryWrapper));
        return pageData;
    }
    @Override
    @Transactional(rollbackFor = {Exception.class,BusinessException.class})
    public void changeOpt(ApplyChangeOptDTO applyChangeOptDTO){
        if(Objects.isNull(applyChangeOptDTO)
                ||Objects.isNull(applyChangeOptDTO.getApplyId())
        ){
            throw new BusinessException(ResponseStatus.BAD_REQUEST);
        }
        LoginUserInfo loginUserInfo = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        ApplyChange applyChange = applyChangeMapper.selectById(applyChangeOptDTO.getApplyId());
        if(Objects.isNull(applyChange)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"未查询到单据数据");
        }
        InsuranceApply insuranceApply = insuranceApplyMapper.selectById(applyChange.getApplyId());
        if(Objects.isNull(insuranceApply)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"未查询到保单数据");
        }
        if(applyChange.getIsdeleted().equals(Constants.ONE)){
            throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(),"数据已删除,无法进行该操作");
        }
        Solutions solutions = solutionsMapper.selectById(insuranceApply.getSolutionId());
        if(Objects.isNull(solutions)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"未查询方案信息");
        }
        Constants.ApplyLogType applyLogType = Constants.ApplyLogType.CA_PLATFORM_CHECK_PASS_NO;
        Constants.NoticeObjectType noticeObjectType = Constants.NoticeObjectType.APPLY_CHANGE;
        if(applyChange.getType().equals(Constants.ONE)){
            noticeObjectType = Constants.NoticeObjectType.CHANGE_FACTORY;
        }
        if(applyChangeOptDTO.getOptType().equals(3)){
            //发起退回申请
            if(!loginUserInfo.getType().equals(Constants.ONE)){
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"非企业端用户无法进行该操作");
            }
            if(!(applyChange.getStatus().equals(Constants.ApplyChangeStatus.UPLOAD.getKey())
                || applyChange.getStatus().equals(Constants.ApplyChangeStatus.SIGNATURE.getKey()))){
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"数据状态错误无法进退回申请!");
            }
            if(applyChange.getStatus().equals(Constants.ApplyChangeStatus.UPLOAD.getKey())){
                applyChange.setStatus(Constants.ApplyChangeStatus.RETURN_APPLY_UPLOAD.getKey());
            }else{
                applyChange.setStatus(Constants.ApplyChangeStatus.RETURN_APPLY_SIGNATURE.getKey());
            }
            //存储待办信息
            //删除其他待办
            noticesMapper.delete(new QueryWrapper<Notices>().lambda().eq(Notices::getObjType,noticeObjectType.getKey()).eq(Notices::getObjId,applyChange.getId()));
            Notices notices = new Notices(noticeObjectType,Constants.ZERO,applyChange.getId(),solutions.getName(),
                    insuranceApply.getCompanyId(), Constants.NoticeType.THREE);
            noticesMapper.insert(notices);
        }else if(applyChangeOptDTO.getOptType().equals(4)){
            applyLogType = Constants.ApplyLogType.CA_PLATFORM_AGREE_BACK_APPLY;
            //平台同意退回
            if(loginUserInfo.getType().equals(Constants.ZERO)){
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"非平台端用户无法进行该操作");
            }
            if(!(applyChangeOptDTO.getOptType().equals(Constants.ApplyChangeStatus.RETURN_APPLY_UPLOAD.getKey())
                            ||applyChangeOptDTO.getOptType().equals(Constants.ApplyChangeStatus.RETURN_APPLY_SIGNATURE.getKey())
                    )){
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"数据状态错误无法进行该操作!");
            }
        }else if(applyChangeOptDTO.getOptType().equals(5)){
            applyLogType = Constants.ApplyLogType.CA_PALTFORM_REFUSE_APPLY;
            //平台驳回退回
            if(loginUserInfo.getType().equals(Constants.ZERO)){
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"非平台端用户无法进行该操作");
            }
            if(!(applyChangeOptDTO.getOptType().equals(Constants.ApplyChangeStatus.RETURN_APPLY_UPLOAD.getKey())
                            ||applyChangeOptDTO.getOptType().equals(Constants.ApplyChangeStatus.RETURN_APPLY_SIGNATURE.getKey())
                    )){
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"数据状态错误无法进行该操作!");
            }
            if(applyChange.getStatus().equals(Constants.ApplyChangeStatus.RETURN_APPLY_UPLOAD.getKey())){
                applyChange.setStatus(Constants.ApplyChangeStatus.UPLOAD.getKey());
            }else{
                applyChange.setStatus(Constants.ApplyChangeStatus.SIGNATURE.getKey());
            }
        }else if(applyChangeOptDTO.getOptType().equals(6)){
            //企业关闭
            applyLogType = Constants.ApplyLogType.CA_COMPANY_CLOSE;
            if(!loginUserInfo.getType().equals(Constants.ONE)){
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"非企业端用户无法进行该操作");
            }
            if(!applyChange.getStatus().equals(Constants.ApplyChangeStatus.PLATFORM_AGREE.getKey())){
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"数据状态错误无法进行该操作!");
            }
            applyChange.setStatus(Constants.ApplyChangeStatus.CLOSE.getKey());
            //存储待办信息
            //删除其他待办
            noticesMapper.delete(new QueryWrapper<Notices>().lambda().eq(Notices::getObjType,noticeObjectType.getKey()).eq(Notices::getObjId,applyChange.getId()));
        }else{
            throw new BusinessException(ResponseStatus.BAD_REQUEST  );
        }
        applyChange.setEditor(loginUserInfo.getId());
        applyChange.setEditDate(new Date());
        applyChangeMapper.updateById(applyChange);
        String info = applyLogType.getInfo();
        if(StringUtils.isNotBlank(applyChangeOptDTO.getOptIllustration())){
            info = info.replace("${param}", applyChangeOptDTO.getOptIllustration());
        }else{
            info = info.replace("${param}", "");
        }
        ApplyLog log = new ApplyLog(applyChange,applyLogType.getName(),info,applyChange.getId(),applyLogType.getKey(), null, null);
        applyLogMapper.insert(log);
    }
    @Override
    public ApplyChange findDetail(Integer id){
        MPJLambdaWrapper<ApplyChange> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(ApplyChange.class)
                .selectAs(InsuranceApply::getCode,ApplyChange::getApplyCode)
                .selectAs(Company::getName,ApplyChange::getCompanyName)
                .selectAs(InsuranceApply::getStartTime,ApplyChange::getStartTime)
                .selectAs(InsuranceApply::getEndTime,ApplyChange::getEndTime)
                .selectAs(Solutions::getName,ApplyChange::getSolutionsName)
                .select("( select count(1) from apply_chagne_detail ad where t.id = ad.APPLY_CHANGE_ID and ad.TYPE = 0  )",ApplyChange::getAddNum)
                .select("( select count(1) from apply_chagne_detail ad where t.id = ad.APPLY_CHANGE_ID and ad.TYPE = 1  )",ApplyChange::getDelNum)
                .select("( select count(1) from apply_chagne_detail ad where t.id = ad.APPLY_CHANGE_ID and ad.TYPE = 2  )",ApplyChange::getChangeNum)
                .leftJoin(InsuranceApply.class,InsuranceApply::getId,ApplyChange::getApplyId)
                .leftJoin(Solutions.class,Solutions::getId,InsuranceApply::getSolutionId)
                .leftJoin(Company.class,Company::getId,InsuranceApply::getCompanyId)
                .eq(ApplyChange::getId,id);
        ApplyChange applyChange =  applyChangeJoinMapper.selectOne(queryWrapper);
        //查询操作记录
        List<ApplyLog> applyLogList = applyLogJoinMapper.selectJoinList(ApplyLog.class,
                new MPJLambdaWrapper<ApplyLog>()
                        .selectAll(ApplyLog.class)
                        .selectAs(SystemUser::getRealname,ApplyLog::getCreatorName)
                        .selectAs(SystemUser::getType,ApplyLog::getCreatorType)
                        .selectAs(Company::getName,ApplyLog::getCompanyName)
                        .leftJoin(SystemUser.class,SystemUser::getId,ApplyLog::getCreator)
                        .leftJoin(Company.class,Company::getId,SystemUser::getCompanyId)
                        .in(ApplyLog::getObjType,Constants.ApplyLogType.getTypeList(Constants.ONE))
                        .eq(ApplyLog::getObjId,applyChange.getId())
                        .orderByAsc(ApplyLog::getCreateDate)
        );
        applyChange.setApplyLogList(applyLogList);
        List<Multifile> multifiles = multifileMapper.selectList(new QueryWrapper<Multifile>().lambda()
                .eq(Multifile::getObjId,applyChange.getId())
                .in(Multifile::getObjType, Arrays.asList(new Integer[]{Constants.MultiFile.CA_APPLY_JIAJIAN_SIGN.getKey()
                        ,Constants.MultiFile.CA_PD_PDF.getKey()
                        ,Constants.MultiFile.CA_APPLY_CHANGEUNIT_SIGN.getKey()}))
                .eq(Multifile::getIsdeleted,Constants.ZERO));
        if(multifiles!=null){
            String path = systemDictDataBiz.queryByCode(Constants.OSS,Constants.RESOURCE_PATH).getCode()
                    +systemDictDataBiz.queryByCode(Constants.OSS,Constants.APPLY_FILE).getCode();
            for(Multifile f : multifiles){
                if(StringUtils.isBlank(f.getFileurl())){
                    continue;
                }
                f.setFileurlFull(path+f.getFileurl());
                if(Constants.equalsInteger(f.getObjType(),Constants.MultiFile.CA_APPLY_JIAJIAN_SIGN.getKey())){
                    //签署后申请单
                    applyChange.setApplyFile(f);
                }else    if(Constants.equalsInteger(f.getObjType(),Constants.MultiFile.CA_APPLY_CHANGEUNIT_SIGN.getKey())){
                    //签署后申请单
                    applyChange.setApplyUnitFile(f);
                }else if(Constants.equalsInteger(f.getObjType(),Constants.MultiFile.CA_PD_PDF.getKey())){
                    //签署后的投保单
                    applyChange.setPidanFile(f);
                }
            }
        }
        return applyChange;
    }
    /**
     * 导出换厂申请表
     * @param param
     * @return
     */
    @Override
    public  ApplyChange  exportChangeUnitExcel(ApplyChange param){
        ApplyChange model = findJoinDetail(param);
        if(Objects.isNull(model) ||! Constants.equalsInteger(Constants.ZERO,model.getIsdeleted())){
            throw new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        //查询明细
        List<ApplyChagneDetail> detailList =findJoinChangeDetailList(model);
        model.setChangeDetailList(detailList!=null?detailList:new ArrayList<>());
        model.setChangeNum(model.getChangeDetailList().size());
        return model;
    }
    /**
     * 导出换厂申请表
     * @param param
     * @return
     */
    @Override
    public  String  getSignLinkJiajiabao(ApplyChange param){
        ApplyChange model = exportJiajianBaoExcel(param);
        return  getOnlineSignLink(model);
    }
    /**
     * 导出换厂申请表
     * @param param
     * @return
     */
    @Override
    public  String  getSignLinkChangeUnit(ApplyChange param){
        ApplyChange model = exportChangeUnitExcel(param);
        return  getOnlineSignLink(model);
    }
    private String getOnlineSignLink(ApplyChange model) {
        if(Objects.isNull(model) ||! Constants.equalsInteger(Constants.ZERO,model.getIsdeleted())){
            throw new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        if(!Constants.equalsInteger(Constants.ZERO,model.getStatus())){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"对不起,该申请状态已流转,当前不支持签章操作!");
        }
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        Company company = user.getCompany();
        if(debugModel){
            company = companyMapper.selectById(model.getCompanyId());
        }
        if(company== null || StringUtils.isBlank( company.getEmail()) || !Constants.equalsInteger(company.getSignStatus(),Constants.THREE)){
            throw  new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"对不起,企业尚未具备在线签章条件,请联系平台管理员确认~");
        }
        InsuranceApply insuranceApply = insuranceApplyMapper.selectById(model.getApplyId());
        if(Objects.isNull(insuranceApply)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"未查询保单信息");
        }
        Solutions solutions = solutionsMapper.selectById(insuranceApply.getSolutionId());
        if(Objects.isNull(solutions)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"未查询方案信息");
        }
        String fileUrl = null;
        if(Constants.equalsObject(model.getType(), Constants.ONE)){
              fileUrl = ExcelExporter.build(ApplyChange.class).exportChangeUnitExcelToPdf(model,"换厂申请表");
        }else{
            fileUrl = ExcelExporter.build(ApplyChange.class).exportJiajianBaoExcelToPdf(model,"加减保申请表");
        }
        String notifyUrl = systemDictDataBiz.queryByCode(Constants.SYSTEM,Constants.SIGN_DONE_NOTIFY_URL).getCode();
        notifyUrl = notifyUrl.replace("${type}","0").replace("${id}",model.getId().toString());
        String applyNo = signService.applySignLocalFile(company.getName(),company.getName(),fileUrl,company.getCode(),company.getEmail(),"投保企业签章",company.getSignId(),notifyUrl);
        if(StringUtils.isBlank(applyNo) ){
            throw  new BusinessException(ResponseStatus.SERVER_ERROR.getCode(),"对不起,获取在线签章地址失败,请稍后重试!");
        }
        String link = signService.signLink(applyNo,company.getName(),company.getCode());
        if(StringUtils.isBlank(link) ){
            throw  new BusinessException(ResponseStatus.SERVER_ERROR.getCode(),"对不起,获取在线签章地址失败,请稍后重试!");
        }
        ApplyChange update= new ApplyChange();
        update.setId(model.getId());
        update.setEditor(user.getId());
        update.setEditDate(new Date());
        update.setSignApplyNo(applyNo);
        applyChangeMapper.updateById(update);
        return  link;
    }
    /**
     * 导出加减保申请表
     * @param param
     * @return
     */
    @Override
    public  ApplyChange  exportJiajianBaoExcel(ApplyChange param){
        ApplyChange model = findJoinDetail(param);
        if(Objects.isNull(model) ||! Constants.equalsInteger(Constants.ZERO,model.getIsdeleted())){
            throw new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        //查询明细
        List<ApplyChagneDetail> detailList =findJoinDetailList(model);
        model.setAddDetailList(new ArrayList<>());
        model.setDelDetailList(new ArrayList<>());
        if(detailList!=null){
            for(ApplyChagneDetail ad :detailList){
                if(Constants.equalsInteger(ad.getType(),Constants.ZERO)){
                    model.getAddDetailList().add(ad);
                }else{
                    model.getDelDetailList().add(ad);
                }
            }
        }
        model.setDelNum(model.getDelDetailList().size());
        model.setAddNum(model.getAddDetailList().size());
        return model;
    }
    private ApplyChange findJoinDetail(ApplyChange param) {
        MPJLambdaWrapper wrapper=  new MPJLambdaWrapper<ApplyChange>()
                .selectAll(ApplyChange.class)
                .selectAs(Solutions::getName,ApplyChange::getSolutionsName)
                .selectAs(Company::getName,ApplyChange::getCompanyName)
                .selectAs(InsuranceApply::getCompanyId,ApplyChange::getCompanyId)
                .selectAs(InsuranceApply::getCode,ApplyChange::getApplyCode)
                .selectAs(InsuranceApply::getStartTime,ApplyChange::getStartTime)
                .selectAs(InsuranceApply::getEndTime,ApplyChange::getEndTime)
                .leftJoin(InsuranceApply.class,InsuranceApply::getId,ApplyChange::getApplyId)
                .leftJoin(Solutions.class,Solutions::getId,InsuranceApply::getSolutionId)
                .leftJoin(Company.class,Company::getId,InsuranceApply::getCompanyId)
                .eq(ApplyChange::getId,param.getId())
                .last("limit 1");
        ApplyChange model = applyChangeJoinMapper.selectJoinOne(ApplyChange.class,wrapper);
        return  model;
    }
    private List<ApplyChagneDetail> findJoinDetailList(ApplyChange model) {
        MPJLambdaWrapper wrapper1=  new MPJLambdaWrapper<ApplyChagneDetail>()
                .selectAll(ApplyChagneDetail.class)
                .selectAs(Member::getName,ApplyChagneDetail::getMemberName)
                .selectAs(Member::getSex,ApplyChagneDetail::getSex)
                .selectAs(Member::getIdcardNo,ApplyChagneDetail::getMemberIdcardNo)
                .selectAs(Worktype::getName,ApplyChagneDetail::getWorkTypeName)
                .selectAs(DispatchUnit::getName,ApplyChagneDetail::getDuName)
                .leftJoin(Worktype.class,Worktype::getId,ApplyChagneDetail::getWorktypeId)
                .leftJoin(DispatchUnit.class,DispatchUnit::getId,ApplyChagneDetail::getDuId)
                .leftJoin(Member.class,Member::getId,ApplyChagneDetail::getMemberId)
                .eq(ApplyChagneDetail::getIsdeleted,Constants.ZERO)
                .eq(ApplyChagneDetail::getApplyChangeId,model.getId());
        //查询明细
        List<ApplyChagneDetail> detailList =applyChagneDetailJoinMapper.selectJoinList(ApplyChagneDetail.class,wrapper1);
        return  detailList;
    }
    private List<ApplyChagneDetail> findJoinChangeDetailList(ApplyChange model) {
        MPJLambdaWrapper wrapper1=  new MPJLambdaWrapper<ApplyChagneDetail>()
                .selectAll(ApplyChagneDetail.class)
                .selectAs(Member::getName,ApplyChagneDetail::getMemberName)
                .selectAs(Member::getSex,ApplyChagneDetail::getSex)
                .select("t1.name as worktypeName")
                .select("t2.name as duName")
                .select("t3.name as oldWorktypeName")
                .select("t4.name as oldDuName")
                .selectAs(Member::getSex,ApplyChagneDetail::getSex)
                .selectAs(Member::getIdcardNo,ApplyChagneDetail::getMemberIdcardNo)
                .leftJoin(Worktype.class,Worktype::getId,ApplyChagneDetail::getWorktypeId)
                .leftJoin(DispatchUnit.class,DispatchUnit::getId,ApplyChagneDetail::getDuId)
                .leftJoin(Worktype.class,Worktype::getId,ApplyChagneDetail::getOldWorktypeId)
                .leftJoin(DispatchUnit.class,DispatchUnit::getId,ApplyChagneDetail::getOldDuId)
                .leftJoin(Member.class,Member::getId,ApplyChagneDetail::getMemberId)
                .eq(ApplyChagneDetail::getIsdeleted,Constants.ZERO)
                .eq(ApplyChagneDetail::getApplyChangeId,model.getId());
        //查询明细
        List<ApplyChagneDetail> detailList =applyChagneDetailJoinMapper.selectJoinList(ApplyChagneDetail.class,wrapper1);
        return  detailList;
    }
    /**
     * 加减保申请时 查询加减金额
     * @param applyChangeCyclePriceDTO
     * @return
     */
    @Override
    public CountCyclePriceVO getChangeCountCyclePriceVO(ApplyChangeCyclePriceDTO applyChangeCyclePriceDTO){
        if(Objects.isNull(applyChangeCyclePriceDTO)
            || Objects.isNull(applyChangeCyclePriceDTO.getApplyId())
            || Objects.isNull(applyChangeCyclePriceDTO.getValidTime())){
            throw new BusinessException(ResponseStatus.BAD_REQUEST);
        }
        InsuranceApply insuranceApply = insuranceApplyMapper.selectById(applyChangeCyclePriceDTO.getApplyId());
        if(Objects.isNull(insuranceApply)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"未查询到保单");
        }
        Solutions solutions = solutionsMapper.selectById(insuranceApply.getSolutionId());
        if(Objects.isNull(solutions)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"未查询方案信息");
        }
        //根据批单日期 和 结束日期 计算金额
        //验证批单日期是否在当前日期后 且 在保单结束日期前 申请时间必须处于保单的时间范围内
        if (!(DateUtil.compareDate( insuranceApply.getStartTime(),applyChangeCyclePriceDTO.getValidTime()) >= Constants.ZERO
                && DateUtil.compareDate( applyChangeCyclePriceDTO.getValidTime(),insuranceApply.getEndTime()) >= Constants.ZERO)) {
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "申请日期未处于保单日期内,无法进行该操作");
        }
        //总天数
        Integer sumDays = DateUtil.daysBetweenDates(insuranceApply.getEndTime(),insuranceApply.getStartTime()) + 1;
        //加减保 到结束的天数
        Integer optDays = DateUtil.daysBetweenDates(insuranceApply.getEndTime(),applyChangeCyclePriceDTO.getValidTime()) + 1;
        CountCyclePriceVO countCyclePriceVO = Constants.countPriceVO(insuranceApply.getStartTime(),solutions);
        //总金额
        BigDecimal sumPrice = countCyclePriceVO.getCyclePrice();
        CountCyclePriceVO returnCountCyclePriceVO = new CountCyclePriceVO();
        //加减保金额
        returnCountCyclePriceVO.setCyclePrice(sumPrice.multiply(new BigDecimal(optDays)).divide(new BigDecimal(sumDays),2, RoundingMode.HALF_UP));
        return returnCountCyclePriceVO;
    }
    /**
     * 计算保单下  X天 多少费用
     * @param applyId
     * @param optDays
     * @return
     */
    public BigDecimal getApplyPrice(Integer applyId,Integer optDays){
        InsuranceApply insuranceApply = insuranceApplyMapper.selectById(applyId);
        if(Objects.isNull(insuranceApply)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"未查询到保单");
        }
        Solutions solutions = solutionsMapper.selectById(insuranceApply.getSolutionId());
        if(Objects.isNull(solutions)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"未查询方案信息");
        }
        //总天数
        Integer sumDays = DateUtil.daysBetweenDates(insuranceApply.getEndTime(),insuranceApply.getStartTime()) + 1;
        CountCyclePriceVO countCyclePriceVO = Constants.countPriceVO(insuranceApply.getStartTime(),solutions);
        //总金额
        BigDecimal sumPrice = countCyclePriceVO.getCyclePrice();;
        return sumPrice.divide(new BigDecimal(sumDays),2, RoundingMode.HALF_UP).multiply(new BigDecimal(optDays));
    }
}