k94314517
2024-04-09 02bc3bfe47e3d5311a0bb041c94e70a34b1ca73c
server/service/src/main/java/com/doumee/service/business/impl/UnionChangeServiceImpl.java
@@ -1,20 +1,45 @@
package com.doumee.service.business.impl;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.api.R;
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.UnionChangeMapper;
import com.doumee.dao.business.model.UnionChange;
import com.doumee.dao.business.*;
import com.doumee.dao.business.dto.*;
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.SmsEmailService;
import com.doumee.service.business.UnionChangeService;
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.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
 * 加减保换厂合并单信息表Service实现
@@ -27,6 +52,51 @@
    @Autowired
    private UnionChangeMapper unionChangeMapper;
    @Autowired
    private UnionChangeJoinMapper unionChangeJoinMapper;
    @Autowired
    private ApplyChangeJoinMapper applyChangeJoinMapper;
    @Autowired
    private ApplyChagneDetailJoinMapper applyChagneDetailJoinMapper;
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private SolutionsMapper solutionsMapper;
    @Autowired
    private SystemDictDataBiz systemDictDataBiz;
    @Autowired
    private SignService signService;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private ApplyDetailJoinMapper applyDetailJoinMapper;
    @Autowired
    private MemberInsuranceJoinMapper memberInsuranceJoinMapper;
    @Autowired
    private InsuranceApplyMapper insuranceApplyMapper;
    @Value("${debug_model}")
    private boolean debugModel;
    @Autowired
    private SmsEmailService smsEmailService;
    @Autowired
    private MultifileMapper multifileMapper;
    @Autowired
    private ApplyLogMapper applyLogMapper;
    @Autowired
    private ApplyLogJoinMapper applyLogJoinMapper;
    @Override
    public Integer create(UnionChange unionChange) {
        unionChangeMapper.insert(unionChange);
@@ -72,6 +142,90 @@
        return unionChangeMapper.selectById(id);
    }
    @Override
    public UnionChange getDetail(Integer id){
        UnionChange unionChange = unionChangeJoinMapper.selectJoinOne(UnionChange.class,
                new MPJLambdaWrapper<UnionChange>()
                        .selectAll(UnionChange.class)
                 .selectAs(UnionApply::getCode,UnionChange::getApplyCode)
                .selectAs(Solutions::getName,UnionChange::getSolutionsName)
                .selectAs(UnionApply::getStartTime,UnionChange::getStartTime)
                .selectAs(UnionApply::getEndTime,UnionChange::getEndTime)
                .selectAs(Company::getName,UnionChange::getShopName)
                .select("( select count(1) from apply_chagne_detail ad where t.id = ad.UNION_CHANGE_ID and ad.TYPE = 0  )",UnionChange::getAddNum)
                .select("( select count(1) from apply_chagne_detail ad where t.id = ad.UNION_CHANGE_ID and ad.TYPE = 1  )",UnionChange::getDelNum)
                .select("( select count(1) from apply_chagne_detail ad where t.id = ad.UNION_CHANGE_ID and ad.TYPE = 2  )",UnionChange::getChangeNum)
                .leftJoin(UnionApply.class,UnionApply::getId,UnionChange::getUnionApplyId)
                .leftJoin(Solutions.class,Solutions::getId,UnionApply::getSolutionId)
                .leftJoin(Company.class,Company::getId,UnionChange::getShopId)
                        .eq(UnionChange::getId,id)
                        .last(" limit 1 ")
        );
        if(!Objects.isNull(unionChange)){
            //查询加减保明细数据
            List<ApplyChagneDetail> applyChangeList = applyChagneDetailJoinMapper
                    .selectList(new QueryWrapper<ApplyChagneDetail>()
                            .lambda()
                            .eq(ApplyChagneDetail::getIsdeleted,Constants.ZERO)
                            .ne(ApplyChagneDetail::getType,Constants.TWO)
                            .eq(ApplyChagneDetail::getUnionChangeId,unionChange.getId()));
            BigDecimal fee = BigDecimal.ZERO;
            for (ApplyChagneDetail applyChagneDetail:applyChangeList) {
                Integer maxDays = DateUtil.calculateBetween(unionChange.getApplyStartTime(),applyChagneDetail.getEndTime(),0);
                if(applyChagneDetail.getType().equals(Constants.ZERO)){
                    fee = fee.add(new BigDecimal(maxDays).multiply(applyChagneDetail.getPrice()));
                }else{
                    fee = fee.subtract(new BigDecimal(maxDays).multiply(applyChagneDetail.getPrice()));
                }
            }
            unionChange.setFee(fee);
            //查询操作记录
            List<ApplyLog> applyLogList = applyLogJoinMapper.selectJoinList(ApplyLog.class,
                    new MPJLambdaWrapper<ApplyLog>()
                            .selectAll(ApplyLog.class)
                            .selectAs(SystemUser::getRealname,ApplyLog::getCreatorName)
                            .selectAs(Company::getName,ApplyLog::getCompanyName)
                            .selectAs(SystemUser::getType,ApplyLog::getCreatorType)
                            .leftJoin(SystemUser.class,SystemUser::getId,ApplyLog::getCreator)
                            .leftJoin(Company.class,Company::getId,SystemUser::getCompanyId)
                            .in(ApplyLog::getObjType,Constants.ApplyLogType.getTypeList(Constants.FOUR))
                            .eq(ApplyLog::getApplyId,unionChange.getId())
                            .orderByAsc(ApplyLog::getCreateDate)
            );
            unionChange.setApplyLogList(applyLogList);
        }
        initFiles(unionChange);
        return unionChange;
    }
    private void initFiles(UnionChange unionChange) {
        List<Multifile> multifiles = multifileMapper.selectList(new QueryWrapper<Multifile>().lambda()
                .eq(Multifile::getObjId, unionChange.getId() )
                .in(Multifile::getObjType, Arrays.asList(new Integer[]{Constants.MultiFile.WTB_CA_TBD_PDF.getKey(),Constants.MultiFile.WTB_CA_DONE_PDF.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.WTB_CA_TBD_PDF.getKey())){
                    //签署后申请单
                    unionChange.setApplyFile(f);
                }
                if(Constants.equalsInteger(f.getObjType(),Constants.MultiFile.WTB_CA_DONE_PDF.getKey())){
                    //签署后申请单
                    unionChange.setPidanFile(f);
                }
            }
        }
    }
    @Override
    public UnionChange findOne(UnionChange unionChange) {
        QueryWrapper<UnionChange> wrapper = new QueryWrapper<>(unionChange);
@@ -87,59 +241,80 @@
    @Override
    public PageData<UnionChange> findPage(PageWrap<UnionChange> pageWrap) {
        IPage<UnionChange> page = new Page<>(pageWrap.getPage(), pageWrap.getCapacity());
        QueryWrapper<UnionChange> queryWrapper = new QueryWrapper<>();
        MPJLambdaWrapper<UnionChange> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(UnionChange.class);
        pageWrap.getModel().setIsdeleted(Constants.ZERO);
        queryWrapper.selectAs(UnionApply::getCode,UnionChange::getApplyCode);
        queryWrapper.selectAs(Solutions::getName,UnionChange::getSolutionsName)
        .select("( select count(1) from apply_chagne_detail ad where t.id = ad.UNION_CHANGE_ID and ad.TYPE = 0  )",UnionChange::getAddNum)
        .select("( select count(1) from apply_chagne_detail ad where t.id = ad.UNION_CHANGE_ID and ad.TYPE = 1  )",UnionChange::getDelNum)
        .select("( select count(1) from apply_chagne_detail ad where t.id = ad.UNION_CHANGE_ID and ad.TYPE = 2  )",UnionChange::getChangeNum);
        queryWrapper.leftJoin(UnionApply.class,UnionApply::getId,UnionChange::getUnionApplyId);
        queryWrapper.leftJoin(Solutions.class,Solutions::getId,UnionApply::getSolutionId);
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(Constants.equalsInteger(user.getType(),Constants.TWO)){
            queryWrapper.eq(UnionChange::getShopId, user.getCompanyId());
        }
        Utils.MP.blankToNull(pageWrap.getModel());
        if (pageWrap.getModel().getId() != null) {
            queryWrapper.lambda().eq(UnionChange::getId, pageWrap.getModel().getId());
            queryWrapper.eq(UnionChange::getId, pageWrap.getModel().getId());
        }
        if (pageWrap.getModel().getCreator() != null) {
            queryWrapper.lambda().eq(UnionChange::getCreator, pageWrap.getModel().getCreator());
            queryWrapper.eq(UnionChange::getCreator, pageWrap.getModel().getCreator());
        }
        if (pageWrap.getModel().getQueryStartTime() != null) {
            queryWrapper.ge(UnionChange::getCreateDate, pageWrap.getModel().getQueryStartTime() +" 00:00:00" );
        }
        if (pageWrap.getModel().getQueryEndTime() != null) {
            queryWrapper.le(UnionChange::getCreateDate, pageWrap.getModel().getQueryEndTime() +" 23:59:59");
        }
        if (pageWrap.getModel().getCreateDate() != null) {
            queryWrapper.lambda().ge(UnionChange::getCreateDate, Utils.Date.getStart(pageWrap.getModel().getCreateDate()));
            queryWrapper.lambda().le(UnionChange::getCreateDate, Utils.Date.getEnd(pageWrap.getModel().getCreateDate()));
            queryWrapper.ge(UnionChange::getCreateDate, Utils.Date.getStart(pageWrap.getModel().getCreateDate()));
            queryWrapper.le(UnionChange::getCreateDate, Utils.Date.getEnd(pageWrap.getModel().getCreateDate()));
        }
        if (pageWrap.getModel().getEditor() != null) {
            queryWrapper.lambda().eq(UnionChange::getEditor, pageWrap.getModel().getEditor());
            queryWrapper.eq(UnionChange::getEditor, pageWrap.getModel().getEditor());
        }
        if (pageWrap.getModel().getEditDate() != null) {
            queryWrapper.lambda().ge(UnionChange::getEditDate, Utils.Date.getStart(pageWrap.getModel().getEditDate()));
            queryWrapper.lambda().le(UnionChange::getEditDate, Utils.Date.getEnd(pageWrap.getModel().getEditDate()));
            queryWrapper.ge(UnionChange::getEditDate, Utils.Date.getStart(pageWrap.getModel().getEditDate()));
            queryWrapper.le(UnionChange::getEditDate, Utils.Date.getEnd(pageWrap.getModel().getEditDate()));
        }
        if (pageWrap.getModel().getIsdeleted() != null) {
            queryWrapper.lambda().eq(UnionChange::getIsdeleted, pageWrap.getModel().getIsdeleted());
            queryWrapper.eq(UnionChange::getIsdeleted, pageWrap.getModel().getIsdeleted());
        }
        if (pageWrap.getModel().getRemark() != null) {
            queryWrapper.lambda().eq(UnionChange::getRemark, pageWrap.getModel().getRemark());
            queryWrapper.eq(UnionChange::getRemark, pageWrap.getModel().getRemark());
        }
        if (pageWrap.getModel().getSortnum() != null) {
            queryWrapper.lambda().eq(UnionChange::getSortnum, pageWrap.getModel().getSortnum());
            queryWrapper.eq(UnionChange::getSortnum, pageWrap.getModel().getSortnum());
        }
        if (pageWrap.getModel().getShopId() != null) {
            queryWrapper.lambda().eq(UnionChange::getShopId, pageWrap.getModel().getShopId());
            queryWrapper.eq(UnionChange::getShopId, pageWrap.getModel().getShopId());
        }
        if (pageWrap.getModel().getCode() != null) {
            queryWrapper.lambda().eq(UnionChange::getCode, pageWrap.getModel().getCode());
            queryWrapper.eq(UnionChange::getCode, pageWrap.getModel().getCode());
        }
        if (pageWrap.getModel().getApplyStartTime() != null) {
            queryWrapper.lambda().ge(UnionChange::getApplyStartTime, Utils.Date.getStart(pageWrap.getModel().getApplyStartTime()));
            queryWrapper.lambda().le(UnionChange::getApplyStartTime, Utils.Date.getEnd(pageWrap.getModel().getApplyStartTime()));
            queryWrapper.ge(UnionChange::getApplyStartTime, Utils.Date.getStart(pageWrap.getModel().getApplyStartTime()));
            queryWrapper.le(UnionChange::getApplyStartTime, Utils.Date.getEnd(pageWrap.getModel().getApplyStartTime()));
        }
        if (pageWrap.getModel().getStatus() != null) {
            queryWrapper.lambda().eq(UnionChange::getStatus, pageWrap.getModel().getStatus());
            queryWrapper.eq(UnionChange::getStatus, pageWrap.getModel().getStatus());
        }
        if (pageWrap.getModel().getValidTime() != null) {
            queryWrapper.lambda().ge(UnionChange::getValidTime, Utils.Date.getStart(pageWrap.getModel().getValidTime()));
            queryWrapper.lambda().le(UnionChange::getValidTime, Utils.Date.getEnd(pageWrap.getModel().getValidTime()));
            queryWrapper.ge(UnionChange::getValidTime, Utils.Date.getStart(pageWrap.getModel().getValidTime()));
            queryWrapper.le(UnionChange::getValidTime, Utils.Date.getEnd(pageWrap.getModel().getValidTime()));
        }
        if (pageWrap.getModel().getValidCode() != null) {
            queryWrapper.lambda().eq(UnionChange::getValidCode, pageWrap.getModel().getValidCode());
            queryWrapper.eq(UnionChange::getValidCode, pageWrap.getModel().getValidCode());
        }
        if (pageWrap.getModel().getType() != null) {
            queryWrapper.lambda().eq(UnionChange::getType, pageWrap.getModel().getType());
            queryWrapper.eq(UnionChange::getType, pageWrap.getModel().getType());
        }
        if (pageWrap.getModel().getSignApplyNo() != null) {
            queryWrapper.lambda().eq(UnionChange::getSignApplyNo, pageWrap.getModel().getSignApplyNo());
            queryWrapper.eq(UnionChange::getSignApplyNo, pageWrap.getModel().getSignApplyNo());
        }
        for(PageWrap.SortData sortData: pageWrap.getSorts()) {
            if (sortData.getDirection().equalsIgnoreCase(PageWrap.DESC)) {
@@ -148,7 +323,8 @@
                queryWrapper.orderByAsc(sortData.getProperty());
            }
        }
        return PageData.from(unionChangeMapper.selectPage(page, queryWrapper));
        PageData<UnionChange> pageData = PageData.from(unionChangeJoinMapper.selectJoinPage(page,UnionChange.class, queryWrapper));
        return pageData;
    }
    @Override
@@ -156,4 +332,663 @@
        QueryWrapper<UnionChange> wrapper = new QueryWrapper<>(unionChange);
        return unionChangeMapper.selectCount(wrapper);
    }
    @Override
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    public Integer merge(SaveUnionChangeDTO saveUnionChangeDTO){
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        if(!user.getType().equals(Constants.TWO)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"非商户用户,无法进行该操作");
        }
        if(Objects.isNull(saveUnionChangeDTO)
                || Objects.isNull(saveUnionChangeDTO.getApplyIds())
                || Objects.isNull(saveUnionChangeDTO.getApplyDate())
                || Objects.isNull(saveUnionChangeDTO.getUnionApplyId())
                || Objects.isNull(saveUnionChangeDTO.getBusinessType())
        ){
            throw new BusinessException(ResponseStatus.BAD_REQUEST);
        }
        List<ApplyChange> applyChangeList = applyChangeJoinMapper.selectJoinList(ApplyChange.class,
                new MPJLambdaWrapper<ApplyChange>()
                        .selectAll(ApplyChange.class)
                        .leftJoin(InsuranceApply.class,InsuranceApply::getId,ApplyChange::getApplyId)
                        .eq(ApplyChange::getIsdeleted, Constants.ZERO)
                        .eq(InsuranceApply::getUnionApplyId,saveUnionChangeDTO.getUnionApplyId())
                        .eq(ApplyChange::getStatus,Constants.ApplyChangeStatus.CHECHED_PASSED.getKey())
                        .eq(InsuranceApply::getStatus,Constants.InsuranceApplyStatus.WTB_DONE.getKey())
                        .eq(ApplyChange::getType,saveUnionChangeDTO.getBusinessType())
                        .in(ApplyChange::getId,saveUnionChangeDTO.getApplyIds())
                        .isNull(ApplyChange::getUnionChangeId)
        );
        //查询数据是否存在未处于审批通过的数据
        if(applyChangeList.size()!=saveUnionChangeDTO.getApplyIds().size()){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"存在数据已处理,请刷新重试");
        }
        UnionChange unionChange = new UnionChange();
        unionChange.setCreateDate(new Date());
        unionChange.setCreator(user.getId());
        unionChange.setShopId(user.getCompanyId());
        unionChange.setIsdeleted(Constants.ZERO);
        unionChange.setUnionApplyId(saveUnionChangeDTO.getUnionApplyId());
        unionChange.setApplyStartTime(DateUtil.getMontageDate(saveUnionChangeDTO.getApplyDate(),1));
        unionChange.setType(saveUnionChangeDTO.getBusinessType());
        unionChange.setStatus(Constants.UnionChangeStatus.MERGE.getKey());
        unionChangeMapper.insert(unionChange);
        applyChangeJoinMapper.update(null,new UpdateWrapper<ApplyChange>().lambda()
                .set(ApplyChange::getUnionChangeId,unionChange.getId())
                .set(ApplyChange::getCheckDate,new Date())
                .set(ApplyChange::getCheckUserId,user.getId())
                .set(ApplyChange::getStatus,Constants.ApplyChangeStatus.WTB_TOUBAOING.getKey())
                .in(ApplyChange::getId,saveUnionChangeDTO.getApplyIds())
        );
        applyChagneDetailJoinMapper.update(null,new UpdateWrapper<ApplyChagneDetail>().lambda()
                .set(ApplyChagneDetail::getUnionChangeId,unionChange.getId())
                .in(ApplyChagneDetail::getApplyChangeId,saveUnionChangeDTO.getApplyIds()));
        Constants.ApplyLogType applyLogType = Constants.ApplyLogType.CA_HBD_UPLOAD;
        ApplyLog log = new ApplyLog(unionChange,applyLogType.getName(), null
                ,unionChange.getId(),applyLogType.getKey(),null, JSONObject.toJSONString(unionChange));
        applyLogMapper.insert(log);
        return unionChange.getId();
    }
    /**
     * 取消保单合并
     * @param closeDTO
     */
    @Override
    @Transactional(rollbackFor = {Exception.class,BusinessException.class})
    public void cancelMerge(CloseDTO closeDTO){
        if(Objects.isNull(closeDTO)
                ||Objects.isNull(closeDTO.getId())
                ||StringUtils.isBlank(closeDTO.getReason())){
            throw new BusinessException(ResponseStatus.BAD_REQUEST);
        }
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        user.setType(Constants.formatIntegerNum(user.getType()));
        if(!user.getType().equals(Constants.TWO)){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"非商户用户,无法进行该操作!");
        }
        UnionChange unionChange = unionChangeMapper.selectById(closeDTO.getId());
        if(Objects.isNull(unionChange)||!Constants.equalsInteger(unionChange.getIsdeleted(),Constants.ZERO)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        unionChange.setStatus(Constants.formatIntegerNum(unionChange.getStatus()));
        unionChange.setShopId(Constants.formatIntegerNum(unionChange.getShopId()));
        if(!unionChange.getShopId().equals(user.getCompanyId())){
            throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(),"对不起非您的合并单,您无法进行操作!");
        }
        if(unionChange.getStatus().equals(Constants.UnionChangeStatus.FINISH.getKey())){
            throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(),"对不起,合并单业务已完结,您无法进行该操作!");
        }
        if(unionChange.getStatus().equals(Constants.UnionChangeStatus.CLOSE.getKey())){
            throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(),"对不起,合并单业务已关闭");
        }
        applyChangeJoinMapper.update(null,new UpdateWrapper<ApplyChange>().lambda()
                .set(ApplyChange::getUnionChangeId,null)
                .set(ApplyChange::getCheckDate,new Date())
                .set(ApplyChange::getCheckUserId,user.getId())
                .set(ApplyChange::getStatus,Constants.ApplyChangeStatus.CHECHED_PASSED.getKey())
                .in(ApplyChange::getUnionChangeId,unionChange.getId())
        );
        applyChagneDetailJoinMapper.update(null,new UpdateWrapper<ApplyChagneDetail>().lambda()
                .set(ApplyChagneDetail::getUnionChangeId,null)
                .eq(ApplyChagneDetail::getUnionChangeId,unionChange.getId()));
        unionChangeMapper.update(null,new UpdateWrapper<UnionChange>().lambda()
                .set(UnionChange::getStatus,Constants.UnionChangeStatus.CLOSE.getKey())
                .eq(UnionChange::getId,unionChange.getId())
        );
        Constants.ApplyLogType applyLogType = Constants.ApplyLogType.CA_HBD_CLOSE;
        String info =applyLogType.getInfo();
        info = info.replace("${param}", closeDTO.getReason());
        ApplyLog log = new ApplyLog(unionChange,applyLogType.getName(), info
                ,unionChange.getId(),applyLogType.getKey(),null, JSONObject.toJSONString(unionChange));
        applyLogMapper.insert(log);
    }
    @Override
    public UnionChange unionChangeDetail(Integer unionChangeId){
        if(Objects.isNull(unionChangeId)){
            throw new BusinessException(ResponseStatus.BAD_REQUEST);
        }
        UnionChange unionChange = unionChangeJoinMapper.selectJoinOne(UnionChange.class,
                new MPJLambdaWrapper<UnionChange>()
                        .selectAll(UnionChange.class)
                        .selectAs(Company::getName,UnionChange::getShopName)
                        .selectAs(Solutions::getName,UnionChange::getSolutionsName)
                        .selectAs(UnionApply::getCode,UnionChange::getApplyCode)
                        .selectAs(UnionApply::getStartTime,UnionChange::getStartTime)
                        .selectAs(UnionApply::getEndTime,UnionChange::getEndTime)
                        .leftJoin(UnionApply.class,UnionApply::getId,UnionChange::getUnionApplyId)
                        .leftJoin(Company.class,Company::getId,UnionChange::getShopId)
                        .leftJoin(Solutions.class,Solutions::getId,UnionApply::getSolutionId)
                        .eq(UnionChange::getId,unionChangeId)
                        .last(" limit 1 ")
        );
        //企业名称
        List<ApplyChange> applyChangeList = applyChangeJoinMapper.selectJoinList(ApplyChange.class,new MPJLambdaWrapper<ApplyChange>()
                .selectAll(ApplyChange.class)
                .selectAs(Company::getName,ApplyChange::getCompanyName)
                .leftJoin(InsuranceApply.class,InsuranceApply::getId,ApplyChange::getApplyId)
                .leftJoin(Company.class,Company::getId,InsuranceApply::getCompanyId)
                .eq(ApplyChange::getUnionChangeId,unionChangeId)
        );
        String companyNames = String.join(",",applyChangeList.stream().map(m->m.getCompanyName()).collect(Collectors.toList()));
        List<ApplyChagneDetail> applyChagneDetailList = applyChagneDetailJoinMapper.selectJoinList(ApplyChagneDetail.class,new MPJLambdaWrapper<ApplyChagneDetail>()
                .selectAll(ApplyChagneDetail.class)
                .selectAs(Member::getName,ApplyChagneDetail::getMemberName)
                .selectAs(Member::getIdcardNo,ApplyChagneDetail::getIdcardNo)
                .selectAs(Member::getSex,ApplyChagneDetail::getSex)
                .selectAs(Company::getName,ApplyChagneDetail::getCompanyName)
                .select("t2.name",ApplyChagneDetail::getWorkTypeName)
                .select("t3.name",ApplyChagneDetail::getDuName)
                .select("t4.name",ApplyChagneDetail::getOldWorkTypeName)
                .select("t5.name",ApplyChagneDetail::getOldDuName)
                .leftJoin(Member.class,Member::getId,ApplyChagneDetail::getMemberId)
                .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(Company.class,Company::getId,Member::getCompanyId)
                .eq(ApplyChagneDetail::getUnionChangeId,unionChangeId)
        );
        unionChange.setCompanyNames(companyNames);
        unionChange.setApplyChagneDetailList(applyChagneDetailList);
        return unionChange;
    }
    /**
     * 合并单(加减保/换厂) - 投保申请签署
     * @param smsCheckDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class,BusinessException.class})
    public  String getSignLink(SmsCheckDTO smsCheckDTO) {
        if(Objects.isNull(smsCheckDTO)
                || Objects.isNull(smsCheckDTO.getBusinessId())
                || StringUtils.isBlank(smsCheckDTO.getCode())
        ){
            throw  new BusinessException(ResponseStatus.BAD_REQUEST);
        }
        //验证 验证码
        if(!debugModel){
            smsEmailService.validateCode(smsCheckDTO.getCode());
        }
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        UnionChange unionChange = this.unionChangeDetail(smsCheckDTO.getBusinessId());
        unionChange.setStatus(Constants.formatIntegerNum(unionChange.getStatus()));
        if(Objects.isNull(unionChange)||!Constants.equalsInteger(unionChange.getIsdeleted(),Constants.ZERO)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        if(!unionChange.getShopId().equals(user.getCompanyId())){
            throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(),"对不起非您的合并单,您无法进行操作!");
        }
        if(unionChange.getStatus().equals(Constants.UnionChangeStatus.FINISH.getKey())){
            throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(),"对不起,合并单业务已完结,您无法进行该操作!");
        }
        if(unionChange.getStatus().equals(Constants.UnionChangeStatus.CLOSE.getKey())){
            throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(),"对不起,合并单业务已关闭");
        }
        if(!unionChange.getStatus().equals(Constants.UnionChangeStatus.MERGE.getKey())){
            throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(),"对不起,合并单状态已流转");
        }
        Company company =  companyMapper.selectById(user.getCompanyId());
        if(company== null || StringUtils.isBlank( company.getEmail()) || !Constants.equalsInteger(company.getSignStatus(),Constants.THREE)){
            throw  new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"对不起,企业尚未具备在线签章条件,请联系平台管理员确认~");
        }
        String fileUrl = null;
        if(Constants.equalsObject(unionChange.getType(), Constants.ONE)){
            fileUrl = ExcelExporter.build(UnionChange.class).exportUnionChangeOtherUnitExcelToPdf(unionChange,"换厂申请表");
        }else{
            fileUrl = ExcelExporter.build(UnionChange.class).exportUnionChangeExcelToPdf(unionChange,"加减保申请表");
        }
        String notifyUrl = systemDictDataBiz.queryByCode(Constants.SYSTEM,Constants.SIGN_DONE_NOTIFY_URL).getCode();
        notifyUrl = notifyUrl.replace("${type}","0").replace("${id}",unionChange.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(),"对不起,获取在线签章地址失败,请稍后重试!");
        }
        UnionChange update= new UnionChange();
        update.setId(unionChange.getId());
        update.setEditor(user.getId());
        update.setEditDate(new Date());
        update.setSignApplyNo(applyNo);
        unionChangeMapper.updateById(update);
        return  link;
    }
    @Override
    @Transactional(rollbackFor = {BusinessException.class,Exception.class})
    public void uploadBXD(UnionChangeBXDDTO unionChangeBXDDTO){
        if(Objects.isNull(unionChangeBXDDTO)
            || Objects.isNull(unionChangeBXDDTO.getId())
                || Objects.isNull(unionChangeBXDDTO.getApplyDate())
                || StringUtils.isBlank(unionChangeBXDDTO.getName())
                || StringUtils.isBlank(unionChangeBXDDTO.getFileurl())
                || StringUtils.isBlank(unionChangeBXDDTO.getCode())
        ){
            throw new BusinessException(ResponseStatus.BAD_REQUEST);
        }
        LoginUserInfo user = (LoginUserInfo) SecurityUtils.getSubject().getPrincipal();
        UnionChange unionChange = unionChangeMapper.selectById(unionChangeBXDDTO.getId());
        if(Objects.isNull(unionChange)||!Constants.equalsInteger(unionChange.getIsdeleted(),Constants.ZERO)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        unionChange.setStatus(Constants.formatIntegerNum(unionChange.getStatus()));
        unionChange.setShopId(Constants.formatIntegerNum(unionChange.getShopId()));
        if(!unionChange.getShopId().equals(user.getCompanyId())){
            throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(),"对不起非您的合并单,您无法进行操作!");
        }
        if(unionChange.getStatus().equals(Constants.UnionChangeStatus.FINISH.getKey())){
            throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(),"对不起,合并单业务已完结,您无法进行该操作!");
        }
        if(unionChange.getStatus().equals(Constants.UnionChangeStatus.CLOSE.getKey())){
            throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(),"对不起,合并单业务已关闭");
        }
        if(!unionChange.getStatus().equals(Constants.UnionChangeStatus.UPLOAD_INSURANCE_POLICY.getKey())){
            throw new BusinessException(ResponseStatus.DATA_ERRO.getCode(),"对不起,合并单状态已流转");
        }
        List<ApplyChange> applyChangeList = applyChangeJoinMapper.selectJoinList(ApplyChange.class,
                new MPJLambdaWrapper<ApplyChange>()
                        .selectAll(ApplyChange.class)
                        .selectAs(InsuranceApply::getSolutionId,ApplyChange::getSolutionsId)
                        .selectAs(InsuranceApply::getCode,ApplyChange::getApplyCode)
                        .leftJoin(InsuranceApply.class,InsuranceApply::getId,ApplyChange::getApplyId)
                        .eq(ApplyChange::getUnionChangeId,unionChange.getId()));
        //存储合并单保险单
        Multifile multifile = new Multifile();
        multifile.setIsdeleted(Constants.ZERO);
        multifile.setCreator(user.getId());
        multifile.setCreateDate(new Date());
        multifile.setObjId(unionChangeBXDDTO.getId());
        multifile.setCreateDate(new Date());
        multifile.setObjType(Constants.MultiFile.WTB_CA_DONE_PDF.getKey());
        multifile.setType(Constants.TWO);
        multifile.setFileurl(unionChangeBXDDTO.getFileurl());
        multifile.setName(unionChangeBXDDTO.getName());
        multifileMapper.insert(multifile);
        if(CollectionUtils.isNotEmpty(unionChangeBXDDTO.getApplyChangeBXDList())){
            //查询是否不存在当前合并单的数据
            if(applyChangeJoinMapper.selectCount(new QueryWrapper<ApplyChange>()
                    .lambda().ne(ApplyChange::getUnionChangeId,unionChangeBXDDTO.getId())
                    .in(ApplyChange::getId,
                            unionChangeBXDDTO.getApplyChangeBXDList().stream().map(m->m.getObjId()).collect(Collectors.toList())
                    )
            )>Constants.ZERO){
                throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"批单明细记录存在非本合并单数据");
            };
            for (Multifile m:unionChangeBXDDTO.getApplyChangeBXDList()) {
                if(Objects.isNull(m.getObjId())
                        ||StringUtils.isBlank(m.getFileurl())
                        ||StringUtils.isBlank(m.getName())
                ){
                    throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"批单文件信息缺失");
                }
                m.setId(null);
                m.setIsdeleted(Constants.ZERO);
                m.setCreator(user.getId());
                m.setCreateDate(new Date());
                m.setObjType(Constants.MultiFile.CA_PD_PDF.getKey());
                m.setType(Constants.TWO);
                multifileMapper.insert(m);
            }
        }
        if(CollectionUtils.isNotEmpty(applyChangeList)){
            for (ApplyChange applyChange:applyChangeList) {
                applyChange.setApplyStartTime(unionChangeBXDDTO.getApplyDate());
                applyChange.setValidTime(unionChangeBXDDTO.getApplyDate());
                applyChange.setEditDate(new Date());
                applyChange.setEditor(user.getId());
                applyChange.setStatus(Constants.ApplyChangeStatus.APPROVE.getKey());
                List<ApplyChagneDetail> allList = applyChagneDetailJoinMapper.selectJoinList(ApplyChagneDetail.class,
                        new MPJLambdaWrapper<ApplyChagneDetail>().selectAll(ApplyChagneDetail.class)
                                .selectAs(Member::getName,ApplyChagneDetail::getMemberName )
                                .selectAs(Member::getIdcardNo,ApplyChagneDetail::getIdcardNo )
                                .leftJoin(Member.class,Member::getId,ApplyChagneDetail::getMemberId)
                                .eq(ApplyChagneDetail::getApplyChangeId,applyChange.getId()));
                this.dealApplyChangeDetail(applyChange,allList);
                applyChange.setCode(unionChangeBXDDTO.getCode());
                applyChange.setCheckUserId(user.getId());
                applyChangeJoinMapper.updateById(applyChange);
            }
        }
        unionChangeMapper.update(null,new UpdateWrapper<UnionChange>().lambda()
                .set(UnionChange::getStatus,Constants.UnionChangeStatus.FINISH.getKey())
                .set(UnionChange::getEditDate,new Date())
                .set(UnionChange::getEditor,user.getId())
                .set(UnionChange::getValidTime,unionChangeBXDDTO.getApplyDate())
                .set(UnionChange::getApplyStartTime,unionChangeBXDDTO.getApplyDate())
                .set(UnionChange::getCode,unionChangeBXDDTO.getCode())
                .eq(UnionChange::getId,unionChangeBXDDTO.getId())
        );
        Constants.ApplyLogType applyLogType = Constants.ApplyLogType.CA_HBD_UPLOAD_INSURANCE;
        ApplyLog log = new ApplyLog(unionChange,applyLogType.getName(), null
                ,unionChange.getId(),applyLogType.getKey(),null, JSONObject.toJSONString(unionChange));
        applyLogMapper.insert(log);
        if(true){
            throw new BusinessException(ResponseStatus.BAD_REQUEST);
        }
    }
    public void dealApplyChangeDetail(ApplyChange applyChange,List<ApplyChagneDetail> applyChagneDetailList){
        BigDecimal totalFee = BigDecimal.ZERO;
        BigDecimal currentFee = BigDecimal.ZERO;
        for (ApplyChagneDetail detail:applyChagneDetailList) {
            Member member = memberMapper.selectById(detail.getMemberId());
            if(Objects.isNull(member)){
                throw new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"未查询到员工数据");
            }
            if (Constants.equalsInteger(detail.getType(), Constants.ZERO)) {
               this.addChangeDetailData(applyChange,detail,detail.getPrice(),currentFee,totalFee);
            }else if(Constants.equalsInteger(detail.getType(),Constants.ONE)){
                this.reduceChangeDetailData(applyChange,detail,currentFee,totalFee);
            }else{
                this.otherChangeDetailData(applyChange,detail);
            }
        }
        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, applyChange.getEditor())
                    .set(InsuranceApply::getEditDate, applyChange.getEditDate())
                    .eq(InsuranceApply::getId, applyChange.getApplyId())
            );
            applyChangeJoinMapper.update(null, new UpdateWrapper<ApplyChange>().lambda()
                    .set(ApplyChange::getFee,totalFee)
                    .set(ApplyChange::getEditor, applyChange.getEditor())
                    .set(ApplyChange::getEditDate, applyChange.getEditDate())
                    .eq(ApplyChange::getId, applyChange.getApplyId())
            );
        }
    }
    /**
     * 加保数据处理
     * @param applyChange
     * @param detail
     * @param price
     * @param currentFee
     * @param totalFee
     */
    public void addChangeDetailData(ApplyChange applyChange,ApplyChagneDetail detail
            ,BigDecimal price,BigDecimal currentFee,BigDecimal totalFee){
        //查询加保人员是否存在 冲突的 保单明细数据
        if(applyDetailJoinMapper.selectCount(new QueryWrapper<ApplyDetail>()
                .lambda()
                .eq(ApplyDetail::getApplyId,applyChange.getApplyId())
                .eq(ApplyDetail::getIdcardNo,detail.getIdcardNo())
                .le(ApplyDetail::getStartTime,DateUtil.getMontageDate(applyChange.getApplyStartTime(),1))
                .ge(ApplyDetail::getEndTime,DateUtil.getMontageDate(detail.getEndTime(),2))
        )>Constants.ZERO){
            throw new BusinessException(ResponseStatus.BAD_REQUEST.getCode(), "当前保单下,加保人员【" + detail.getMemberName() + "】存在日期冲突的数据");
        }
        //总天数
        Integer countDays = DateUtil.calculateBetween(applyChange.getApplyStartTime(),DateUtil.getMontageDate(detail.getEndTime(), 2),0);
        //加保
        ApplyDetail add = new ApplyDetail();
        if(new Date().compareTo(DateUtil.getMontageDate(applyChange.getApplyStartTime(), 2))>=0){
            Integer days =  DateUtil.calculateBetween(applyChange.getApplyStartTime(),DateUtil.getMontageDate(new Date(), 2),0);
            //如果已已产生费用,计算已已产生费用
            add.setCurrentFee(new BigDecimal(days).multiply(price));
        }else{
            add.setCurrentFee(BigDecimal.ZERO);
        }
        add.setApplyId(applyChange.getApplyId());
        add.setValidCode(applyChange.getValidCode());
        add.setFee(detail.getFee());
        add.setIsdeleted(Constants.ZERO);
        add.setCreator(applyChange.getEditor());
        add.setCreateDate(applyChange.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(DateUtil.getMontageDate(applyChange.getApplyStartTime(), 1));
        add.setEndTime(DateUtil.getMontageDate(detail.getEndTime(), 2));
        add.setFee(new BigDecimal(countDays).multiply(price));
        applyDetailJoinMapper.insert(add);
        detail.setFee(add.getFee());
        applyChagneDetailJoinMapper.update(null,new UpdateWrapper<ApplyChagneDetail>().lambda()
                .set(ApplyChagneDetail::getFee,add.getFee())
                .set(ApplyChagneDetail::getStartTime,DateUtil.getMontageDate(applyChange.getApplyStartTime(), 1))
                .eq(ApplyChagneDetail::getId,detail.getId())
        );
        totalFee = totalFee.add(add.getFee());
        currentFee = currentFee.add(add.getCurrentFee());
        MemberInsurance memberInsurance = new MemberInsurance(detail, applyChange, applyChange.getEditor(), add.getId(),applyChange.getSolutionsId());
        memberInsurance.setStartTime(add.getStartTime());
        memberInsurance.setEndTime(add.getEndTime());
        memberInsurance.setRelationType(Constants.ONE);
        memberInsuranceJoinMapper.insert(memberInsurance);
    }
    /**
     * 减保数据处理
     * @param applyChange
     * @param detail
     * @param currentFee
     * @param totalFee
     */
    public void reduceChangeDetailData(ApplyChange applyChange,ApplyChagneDetail detail,BigDecimal currentFee,BigDecimal totalFee){
        //查询员工是在主单下 是否存在生效中的数据
        ApplyDetail oldModel = applyDetailJoinMapper.selectOne(new QueryWrapper<ApplyDetail>().lambda()
                .eq(ApplyDetail::getApplyId, applyChange.getApplyId())
                .eq(ApplyDetail::getMemberId, detail.getMemberId())
                .orderByDesc(ApplyDetail::getCreateDate)
                .last("limit 1"));
        if (oldModel == null || oldModel.getStartTime() == null || oldModel.getStartTime().getTime() > applyChange.getApplyStartTime().getTime()) {
            throw new BusinessException(ResponseStatus.SERVER_ERROR.getCode(), "对不起,用户【" + detail.getMemberName() + "】原保单信息有误,当前申请不支持减保处理!");
        }
        //计算已生效天数
        //当审批时间 小于 当前时间 计算实际减少金额 因为已扣金额会大于 应扣金额
        BigDecimal pullFee = BigDecimal.ZERO;
        //减保减少的金额
        BigDecimal reduceFee = BigDecimal.ZERO;
        if (DateUtil.calculateBetween(applyChange.getApplyStartTime(),DateUtil.getMontageDate(new Date(), 2),0) > 0) {
            //计算多扣金额
            Integer days = DateUtil.calculateBetween(applyChange.getApplyStartTime(),DateUtil.getMontageDate(new Date(), 2),0);
            pullFee = new BigDecimal(days).multiply(detail.getPrice()).multiply(new BigDecimal(-1));
        }
        //计算投保明细应减少的天数
        Integer reduceDays = DateUtil.calculateBetween(applyChange.getApplyStartTime(),DateUtil.getMontageDate(oldModel.getEndTime(), 2),0);
        if(reduceDays>0){
            reduceFee = new BigDecimal(reduceDays).multiply(detail.getPrice()).multiply(new BigDecimal(-1));
        }
        applyDetailJoinMapper.update(null, new UpdateWrapper<ApplyDetail>().lambda()
                .setSql(" fee = ifnull(fee,0)+" + reduceFee)
                .setSql(" current_fee = ifnull(current_fee,0)+" + pullFee)
                .set(oldModel.getStartTime().compareTo(applyChange.getApplyStartTime())!=0,ApplyDetail::getEndTime, DateUtil.getMontageDate(applyChange.getApplyStartTime(), 3))
                .set(oldModel.getStartTime().compareTo(applyChange.getApplyStartTime())==0,ApplyDetail::getEndTime, DateUtil.getMontageDate(applyChange.getApplyStartTime(), 2))
                .set(ApplyDetail::getEditor, applyChange.getEditor())
                .set(ApplyDetail::getEditDate, applyChange.getEditDate())
                .eq(ApplyDetail::getId, oldModel.getId())
        );
        totalFee = totalFee.add(reduceFee);
        currentFee = currentFee.add(pullFee);
        //修改 员工投保明细记录 历史数据
        memberInsuranceJoinMapper.update(null, new UpdateWrapper<MemberInsurance>().lambda()
                .setSql(" fee = ifnull(fee,0)+" + reduceFee)
                .set(oldModel.getStartTime().compareTo(applyChange.getApplyStartTime())!=0,MemberInsurance::getEndTime,DateUtil.getMontageDate(applyChange.getApplyStartTime(), 3))
                .set(oldModel.getStartTime().compareTo(applyChange.getApplyStartTime())==0,MemberInsurance::getEndTime,DateUtil.getMontageDate(applyChange.getApplyStartTime(), 2))
                .eq(MemberInsurance::getRelationId, oldModel.getId())
        );
        //修改业务明细行数据实际批单日期
        applyChagneDetailJoinMapper.update(null,new UpdateWrapper<ApplyChagneDetail>().lambda()
                .setSql(" fee = ifnull(fee,0)+" + reduceFee)
                .set(ApplyChagneDetail::getEndTime,DateUtil.getMontageDate(applyChange.getApplyStartTime(), 3))
                .eq(ApplyChagneDetail::getId,detail.getId())
        );
    }
    public void otherChangeDetailData(ApplyChange applyChange,ApplyChagneDetail detail){
        //实际批单生效日期
        Date applyStartTime = DateUtil.getMontageDate(applyChange.getApplyStartTime(),1);
        //查询减保人员是否存在 冲突的 保单明细数据
        if(applyDetailJoinMapper.selectCount(new QueryWrapper<ApplyDetail>()
                .lambda()
                .eq(ApplyDetail::getApplyId,applyChange.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, applyChange.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()+"】原保单信息有误,批单日期未在保单日期内!");
        }
        //如果实际批单日期 和 原记录日期相等 则直接修改记录派遣单位与工种信息
        if(applyStartTime.compareTo(oldModel.getStartTime())!=Constants.ZERO){
            //当前日期大于批单日期 需要回滚数据实际数据
            Boolean flag = DateUtil.getMontageDate(new Date(),2).compareTo(DateUtil.getMontageDate(applyStartTime,2))>0;
            //换厂后历史记录的费用 fee
            Integer days = DateUtil.calculateBetween(DateUtil.getMontageDate(applyStartTime,3),DateUtil.getMontageDate(oldModel.getStartTime(),1),0);
            BigDecimal oldFee = new BigDecimal(days).multiply(detail.getPrice());
            BigDecimal fee = oldModel.getFee();
            BigDecimal oldCurrentFee = oldModel.getCurrentFee();
            applyDetailJoinMapper.update(null, new UpdateWrapper<ApplyDetail>().lambda()
                    .set(ApplyDetail::getEditor,applyChange.getEditor())
                    .set(ApplyDetail::getEditDate,applyChange.getEditDate())
                    .set(ApplyDetail::getEndTime,DateUtil.getMontageDate(applyStartTime,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,applyStartTime)
                    .set(MemberInsurance::getFee,oldFee)
                    .eq(MemberInsurance::getRelationId,oldModel.getId())
            );
            ApplyDetail add = new ApplyDetail();
            add.setApplyId(oldModel.getApplyId());
            add.setCreateDate(new Date());
            add.setCreator(applyChange.getEditor());
            add.setMemberId(oldModel.getMemberId());
            add.setIdcardNo(detail.getIdcardNo());
            add.setSex(Constants.getSexByIdCard(detail.getIdcardNo()));
            add.setMemberName(detail.getMemberName());
            add.setStartTime(DateUtil.getMontageDate(applyStartTime,1));
            add.setEndTime(oldModel.getEndTime());
            add.setDuId(detail.getDuId());
            add.setWorktypeId(detail.getWorktypeId());
            add.setIdcardNo(oldModel.getIdcardNo());
            add.setFee(fee.subtract(oldFee));
            add.setIsdeleted(Constants.ZERO);
            if(flag){
                add.setCurrentFee(oldCurrentFee.multiply(oldFee));
            }else{
                add.setCurrentFee(BigDecimal.ZERO);
            }
            add.setSex(oldModel.getSex());
            add.setMemberName(oldModel.getMemberName());
            add.setFromId(detail.getId());
            applyDetailJoinMapper.insert(add);
            MemberInsurance memberInsurance = new MemberInsurance(oldModel,applyChange.getId());
            memberInsurance.setSolutionId(detail.getSolutionId());
            memberInsurance.setWorktypeName(detail.getWorkTypeName());
            memberInsurance.setDuName(detail.getDuName());
            memberInsurance.setApplyChangeId(detail.getApplyChangeId());
            memberInsurance.setSolutionName(detail.getSolutionsName());
            memberInsurance.setPdCode(applyChange.getValidCode());
            memberInsurance.setBdCode(applyChange.getApplyCode());
            memberInsurance.setRelationType(Constants.ONE);
            memberInsuranceJoinMapper.insert(memberInsurance);
        }else{
            applyDetailJoinMapper.update(null, new UpdateWrapper<ApplyDetail>().lambda()
                    .set(ApplyDetail::getEditor,applyChange.getEditor())
                    .set(ApplyDetail::getEditDate,applyChange.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())
            );
        }
    }
}