package com.bcxin.ins.service.preservation.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bcxin.ins.service.common.ModelSendService;
import com.bcxin.ins.service.preservation.*;
import com.bcxin.ins.service.product.ProductService;
import com.bcxin.ins.spring.executor.MyAsyncExecutor;
import com.bcxin.ins.spring.util.JedisUtils;
import com.bcxin.ins.third.gzzrx.changan.GZZRX_CARequestService;
import com.bcxin.ins.third.gzzrx.pingancai.GZZRX_PACRequestService;
import com.bcxin.ins.third.gzzrx.qianhai.GZZRX_QHRequestService;
import com.bcxin.ins.third.gzzrx.renbao.GZZRX_RBRequestService;
import com.bcxin.ins.enums.TransTypeEnum;
import com.bcxin.ins.third.gzzrx.taibao.GZZRX_TBRequestService;
import com.bcxin.ins.third.gzzrx.zhonghua.GZZRX_ZHRequestService;
import com.bcxin.ins.third.tyx.changan.TYX_CARequestService;
import com.bcxin.ins.third.tyx.huatai.TYX_HTRequestService;
import com.bcxin.ins.third.tyx.pingancai.PACRequestService;
import com.bcxin.ins.third.tyx.qianhai.TYX_QHRequestService;
import com.bcxin.ins.third.tyx.renbao.PackageMessageRB;
import com.bcxin.ins.third.tyx.renbao.RBRequestService;
import com.bcxin.ins.service.order.ComTaskResidualAPIService;
import com.bcxin.ins.service.order.InsRoleInpolicyAPIService;
import com.bcxin.ins.service.order.PolicyService;
import com.bcxin.ins.dao.preservation.InsPreservationRecordAPIDao;
import com.bcxin.ins.core.service.ComDeployConfigService;
import com.bcxin.ins.entity.policy_core.*;
import com.bcxin.ins.util.*;
import com.bcxin.ins.util.email.*;
import com.bcxin.ins.util.http.HuaWeiSmsContent;
import com.bcxin.ins.vo.*;
import com.bcxin.ins.vo.ConstProp;
import com.bcxin.mybatisplus.plugins.Page;
import com.bcxin.mybatisplus.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;


@Service
@Transactional
public class InsPreservationRecordAPIServiceImpl extends ServiceImpl<InsPreservationRecordAPIDao, InsPreservationRecord> implements InsPreservationRecordAPIService {

    private Logger log =  LoggerFactory.getLogger(InsPreservationRecordAPIServiceImpl.class);

    @Autowired
    private InsPreservationRecordAPIDao insPreservationRecordAPIDao;

    @Autowired
    private InsPreservationDetailAPIService insPreservationDetailAPIService;

    @Autowired
    private InsPreservationResultSetAPIService insPreservationResultSetAPIService;
    @Autowired
    private InsPreservationPayAPIService insPreservationPayAPIService;
    @Autowired
    private InsRoleInpolicyAPIService insRoleInpolicyService;
    @Autowired
    private PolicyService policyService;
    @Autowired
    private ProductService productService;
    @Autowired
    private ComDeployConfigService comDeployConfigService;
    @Autowired
    private GZZRX_RBRequestService gZZRX_RBRequestService;
    @Autowired
    private RBRequestService rBRequestService;
    @Autowired
    private GZZRX_ZHRequestService gZZRX_ZHRequestService;
    @Autowired
    private GZZRX_PACRequestService gZZRX_PACRequestService;
    @Autowired
    private GZZRX_CARequestService gZZRX_CARequestService;
    @Autowired
    private TYX_CARequestService tYX_CARequestService;
    @Autowired
    private GZZRX_QHRequestService gZZRX_QHRequestService;
    @Autowired
    private GZZRX_TBRequestService gZZRX_TBRequestService;
    @Autowired
    private TYX_QHRequestService tYX_QHRequestService;
    @Autowired
    private PACRequestService pACRequestService;
    @Autowired
    private TYX_HTRequestService tYX_HTRequestService;
    @Autowired
    private ModelSendService mss;
    @Autowired
    private RecordUpdateStrategy recordUpdateStrategy;

    @Autowired
    private ComTaskResidualAPIService comTaskResidualAPIService;

    @Autowired
    private MyAsyncExecutor myAsyncExecutor;

    /**
     * <b>根据前台用户id跟保全条件查询保全申请单表并进行分页 </b>
     *
     * @param page 分页
     * @param userId 用户id
     * @param revise_status 批改状态
     * @param start_time 提交申请开始时间
     * @param end_time 提交申请最后时间
     * @param keyword 关键字
     * @return
     * @author ZXF
     * @date 2017年8月3日 下午17:19:24
     * @注意事项 </b>
     * <b>
     */
    public List<InsPreservationRecord> findInsPreservationRecordByKeyword(DwzPage page, Long userId, String revise_status, String start_time, String end_time, String keyword){
        Page<InsPreservationRecord> pageHelper = new Page(page.getPageNum(), page.getNumPerPage());
        List<InsPreservationRecord> list = insPreservationRecordAPIDao.findInsPreservationRecordByKeyword( pageHelper, userId, revise_status, start_time, end_time, keyword);
        page.setTotalCount(new Long(pageHelper.getTotal()).intValue());
        return list;
    }

    /**
     * <b> 统计待审核批单条数 </b>
     * @author ZXF
     * @create 2021/05/10 0010 9:44
     * @version
     * @注意事项 </b>
     */
    @Override
    public boolean countDSHByPolicyNo(String policyNo){
        int count = insPreservationRecordAPIDao.countDSHByPolicyNo(policyNo);
        return count>0?true:false;
    }

    /**
     * <b>根据保全申请单id查询InsPreservationRecordVo </b>
     *
     * @param oid
     * @return
     * @author ZXF
     * @date 2017年1月9日 下午8:21:24
     * @注意事项 </b>
     * <b>
     */
    @Override
    public InsPreservationRecordVo findInsPreservationRecordVoById(Long oid){
        InsPreservationRecordVo vo = insPreservationRecordAPIDao.findInsPreservationRecordVoById(oid);
        if(vo == null){
            return vo;
        }
        List<InsPreservationDetailVo> ipdVolist = insPreservationDetailAPIService.findInsPreservationDetailVoByPreservationId("",oid);
        //排除增员的单子
        if(ConstProp.DIGIT_ONE.equals(vo.getRevise_type())){
            vo.setInsPreservationDetailVoList(ipdVolist);
            return vo;
        }
        InsPreservationDetailVo detailVo;
        String[] arr;
        for(InsPreservationDetailVo ipdVo : ipdVolist){
            if(StringUtils.isNotBlank(ipdVo.getBusiness_str())){
                arr = ipdVo.getBusiness_str().split("#");
                detailVo = new InsPreservationDetailVo();
                detailVo.setName(arr[0]);
                detailVo.setId_card(arr[1]);
                detailVo.setId_type(arr[2]);
                detailVo.setTel(arr[3]);
                detailVo.setBirthday(arr[4]);
                detailVo.setSex(arr[5]);
                detailVo.setCareer(arr[6]);
                ipdVo.setBusiness_vo(detailVo);
            }
        }
        vo.setInsPreservationDetailVoList(ipdVolist);
        return vo;
    }

    /**
     * <b> 待审核批单补偿确认 </b>
     * @author ZXF
     * @create 2024/01/02 0002 15:30
     * @version
     * @注意事项 </b>
     */
    private void compensateRecord(Long policyId){
        List<String> list = selectRecordIdByPolicyIdAndStatus(policyId, "2", "");
        for (String record_id:list) {
            addFindPDTask(record_id);
        }
    }

    /**
     * <b> 获取电子批单 </b>
     * @author ZXF
     * @create 2020/11/12 0012 13:41
     * @version
     * @注意事项 </b>
     */
    @Override
    public boolean getDZPD(Long preservationId){
        InsPreservationRecord record = insPreservationRecordAPIDao.selectById(preservationId);
        //获取电子批单
        String path = printDZPD(record.getIns_preservation_record_id(),record.getRevise_serial_num_ins());
        return StringUtils.isEmpty(path)?false:true;
    }

    /**
     * <b>
     *     根据保全单id查询保全信息
     * </b>
     * @author ZXF
     * @create 2018/06/06 0006 15:45
     * @version
     * @注意事项 </b>
     */
    @Override
    public InsPreservationRecordVo findIPRVoById(Long oid){
        return insPreservationRecordAPIDao.findInsPreservationRecordVoById(oid);
    }

    @Override
    public InsPreservationRecord findInsPreservationRecordByBySerialNum(String serial_num){
        Map<String, Object> columnMap = Maps.newHashMap();
        columnMap.put("revise_serial_num_ins",serial_num);
        List<InsPreservationRecord> list = insPreservationRecordAPIDao.selectByMap(columnMap);
        return list.size()>0 ? list.get(0) : null;
    }

    @Override
    public InsPreservationRecord findInsPreservationRecordBySerialNumber(String serial_number){
        Map<String, Object> columnMap = Maps.newHashMap();
        columnMap.put("revise_serial_number",serial_number);
        List<InsPreservationRecord> list = insPreservationRecordAPIDao.selectByMap(columnMap);
        return list.size()>0 ? list.get(0) : null;
    }
    @Override
    public List<InsPreservationRecord> findNotResultRecord(String day){
        List<InsPreservationRecord> list = insPreservationRecordAPIDao.findNotResultRecord(day);
        return list;
    }


    /**
     * <b>根据订单id查询相关保全申请单最后‘已审核’状态的申请单 </b>
     * @param policyID
     * @return
     * @author ZXF
     * @date 2017年1月9日 下午8:21:24
     * @注意事项 </b>
     * <b>
     */
    @Override
    public InsPreservationRecord findInsPreservationRecordByPolicyID(Long policyID){
        InsPreservationRecord ipr = null;
        List<InsPreservationRecord> list = insPreservationRecordAPIDao.findInsPreservationRecordByPolicyID(policyID);
        if(list!=null && !list.isEmpty()){
            ipr = list.get(ConstProp.INT_NUMBER_ZERO);
        }
        return ipr;
    }

    /**
     * <b>根据前台保全缴费id跟保全条件查询保全申请单vo列表并进行分页 </b>
     *
     * @param page 分页
     * @param payId 保全缴费id
     * @param keyword 关键字
     * @return
     * @author ZXF
     * @date 2017年8月3日 下午17:19:24
     * @注意事项 </b>
     * <b>
     */
    @Override
    public List<InsPreservationRecordVo> findInsPreservationRecordVoByPayId(DwzPage page, Long payId, String keyword){
        if(page == null){
            page = new DwzPage();
        }
        Page<InsPreservationRecordVo> pageHelper = new Page(page.getPageNum(), page.getNumPerPage());
        List<InsPreservationRecordVo> list = insPreservationRecordAPIDao.findInsPreservationRecordVoByPayId( pageHelper, payId, keyword);
        page.setTotalCount(new Long(pageHelper.getTotal()).intValue());
        return list;
    }

    /**
     * 初始化保全申请单
     * @param vo 订单信息，通过订单id查询出的OrderFormVo
     * @param revise_type 保全类型1.增员；2.减员；3.替换
     * @param AddNum 保全人数
     * @param inception_date 生效日期
     * @param policyID 订单id
     * @param status 设置的状态（待提交0/待审核1）
     * @param revise_serial_number 暂批改单号
     */
    private InsPreservationRecord initInsPreservationRecord(OrderFormVo vo,String revise_type,int AddNum,Date inception_date,Long policyID,String status,String revise_serial_number){
        InsPreservationRecord ipr = new InsPreservationRecord();
        ipr.setInception_date(inception_date);
        ipr.setStart_time(new Date());
        ipr.setIns_insurance_slip_id(policyID);
        //如果外部已经分配暂批单号就用已分配的，否则新生成一个
        if(StringUtils.isEmpty(revise_serial_number)){
            IdWorker idWorker = new IdWorker(ConstProp.INT_NUMBER_WORKERID, ConstProp.INT_NUMBER_ZERO);
            revise_serial_number =String.valueOf(idWorker.nextId());
        }
        ipr.setRevise_serial_number(revise_serial_number);
        ipr.setRevise_status(status);
        ipr.setRevise_type(revise_type);
        if(DictConst.REVISE_TYPE_Z.equals(revise_type)){
            ipr.setAdd_count(AddNum);
        }else if(DictConst.REVISE_TYPE_J.equals(revise_type)){
            ipr.setMinus_count(AddNum);
        }else if(DictConst.REVISE_TYPE_T.equals(revise_type)){
            ipr.setReplace_count(AddNum);
        }
        ipr.setApp_role_name(vo.getApplicant_name());
        ipr.setPlanned_end_date(DateUtil.convertStringToDate(vo.getPlanned_end_date()));
        ipr.setExternal_reference(vo.getExternal_reference());
        ipr.setSys_client_user_id(Long.parseLong(vo.getUser_oid()));
        ipr.setSys_ins_company_id(Long.parseLong(vo.getInsurance_oid()));
        insert(ipr);
        return ipr;
    }

    /**
     * 更新保全信息
     * @param preservationID 保全申请单id
     * @param AddNum 保全人数
     * @param inception_date 生效日期
     * @param status 设置的状态（待提交0/待审核1）
     */
    private InsPreservationRecord updateInsPreservationRecord(Long preservationID,int AddNum,Date inception_date,String status){
        InsPreservationRecord ipr = selectById(preservationID);
        ipr.setInception_date(inception_date);
        ipr.setUpdate_time(new Date());
        if(DictConst.REVISE_TYPE_Z.equals(ipr.getRevise_type())){
            ipr.setAdd_count(AddNum);
        }else if(DictConst.REVISE_TYPE_J.equals(ipr.getRevise_type())){
            ipr.setMinus_count(AddNum);
        }else if(DictConst.REVISE_TYPE_T.equals(ipr.getRevise_type())){
            ipr.setReplace_count(AddNum);
        }
        ipr.setRevise_status(status);
        updateById(ipr);
        return ipr;
    }

    /**
     * 创建保全申请单，做增员，减员，替换动作
     * @param sign 标记变更是否提交审核（0.暂存=1，1.提交审核=2）
     * @param iprVo 保全单信息（存有1.oid 自身id,2.inception_date 生效的时间,3.ins_insurance_slip_id 订单id,4.revise_type 保全状态）
     * @param ipdVoList 保全的人员
     * @return
     */
    @Override
    public boolean createInsPreservationRecord(int sign,InsPreservationRecordVo iprVo, List<InsPreservationDetailVo> ipdVoList){
        boolean flag = false;
        try {
            OrderFormVo vo = policyService.accordingToOrderIDToGetPolicyDto(Long.parseLong(iprVo.getIns_insurance_slip_id()));
            if(vo == null||ipdVoList==null || ipdVoList.isEmpty()){
                return flag;
            }
            InsPreservationRecord ipr = null;
            String revise_status = DictConst.REVISE_STATUS_ZC;
            Date inception_date = null;
            if(StringUtils.isNotBlank(iprVo.getInception_date())){
                inception_date = DateUtil.convertStringToDate(iprVo.getInception_date());
            }
            int count = ipdVoList.size();
            if(sign == 1){//提交审核
                revise_status = DictConst.REVISE_STATUS_SPZ;
            }
            if(StringUtils.isNotBlank(iprVo.getOid())){
                ipr = updateInsPreservationRecord(Long.parseLong(iprVo.getOid()),count,inception_date,revise_status);
            }else{
                ipr = initInsPreservationRecord(vo,iprVo.getRevise_type(),count,inception_date,Long.parseLong(iprVo.getIns_insurance_slip_id()),revise_status,iprVo.getRevise_serial_number());
            }
            if(NumberUtils.isNumber(iprVo.getTotal_premium())){
                ipr.setTotal_premium(new BigDecimal(iprVo.getTotal_premium()));
                updateById(ipr);
            }
            insPreservationDetailAPIService.saveOrUpdateInsPreservationDetail(ipr.getRevise_type(),ipr.getIns_preservation_record_id(),ipdVoList);
            Long oid = ipr.getIns_preservation_record_id();
            iprVo.setOid(String.valueOf(oid));
            String ind = iprVo.getInception_date();
            if(DictConst.REVISE_STATUS_SPZ.equals(revise_status)){
                myAsyncExecutor.execute(()->{
                    try {
                        //邮件发送
                        sendPreservationEmail(vo.getProduct_code(),ConstProp.BLANK_CHAR,htmlContentByPreservationRecord(vo,ipdVoList,ind));
                    } catch(Exception e) {

                    }
                });
            }
            flag = true;
        }catch (Exception e){
            log.error("创建保全申请单，做增员，减员，替换更新过程事务发现异常，回滚数据",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return flag;
    }

    /**
     * <b>
     *     修改保全单状态为已审核
     * </b>
     * @param record_id 保全单id
     * @author ZXF
     * @create 2018/06/06 0006 14:00
     * @version
     * @注意事项 </b>
     */
    @Override
    public void updateRecordStatus(String record_id, Map<String,String> map){
        try {
            if(map == null){
                return;
            }
            InsPreservationRecord record = insPreservationRecordAPIDao.selectById(Long.parseLong(record_id));
            //如果已出单的不可再做数据变动
            if(DictConst.REVISE_STATUS_TG.equals(record.getRevise_status())||DictConst.REVISE_STATUS_SX.equals(record.getRevise_status())){
                return;
            }
            OrderFormVo vo = policyService.accordingToOrderIDToGetPolicyDto(record.getIns_insurance_slip_id());
            int sign = 0;
            if(StringUtils.isNotEmpty(vo.getProduct_code())){
                sign = getSignAndSetRecord(map, record, vo, sign);
            }
            if(sign == 1){
                //状态
                record.setRevise_status(DictConst.REVISE_STATUS_TG);
                record.setUpdate_time(new Date());
                //初始化保全缴费信息
                insPreservationPayAPIService.setIPPay(record, map);
                //审核通过后推送给百保盾（SAAS）
                policyService.pushRecordInfo(record_id);

                /*new Thread(()->{
                    if("1".equals(GlobalResources.map.get("IS_SEND_SHOP"))){
                        //添加推送批单信息给到商城
                        comTaskResidualAPIService.saveComTaskResidual("createSendOrderTask","保险订单推送商城初始化","com.bcxin.ins.service.order.PolicyService",3,"Long,int,String", record_id+",1,");
                    }
                }).start();*/
                myAsyncExecutor.execute(()->{
                    //获取电子批单
                    printDZPD(Long.parseLong(record_id),record.getRevise_serial_num_ins());
                });
                //是否关闭批单同步业支 1：是，0：否
                if(!ConstProp.DIGIT_ONE.equals(GlobalResources.IS_CLOSE_RECORD_SYNC)) {
                    myAsyncExecutor.execute(()->{
                        //审核通过后推送业务支撑
                        policyService.recordSyncZC(record_id);
                    });
                }
                myAsyncExecutor.execute(()->{
                    //审核通过后发送邮件和短信给投保人
                    sendEmailAndTelByRecord(record);
                });
            }
        }catch (Exception e){
            log.error("修改保全单状态为已审核过程事务发现异常，回滚数据",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

    }

    /**
     * <b>
     *     修改保全单状态为已审核
     * </b>
     * @param revise_serial_number 暂批单号
     * @param revise_serial_num_ins 批单号
     * @param eurl 电子批单
     * @author ZXF
     * @create 2018/06/06 0006 14:00
     * @version
     * @注意事项 </b>
     */
    @Override
    public String updateHTRecordStatus(String revise_serial_number, String revise_serial_num_ins, String eurl, String edrResult, String edrInfo){
        try {
            InsPreservationRecord record = findInsPreservationRecordBySerialNumber(revise_serial_number);
            //如果已出单的不可再做数据变动
            if(DictConst.REVISE_STATUS_TG.equals(record.getRevise_status())||DictConst.REVISE_STATUS_BTG.equals(record.getRevise_status())||DictConst.REVISE_STATUS_SX.equals(record.getRevise_status())){
                return "";
            }
            //批单失败结果处理
            if(!"01".equals(edrResult)){
                record.setRevise_status(DictConst.REVISE_STATUS_BTG);
                record.setUpdate_time(new Date());
                insPreservationRecordAPIDao.updateRecordFail(record.getIns_preservation_record_id()+"",DictConst.REVISE_STATUS_BTG,edrInfo);
                return "";
            }
            //状态
            record.setRevise_status(DictConst.REVISE_STATUS_TG);
            record.setRevise_serial_num_ins(revise_serial_num_ins);
            record.setRevise_path(eurl);
            record.setUpdate_time(new Date());
            System.out.println("=========== updateHTRecordStatus:1");
            //初始化保全缴费信息
            insPreservationPayAPIService.setIPPay(record, null);
            System.out.println("=========== updateHTRecordStatus:2");
            //审核通过后推送给百保盾（SAAS）
            policyService.pushRecordInfo(record.getIns_preservation_record_id()+"");
            System.out.println("=========== updateHTRecordStatus:3");
            myAsyncExecutor.execute(()->{
                //获取电子批单
                printDZPD(record.getIns_preservation_record_id(),record.getRevise_serial_num_ins());
            });
            System.out.println("=========== updateHTRecordStatus:4");
            //是否关闭批单同步业支 1：是，0：否
            if(!ConstProp.DIGIT_ONE.equals(GlobalResources.IS_CLOSE_RECORD_SYNC)) {
                myAsyncExecutor.execute(()->{
                    //审核通过后推送业务支撑
                    policyService.recordSyncZC(record.getIns_preservation_record_id()+"");
                });
            }
            System.out.println("=========== updateHTRecordStatus:5");
            myAsyncExecutor.execute(()->{
                //审核通过后发送邮件和短信给投保人
                sendEmailAndTelByRecord(record);
            });
        }catch (Exception e){
            log.error("修改保全单状态为已审核过程事务发现异常，回滚数据",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return e.getMessage();
        }
        return "";
    }

    /**
     * <b> 捞结算日期大于昨天的保全记录推送商城 </b>
     * @author ZXF
     * @create 2024/05/09 0009 16:36
     * @version
     * @注意事项 </b>
     */
    public void pushRecordToShop(){
        String yesterday = DateUtil.getYesterday();
        List<String> list = insPreservationRecordAPIDao.findRecordIdsByPayTime(yesterday);
        for(String record_id : list){
            myAsyncExecutor.execute(()->{
                policyService.createSendOrderTask(Long.parseLong(record_id),1,"");
            });
        }
    }

    /**
     * <b> 批单信息设置 </b>
     * @author ZXF
     * @create 2020/09/27 0027 14:40
     * @version
     * @注意事项 </b>
     */
    /*private int getSignAndSetRecord(Map<String, String> map, InsPreservationRecord record, OrderFormVo vo, int sign) {
        if(vo.getProduct_code().contains(ConstProp.GZZRX_RB)
                ||vo.getProduct_code().contains(ConstProp.TYX_RB)
                ||vo.getProduct_code().contains(ConstProp.TYX_PAC)
                ||vo.getProduct_code().contains(ConstProp.GZZRX_PAC)){
            if(map.get("batchNumber").contains("未查询到该批单申请号")){
                //人保需要过滤
                *//* 拿到批单申请号调人保接口获取批单号，建立修改批单号的任务*//*
                String batch_number = map.get("batchNumber").replace("未查询到该批单申请号","").replace("的批单号！","");
                new Thread(()->{
                    //异步
                    Map parems = Maps.newHashMap();
                    parems.put("record_id",String.valueOf(record.getIns_preservation_record_id()));
                    parems.put("batch_number",batch_number);
                    comTaskResidualAPIService.saveComTaskResidual("updateBatchNumber","修改人保保全批单号","com.bcxin.ins.service.preservation.InsPreservationRecordAPIService",1,"String", JSONObject.toJSONString(parems));
                }).start();
            }
            //批改单号
            record.setRevise_serial_num_ins(map.get("batchNumber"));
            if(StringUtils.isNotEmpty(map.get("premium"))){
                record.setTotal_premium(BigDecimal.valueOf(Double.parseDouble(map.get("premium"))));
            }
            sign = 1;
        }else if(vo.getProduct_code().contains(ConstProp.GZZRX_TB)){//太平洋保险 雇主责任险
            if(StringUtils.isEmpty(map.get("batchNumber")) && DictConst.REVISE_TYPE_Z.equals(record.getRevise_type())){
                record.setRevise_pay(map.get("payurl"));
                if(StringUtils.isNotEmpty(map.get("batchApplyNumber"))&& !map.get("batchApplyNumber").equals(record.getRevise_serial_number())){
                    record.setRevise_serial_number(map.get("batchApplyNumber"));
                }
                record.setRevise_status(DictConst.REVISE_STATUS_SPZ);
            }else{
                record.setRevise_serial_num_ins(map.get("batchNumber"));
                record.setRevise_path(map.get("eurl"));
                sign = 1;
            }
            insPreservationRecordAPIDao.updateById(record);
        }
        else if(vo.getProduct_code().contains(ConstProp.GZZRX_ZH)){
            //批改单号
            record.setRevise_serial_num_ins(map.get("batchNumber"));
            if(StringUtils.isNotEmpty(map.get("premium"))){
                record.setTotal_premium(BigDecimal.valueOf(Double.parseDouble(map.get("premium"))));
            }
            record.setRevise_path(map.get("eurl"));
            if(StringUtils.isNotEmpty(map.get("tbsxsj"))){
                record.setInception_date(DateUtil.parseDate(map.get("tbsxsj")));
            }
            sign = 1;
        }else if(vo.getProduct_code().contains(ConstProp.GZZRX_CA)){
            //长安返回的暂批改单号
            record.setRevise_serial_number(map.get("batchNumber"));
            if(StringUtils.isNotEmpty(map.get("premium"))){
                record.setTotal_premium(BigDecimal.valueOf(Double.parseDouble(map.get("premium"))));
            }
            if(map.get("eurl")!=null){
                record.setRevise_path(map.get("eurl"));
            }
            insPreservationRecordAPIDao.updateById(record);
        }else if(vo.getProduct_code().contains(ConstProp.TYX_CA)){
            //长安返回的暂批改单号
            record.setRevise_serial_num_ins(map.get("batchNumber"));
            if(StringUtils.isNotEmpty(map.get("premium"))){
                record.setTotal_premium(BigDecimal.valueOf(Double.parseDouble(map.get("premium"))));
            }
            if(map.get("eurl")!=null){
                record.setRevise_path(map.get("eurl"));
            }
            sign = 1;
        }else if(vo.getProduct_code().contains(ConstProp.TYX_HT)){
            //华泰返回的批单申请单号
            record.setRevise_serial_number(map.get("batchNumber"));
            if(StringUtils.isNotEmpty(map.get("premium"))){
                record.setTotal_premium(BigDecimal.valueOf(Double.parseDouble(map.get("premium"))));
            }
            record.setRevise_status(DictConst.REVISE_STATUS_SPZ);
            insPreservationRecordAPIDao.updateById(record);
            //到这里map作用结束，外层根据该值判断批单在待审核阶段
            //map = null;
        }else if(vo.getProduct_code().contains(ConstProp.GZZRX_QH)){
            record.setRevise_serial_num_ins(map.get("batchNumber"));
            if(StringUtils.isNotEmpty(map.get("premium"))){
                record.setTotal_premium(BigDecimal.valueOf(Double.parseDouble(map.get("premium"))));
            }
            if(map.get("eurl")!=null){
                record.setRevise_path(map.get("eurl"));
            }
            sign = 1;
        }
        return sign;
    }*/

     private int getSignAndSetRecord(Map<String, String> map, InsPreservationRecord record, OrderFormVo vo, int sign) {
        String productCode = vo.getProduct_code();

        // 人保系列
        if (isRenbaoProduct(productCode)) {
            return recordUpdateStrategy.handleRenbaoUpdate(map, record, vo, sign);
        }
        // 平安财系列
        if (isPingAnCaiProduct(productCode)) {
            return recordUpdateStrategy.handlePingAnCaiUpdate(map, record, vo, sign);
        }
        // 太平洋系列
        else if (isTaiBaoProduct(productCode)) {
            return recordUpdateStrategy.handleTaipingyangUpdate(map, record, sign);
        }
        // 中华系列
        else if (isZhongHuaProduct(productCode)) {
            return recordUpdateStrategy.handleZhonghuaUpdate(map, record, sign);
        }
        // 长安系列
        else if (isChanganProduct(productCode)) {
            return recordUpdateStrategy.handleChanganUpdate(map, record, productCode, sign);
        }
        // 华泰系列
        else if (isHuaTaiProduct(productCode)) {
            return recordUpdateStrategy.handleHuataiUpdate(map, record, sign);
        }
        // 前海系列
        else if (isQianhaiProduct(productCode)) {
            return recordUpdateStrategy.handleQianhaiUpdate(map, record, sign);
        }

        return sign;
    }

    private boolean isRenbaoProduct(String productCode) {
        return productCode.contains(ConstProp.GZZRX_RB)
                || productCode.contains(ConstProp.TYX_RB);
    }
    private boolean isPingAnCaiProduct(String productCode) {
        return productCode.contains(ConstProp.TYX_PAC)
                || productCode.contains(ConstProp.GZZRX_PAC);
    }

    private boolean isChanganProduct(String productCode) {
        return productCode.contains(ConstProp.GZZRX_CA)
                || productCode.contains(ConstProp.TYX_CA);
    }

    private boolean isQianhaiProduct(String productCode) {
        return productCode.contains(ConstProp.GZZRX_QH);
    }
    private boolean isHuaTaiProduct(String productCode) {
        return productCode.contains(ConstProp.TYX_HT);
    }
    private boolean isZhongHuaProduct(String productCode) {
        return productCode.contains(ConstProp.GZZRX_ZH);
    }
    private boolean isTaiBaoProduct(String productCode) {
        return productCode.contains(ConstProp.GZZRX_TB);
    }



    /**
     * 保全申请-审核退回 发送邮件
     * 发送方：系统（bot）
     * 接收方：投保人
     *
     * @param record record_id 保全申请单id
     */
    private void sendEmailAndTelByRecord(InsPreservationRecord record) {
        String status = record.getRevise_status();
        OrderFormVo vo = policyService.accordingToOrderIDToGetPolicyDto(record.getIns_insurance_slip_id());
        List<InsRoleInpolicy> iriList = insRoleInpolicyService.getInsRoleInpolicyListByIDAndKind(record.getIns_insurance_slip_id(), "1");
        String email = ConstProp.BLANK_CHAR;
        String tel = ConstProp.BLANK_CHAR;
        if(iriList.size()>0){
            email = iriList.get(0).getLink_email();
            tel = iriList.get(0).getLink_tel();
        }
        String reviseType = DictConst.REVISE_TYPE_Z.equals(record.getRevise_type())? "增员"
                : DictConst.REVISE_TYPE_J.equals(record.getRevise_type())? "减员"
                : DictConst.REVISE_TYPE_T.equals(record.getRevise_type())? "替换"
                : ConstProp.BLANK_CHAR;
        String personNum = DictConst.REVISE_TYPE_Z.equals(record.getRevise_type())? String.valueOf(record.getAdd_count())
                : DictConst.REVISE_TYPE_J.equals(record.getRevise_type())? String.valueOf(record.getMinus_count())
                : DictConst.REVISE_TYPE_T.equals(record.getRevise_type())? String.valueOf(record.getReplace_count())
                : ConstProp.BLANK_CHAR;
        if(StringUtils.isNotBlank(email)){
            EmailMsgRecordType emr = null;
            if(ConstProp.DIGIT_THREE.equals(status)){
                //审核退回
                emr = EmailMsgRecordType.RECORD_SEND_BACK;
            }else if(ConstProp.DIGIT_FOUR.equals(status)){
                //审核通过
                emr = EmailMsgRecordType.RECORD_CHECKED;
            }
            EmailModel emailModel = new EmailModel(emr, DateUtil.convertDateToString(record.getStart_time(),DateUtil.FORMAT1_1), reviseType, personNum, vo.getTrade_serial_number(), record.getExternal_reference(), record.getRevise_serial_number());
            log.info(emr.getName()+"邮件发送（内容htmlContent）:"+emailModel.getContent());
            List<String> emailList = new ArrayList<String>();
            emailList.add(email.trim());
            log.info(emr.getName()+"邮件发送（收件人Email-1）:"+email);
            emailModel.setTo(emailList);
            SendEmailAndMsgUtil.sendEmail(emailModel);
        }
        if(StringUtils.isNotBlank(tel)){
            //短信内容（弃用），只为了输出日志
            String content = ConstProp.BLANK_CHAR;
            if(ConstProp.DIGIT_THREE.equals(status)){
                //审核退回
                content = new MessageModel(DateUtil.convertDateToString(record.getStart_time(),DateUtil.FORMAT1_1)
                        ,reviseType
                        ,personNum
                        ,record.getRevise_serial_number()
                        ,ConstProp.BLANK_CHAR
                        , EmailMsgType.BQTH).getContent();
                log.info("保全申请审核退回短信发送（内容htmlContent）:"+content);
                //华为短信发送
                mss.sendHuaWeiSMS(new HuaWeiSmsContent(
                        ConstProp.SMSPLATFORM_BLB,
                        ConstProp.SMSCODE_B7,
                        tel,
                        JSON.toJSONString(new String[]{DateUtil.convertDateToString(record.getStart_time(),DateUtil.FORMAT1_1)
                                ,reviseType
                                ,personNum
                                ,record.getRevise_serial_number()})));
            }else if(ConstProp.DIGIT_FOUR.equals(status)){
                //审核通过（由于提交频繁关闭短信业务）
//                content = new MessageModel(DateUtil.convertDateToString(record.getStart_time(),DateUtil.FORMAT1_1)
//                        ,reviseType
//                        ,personNum
//                        ,record.getRevise_serial_number()
//                        ,DateUtil.convertDateToString(record.getInception_date(),DateUtil.FORMAT1)
//                        , EmailMsgType.BQTG).getContent();
//                log.info("保全申请审核通过短信发送（内容htmlContent）:"+content);
//                //华为短信发送
//                SMSUtil.sendHuaWeiSMS(new HuaWeiSmsContent(
//                        ConstProp.SMSPLATFORM_BLB,
//                        ConstProp.SMSCODE_B8,
//                        tel,
//                        JSON.toJSONString(new String[]{reviseType
//                                ,personNum
//                                ,record.getRevise_serial_number()
//                                ,DateUtil.convertDateToString(record.getInception_date(),DateUtil.FORMAT1)})));
            }

            log.info("保全申请短信发送（收件人Modle-1）:"+tel);
//            mss.sendModleMessage("blb", content, tel);
        }
    }

    /**
     * 减员做修改用该方法，只做保全申请单修改，不对保全人员做更新，因为减员不存在修改人员只做删除所以这方法主要用来更新当前人员数量级生效日期变更就行
     * @param sign
     * @param iprVo
     * @param ipdVoList
     * @return
     */
    @Override
    public boolean minusInsPreservationRecord(int sign,InsPreservationRecordVo iprVo, List<InsPreservationDetailVo> ipdVoList){
        boolean flag = false;
        try {
            OrderFormVo vo = policyService.accordingToOrderIDToGetPolicyDto(Long.parseLong(iprVo.getIns_insurance_slip_id()));
            if(vo == null || ipdVoList==null || ipdVoList.isEmpty()){
                return flag;
            }
            String revise_status = DictConst.REVISE_STATUS_ZC;
            int count = ipdVoList.size();
            if(DictConst.RECORD_SIGN_TJ.equals(String.valueOf(sign))){
                //提交审核
                revise_status = DictConst.REVISE_STATUS_SPZ;
            }
            if(StringUtils.isNotBlank(iprVo.getOid())){
                Date inception_date = null;
                if(StringUtils.isNotBlank(iprVo.getInception_date())){
                    inception_date = DateUtil.convertStringToDate(iprVo.getInception_date());
                }
                updateInsPreservationRecord(Long.parseLong(iprVo.getOid()),count,inception_date,revise_status);
                flag = true;
            }
            String inception_date = iprVo.getInception_date();
            if(DictConst.REVISE_STATUS_SPZ.equals(revise_status)){
                myAsyncExecutor.execute(()->{
                    //异步发送保全邮件
                    try {
                        //邮件发送
                        sendPreservationEmail(vo.getProduct_code(),ConstProp.BLANK_CHAR,htmlContentByPreservationRecord(vo,ipdVoList,inception_date));
                    } catch(Exception e) {

                    }
                });
            }
        }catch (Exception e){
            log.error("保全申请单更新过程事务发现异常，回滚数据",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return flag;
    }

    @Override
    public boolean againRecord(Long oid){
        boolean flag = true;
        InsPreservationRecord ipr = selectById(oid);

        if(ipr == null){
            return false;
        }
        InsPreservationRecordVo vo = findInsPreservationRecordVoById(oid);
        OrderFormVo ovo = policyService.accordingToOrderIDToGetPolicyDto(ipr.getIns_insurance_slip_id());
        //重新统计参与人员数
//        List<InsPreservationDetail> ipdList = insPreservationDetailAPIService.findInsPreservationDetailByKeyword(null,ipr.getIns_preservation_record_id(),ConstProp.BLANK_CHAR);
        if(ConstProp.DIGIT_ONE.equals(ipr.getRevise_type())){
            ipr.setAdd_count(vo.getInsPreservationDetailVoList().size());
        }else if(ConstProp.DIGIT_TWO.equals(ipr.getRevise_type())){
            ipr.setMinus_count(vo.getInsPreservationDetailVoList().size());
        }else{
            ipr.setReplace_count(vo.getInsPreservationDetailVoList().size());
        }
        if(StringUtils.isEmpty(ipr.getRevise_serial_number())){
            //重新分配暂批改单号
            IdWorker idWorker = new IdWorker(ConstProp.INT_NUMBER_WORKERID, ConstProp.INT_NUMBER_ZERO);
            ipr.setRevise_serial_number(String.valueOf(idWorker.nextId()));
        }
        //重新提交审核状态
        //2,待审核
        ipr.setRevise_status(DictConst.REVISE_STATUS_SPZ);
        //再次提交业务中，由于长安批单异步处理才需要下面批单核保业务
        if(StringUtils.isNotEmpty(ovo.getProduct_code())&&ovo.getProduct_code().contains(ConstProp.GZZRX_CA)){
            Map<String, String> map = recordRestToRB(vo, "1");
            if(map != null){
                if("300".equals(map.get("ret"))){
                    return false;
                }
            }else{
                return false;
            }
//            ipr.setRevise_serial_num_ins(map.get("batchNumber"));
//            ipr.setTotal_premium(BigDecimal.valueOf(Double.parseDouble(map.get("premium"))));
//            ipr.setRemark("");
//            ipr.setRevise_status(DictConst.REVISE_STATUS_TG);
            updateRecordStatus(String.valueOf(ipr.getIns_preservation_record_id()),map);
            return true;
        }else if(StringUtils.isNotEmpty(ovo.getProduct_code())&&ovo.getProduct_code().contains(ConstProp.GZZRX_TB)){
            Map<String, String> map = recordRestToRB(vo, "1");
            if(map != null){
                if("300".equals(map.get("ret"))){
                    throw new RuntimeException(map.get("msg"));
//                    return false;
                }
            }else{
                return false;
            }
//            ipr.setRevise_serial_num_ins(map.get("batchNumber"));
//            ipr.setRevise_path(map.get("eurl"));
//            ipr.setTotal_premium(BigDecimal.valueOf(Double.parseDouble(map.get("premium"))));
//            ipr.setRevise_status(DictConst.REVISE_STATUS_TG);
            updateRecordStatus(String.valueOf(ipr.getIns_preservation_record_id()),map);
            return true;
        }else if(StringUtils.isNotEmpty(ovo.getProduct_code())&&ovo.getProduct_code().contains(ConstProp.GZZRX_QH)){
            Map<String, String> map = recordRestToRB(vo, "1");
            if(map != null){
                if("300".equals(map.get("ret"))){
                    throw new RuntimeException(map.get("msg"));
                }
            }else{
                return false;
            }
            updateRecordStatus(String.valueOf(ipr.getIns_preservation_record_id()),map);
            return true;
            //长安返回的暂批改单号
//            ipr.setRevise_serial_num_ins(map.get("batchNumber"));
//            ipr.setRevise_status(DictConst.REVISE_STATUS_TG);
//            if(StringUtils.isNotEmpty(map.get("premium"))){
//                ipr.setTotal_premium(BigDecimal.valueOf(Double.parseDouble(map.get("premium"))));
//            }
//            if(map.get("eurl")!=null){
//                ipr.setRevise_path(map.get("eurl"));
//            }
        }
        try {
            updateById(ipr);
        }catch (Exception e){//回滚
            log.error("保全申请单再次提交审核过程事务发现异常，回滚数据",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        if(!DictConst.REVISE_STATUS_SPZ.equals(ipr.getRevise_status())){
            return flag;
        }
        //邮件发送
//        List<InsPreservationDetailVo> ipdVoList = new ArrayList<InsPreservationDetailVo>();
//        for(InsPreservationDetail ipd : ipdList){
//            InsPreservationDetailVo vo = new InsPreservationDetailVo();
//            try {
//                MyConverUtil.map2PO(MyConverUtil.PO2Map(ipd), vo);
//                vo.setOid(String.valueOf(ipd.getIns_preservation_detail_id()));
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            ipdVoList.add(vo);
//        }

//        String inception_date = DateUtil.convertDateToString(ipr.getInception_date(),DateUtil.FORMAT2);
        myAsyncExecutor.execute(()->{
            try {
                //邮件发送
                sendPreservationEmail(ovo.getProduct_code(),ConstProp.BLANK_CHAR,htmlContentByPreservationRecord(ovo,vo.getInsPreservationDetailVoList(),vo.getInception_date()));
            } catch(Exception e) {

            }
        });
        return flag;
    }

    @Override
    public boolean addAgainRecord(Long oid,List<InsPreservationDetailVo> ipdVoList){
        try {
            insPreservationDetailAPIService.saveOrUpdateInsPreservationDetail(ConstProp.DIGIT_ONE,oid,ipdVoList);
            againRecord(oid);
            return true;
        }catch (Exception e){//回滚
            log.error("保全申请单增员再次审核更新过程事务发现异常，回滚数据",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    /**
     * <b> 获取电子批单地址 </b>
     * @author ZXF
     * @create 2020/01/13 0013 16:14
     * @version
     * @注意事项 </b>
     */
    @Override
    public String printDZPD(Long record_id,String batchNumber) {
        String path = ConstProp.BLANK_CHAR;
        InsPreservationRecordVo recordVo = insPreservationRecordAPIDao.findInsPreservationRecordVoById(record_id);
        if(recordVo == null){
            return path;
        }
        if(StringUtils.isNotEmpty(recordVo.getRevise_path())){
            return recordVo.getRevise_path();
        }
        if(StringUtils.isEmpty(recordVo.getRevise_serial_num_ins())){
            recordVo.setRevise_serial_num_ins(batchNumber);
        }
        OrderFormVo orderVo = policyService.accordingToOrderIDToGetPolicyDto(Long.parseLong(recordVo.getIns_insurance_slip_id()));
        if(orderVo == null){
            return path;
        }
        try {
            if(orderVo.getProduct_code().contains(ConstProp.GZZRX_PAC)){
                String result = gZZRX_PACRequestService.requestPAC(Long.parseLong(recordVo.getIns_insurance_slip_id()), TransTypeEnum.DZPD.getValue(),recordVo);
                if(StringUtils.isNotEmpty(result)&&result.contains("200#")){
                    path = result.replace("200#",ConstProp.BLANK_CHAR);
                }
            }/*else if(orderVo.getProduct_code().contains(ConstProp.TYX_PAC)){
                String result = pACRequestService.requestPAC(Long.parseLong(recordVo.getIns_insurance_slip_id()),RB_TT.DZPD.getValue(),recordVo);
                if(StringUtils.isNotEmpty(result)&&result.contains("200#")){
                    path = result.replace("200#",ConstProp.BLANK_CHAR);
                }
            }*/
            if(StringUtils.isNotEmpty(path)){
                saveRevisePath(record_id,path);
            }
        } catch (Exception e) {
            log.error("电子批单获取异常，ERROR:",e.getMessage());
        }
        return path;
    }

    /**
     * <b> 保存电子批单 </b>
     * @author ZXF
     * @create 2020/01/13 0013 16:48
     * @version
     * @注意事项 </b>
     */
    @Override
    public void saveRevisePath(Long record_id, String path) {
        insPreservationRecordAPIDao.saveRevisePath(record_id,path);
    }

    @Override
    public boolean deleteInsPreservationRecord(Long oid){
        boolean flag = true;
        InsPreservationRecord ipr = selectById(oid);
        if(ipr != null){
            //逻辑删除,TODO 状态0为废弃
            ipr.setRevise_status(DictConst.REVISE_STATUS_FQ);
            try {
                updateById(ipr);
            }catch (Exception e){//回滚
                log.error("删除保全申请单过程事务发现异常，回滚数据",e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }else{
            flag = false;
        }
        return flag;
    }

    @Override
    public boolean revokeInsPreservationRecord(Long oid){
        boolean flag = true;
        InsPreservationRecordVo iprVo = findInsPreservationRecordVoById(oid);
        if(iprVo != null){
            try {
                String result = gZZRX_TBRequestService.request_tb_gzzrx(Long.parseLong(iprVo.getIns_insurance_slip_id()), TransTypeEnum.PDZFCX.getValue(),iprVo);
                if(StringUtils.isNotEmpty(result)&& result.startsWith("200")){
                    InsPreservationRecord ipr = selectById(oid);
                    ipr.setRevise_status(DictConst.REVISE_STATUS_BTG);
                    updateById(ipr);
                }else{
                    flag = false;
                }
            }catch (Exception e){//回滚
                log.error("撤销保全申请单过程事务发现异常，回滚数据",e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }else{
            flag = false;
        }
        return flag;
    }



    /**
     * 保存保全用户 （增员或者减员接口）
     * 对接
     * @param map
     */
    @Override
    public List<InsPreservationDetailVo> saveOrderPreservation(Map<String, Object> map){
//        姓名，身份证号，性别，出生年月日，职业类别，增员/减员  订单id
        try {
            String webType = "";
            if(map.get("webType") != null){
                webType = (String)map.get("webType");
            }
            String oid = "";
            if(map.get("orderNo") != null){
                oid = (String)map.get("orderNo");
            }
            String inception_date = "";
            if(map.get("inceptionDate") != null){
                inception_date = (String)map.get("inceptionDate");
            }
            String reviseType = "";
            if(map.get("reviseType") != null){
                reviseType = (String)map.get("reviseType");
            }
            String externalReference = "";
            if(map.get("externalReference") != null){
                externalReference = (String)map.get("externalReference");
            }
            String productName = "";
            if(map.get("productName") != null){
                productName = (String)map.get("productName");
            }
            String applicantName = "";
            if(map.get("applicantName") != null){
                applicantName = (String)map.get("applicantName");
            }
            String responsibilityVo1 = "";
            if(map.get("responsibilityVo1") != null){
                responsibilityVo1 = (String)map.get("responsibilityVo1");
            }
            String responsibilityVo2 = "";
            if(map.get("responsibilityVo2") != null){
                responsibilityVo2 = (String)map.get("responsibilityVo2");
            }
            String responsibilityVo3 = "";
            if(map.get("responsibilityVo3") != null){
                responsibilityVo3 = (String)map.get("responsibilityVo3");
            }
            List<InsPreservationDetailVo> list  = null;
            if(map.get("vo") != null){
                list = (List<InsPreservationDetailVo>)map.get("vo");
            }
            String htmlContent="<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"UTF-8\"><title>保全申请书</title><style type=\"text/css\">.wrap{width:500px;margin:30px auto}.wrap h1{text-align:center}.shenqing-con p strong,.shenqing-con p span{display:block;font-size:14px;line-height:24px}.shenqing-con p strong{float:left;margin-right:8px}.shenqing-con div{float:left}.shenqing-con p.mg-r{width:200px;margin-left:78px}table{width:680px}table th,table td{padding:5px}</style></head><body><div class=\"wrap\"><h1>保全申请书</h1><div class=\"shenqing-con\"><p><strong>保险订单号：</strong><span>#ORDERNUM#</span></br><strong>生效日期：</strong><span>#INCEPTIONDATE#</span></br><strong>保险公司：</strong><span>泰康在线财产保险股份有限公司</span></br><strong>保单号：</strong><span>#EXTERNALREFERENCE#</span></br><strong>投保人：</strong><span>#APPLICANTNAME#</span></br><strong>保险产品：</strong><span>[产品名称：#PRODUCTNAME#]</span></br><strong>保障内容：</strong></br><span class=\"mg-r\">#RESPONSIBILITYVO1#</span></br><span class=\"mg-r\">#RESPONSIBILITYVO2#</span></br><span class=\"mg-r\">#RESPONSIBILITYVO3#</span></br></p><h2>申请该保单项下[#TYPE#]以下被保险人：</h2><table border=\"1\"cellspacing=\"0\"cellpadding=\"0\"><thead><tr><th>序号</th><th>姓名</th><th>身份证号</th><th>性别</th><th>出生日期</th><th>职业</th></tr></thead><tbody>#TRCONTENT#</tbody></table></div></div></body></html>";
            htmlContent=htmlContent.replace("#ORDERNUM#",oid);
            htmlContent=htmlContent.replace("#EXTERNALREFERENCE#",""+externalReference);
            htmlContent=htmlContent.replace("#INCEPTIONDATE#",inception_date);
            htmlContent=htmlContent.replace("#PRODUCTNAME#",productName);
            htmlContent=htmlContent.replace("#APPLICANTNAME#",applicantName);
            htmlContent=htmlContent.replace("#RESPONSIBILITYVO1#",responsibilityVo1);
            htmlContent=htmlContent.replace("#RESPONSIBILITYVO2#",responsibilityVo2);
            htmlContent=htmlContent.replace("#RESPONSIBILITYVO3#",responsibilityVo3);
            List<InsPreservationDetailVo> rightList=new ArrayList<InsPreservationDetailVo>();
            removeErrorList(list,oid,webType,rightList);//订单id
            if(rightList==null||rightList.size()<=0){
                return null;
            }
            InsPreservationRecordVo iprVo = new InsPreservationRecordVo();
            iprVo.setIns_insurance_slip_id(oid);
            iprVo.setInception_date(inception_date);
            iprVo.setRevise_type(reviseType);
            StringBuffer trContent= new StringBuffer();
            int count = 0;
            for(InsPreservationDetailVo detailVo : rightList){
                if(count==0){
                    String tty = ConstProp.BLANK_CHAR;
                    if(DictConst.REVISE_TYPE_Z.equals(detailVo.getRevise_type())){
                        tty = "增员";
                    }else if(DictConst.REVISE_TYPE_J.equals(detailVo.getRevise_type())){
                        tty = "减员";
                    }else if(DictConst.REVISE_TYPE_T.equals(detailVo.getRevise_type())){
                        tty = "替换";
                    }
                    htmlContent=htmlContent.replace("#TYPE#",tty);
                }
                trContent.append("<tr><td>"+(count+1)+"</td><td>"+detailVo.getName()+"</td><td>"+detailVo.getId_card()+"</td><td>");
                if(ConstProp.DIGIT_TWO.equals(IdNumberValidator.getSexFromCard(detailVo.getId_card()))){
                    trContent.append("女");
                }else{
                    trContent.append("男");
                }
                //历史获取出生日期：DateUtil.convertDateToString(IdNumberValidator.idNumber2BirthDate(detailVo.getId_card()),DateUtil.FORMAT2)
                trContent.append("</td><td>"+ detailVo.getBirthday());
                String career = ConstProp.DIGIT_ONE.equals(detailVo.getCareer()) ? "内勤人员"
                        : ConstProp.DIGIT_TWO.equals(detailVo.getCareer()) ? "保安人员"
                        : ConstProp.DIGIT_THREE.equals(detailVo.getCareer()) ? "武装押运人员"
                        : ConstProp.DIGIT_FOUR.equals(detailVo.getCareer()) ? "保洁人员"
                        : "";
                trContent.append("</td><td>"+career+"</td></tr>");
                count++;
            }
            htmlContent=htmlContent.replace("#TRCONTENT#",trContent.toString());
            OrderFormVo vo = policyService.accordingToOrderIDToGetPolicyDto(Long.parseLong(oid));
            //泰康保全邮件
            sendPreservationEmail(vo.getProduct_code(),"0",htmlContent);
            if(createInsPreservationRecord(1,iprVo,rightList)){
                return rightList;
            }
        } catch (Exception e) {
            log.error("保全人员邮件组装过程事务发现异常，回滚数据",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }
        return null;
    }

    /**
     * <b> 保全人员邮件内容数据组装 </b>
     * @author ZXF
     * @create 2017/12/21 0021 16:58
     * @version
     * @注意事项 </b>
     */
    private String htmlContentByPreservationRecord(OrderFormVo orderVo,List<InsPreservationDetailVo> ipdVoList, String inception_date){
//        姓名，身份证号，性别，出生年月日，职业类别，增员/减员  订单id
        StringBuffer htmlContent= new StringBuffer();
        try {
            if(ipdVoList==null||ipdVoList.size()<1){
                return null;
            }
            if(orderVo == null){
                log.info("保全人员邮件内容数据组装-订单信息不存在----------------");
                return htmlContent.toString();
            }
            String tty = ConstProp.BLANK_CHAR;
            String revise_type = ConstProp.BLANK_CHAR;
            int sign = 0;
            StringBuffer oldRole = new StringBuffer();
            StringBuffer newRole = new StringBuffer();
            //oldRole 被替换人员（替换类型才存在这个值），newRole 当前操作人员
            oldRole.append("<table border=\"1\"cellspacing=\"0\"cellpadding=\"0\"><thead><tr><th>序号</th><th>姓名</th><th>证件号码</th><th>性别</th><th>出生日期</th><th>职业</th></tr></thead><tbody>");
            newRole.append("<table border=\"1\"cellspacing=\"0\"cellpadding=\"0\"><thead><tr><th>序号</th><th>姓名</th><th>证件号码</th><th>性别</th><th>出生日期</th><th>职业</th></tr></thead><tbody>");
            for(InsPreservationDetailVo detailVo : ipdVoList) {
                if(sign == 0){
                    revise_type = detailVo.getRevise_type();
                    if (ConstProp.DIGIT_ONE.equals(detailVo.getRevise_type())) {
                        tty = "增员";
                    } else if (ConstProp.DIGIT_TWO.equals(detailVo.getRevise_type())) {
                        tty = "减员";
                    } else if (ConstProp.DIGIT_THREE.equals(detailVo.getRevise_type())) {
                        tty = "替换";
                    }
                }
                if(ConstProp.DIGIT_THREE.equals(detailVo.getRevise_type())){
                    InsPreservationResultSetVo resultSet = insPreservationResultSetAPIService.getInsPreservationResultSetVoByOidAndSign(detailVo.getBusiness_id(), detailVo.getBusiness_type());
                    InsPreservationDetailVo dvo = insPreservationDetailAPIService.detailConvertToResultSet(resultSet);
                    getTableRole(oldRole,dvo,sign);
                }
                getTableRole(newRole,detailVo,sign);
                sign++;
            }
            oldRole.append("</tbody></table>");
            newRole.append("</tbody></table>");
            String stro = "";
            if(StringUtils.isNotEmpty(inception_date)){
                stro = "<strong>生效日期：</strong><span>"+inception_date+"</span></br>";
            }
            htmlContent.append("<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"UTF-8\"><title>保全申请书</title><style type=\"text/css\">.wrap{width:500px;margin:30px auto}.wrap h1{text-align:center}.shenqing-con p strong,.shenqing-con p span{display:block;font-size:14px;line-height:24px}.shenqing-con p strong{float:left;margin-right:8px}.shenqing-con div{float:left}.shenqing-con p.mg-r{width:200px;margin-left:78px}table{width:680px}table th,table td{padding:5px}</style></head><body><div class=\"wrap\"><h1>保全申请书</h1><div class=\"shenqing-con\"><p>");
            htmlContent.append("<strong>保险订单号：</strong><span>"+orderVo.getTrade_serial_number()+"</span></br>");
            htmlContent.append("<strong>保险公司：</strong><span>"+orderVo.getInsurance_name()+"</span></br><strong>保单号：</strong><span>"+orderVo.getExternal_reference()+"</span></br>"+stro+"<strong>投保人：</strong><span>"+orderVo.getApplicant_name()+"</span></br><strong>保险产品：</strong><span>[产品名称："+orderVo.getProduct_name()+"]</span></br><strong>保障内容：</strong></br>");
            for(ResponsibilityVo rvo : orderVo.getResponsibilityVoList()){
                htmlContent.append("<span class=\"mg-r\">"+rvo.getShow_name()+rvo.getFcy()+"</span></br>");
            }
            htmlContent.append("</p><h2>申请该保单项下["+tty+"]以下被保险人：</h2>");
            if(ConstProp.DIGIT_THREE.equals(revise_type)){
                htmlContent.append("<span class=\"mg-r\">（原被保险人）</span></br>");
                htmlContent.append(oldRole);
                htmlContent.append("<span class=\"mg-r\">（现被保险人）</span></br>");
            }
            htmlContent.append(newRole);
            htmlContent.append("</div></div></body></html>");
        } catch (Exception e) {
            log.error("保全人员邮件内容数据组装过程事务发现异常，回滚数据",e);
            e.printStackTrace();
        }
        return htmlContent.toString();
    }

    private void getTableRole(StringBuffer role, InsPreservationDetailVo detailVo, int sign){
        role.append("<tr><td>"+(sign+1)+"</td><td>"+detailVo.getName()+"</td><td>"+detailVo.getId_card()+"</td><td>");
        if(ConstProp.DIGIT_TWO.equals(detailVo.getSex())){
            role.append("女");
        }else{
            role.append("男");
        }
        //历史获取出生日期：DateUtil.convertDateToString(IdNumberValidator.idNumber2BirthDate(detailVo.getId_card()),DateUtil.FORMAT2)
        role.append("</td><td>"+ detailVo.getBirthday());
        String career = ConstProp.DIGIT_ONE.equals(detailVo.getCareer()) ? "内勤人员"
                : ConstProp.DIGIT_TWO.equals(detailVo.getCareer()) ? "保安人员"
                : ConstProp.DIGIT_THREE.equals(detailVo.getCareer()) ? "武装押运人员"
                : ConstProp.DIGIT_FOUR.equals(detailVo.getCareer()) ? "保洁人员"
                : "";
        role.append("</td><td>"+career+"</td></tr>");
    }

    /**
     * 发送保全邮件
     *
     * @param product_code
     * @param type  默认泰康0
     */
    @Override
    public void sendPreservationEmail(String product_code,String type,String htmlContent ) {
        log.info("保全邮件发送（内容htmlContent）:"+htmlContent);
        //exmail格式：123@qq.com;333@qq.com:GZZRX-RB;413@qq.com:GZZRX-ZH
        String[] arrs = comDeployConfigService.getValueByKey("RECORD_EMAIL").split(ConstProp.SEMICOLON);
        EmailModel emailModel = new EmailModel("保单保全信息", htmlContent);
        List<String> emailList = new ArrayList<String>();
        String em;
        for(int i=0;i<arrs.length;i++){
            if(StringUtils.isBlank(arrs[i])){
                continue;
            }
            em = ConstProp.BLANK_CHAR;
            //邮箱加产品代码 3804@qq.com:GZZRX-ZH
            if(arrs[i].contains(ConstProp.COLON)){
                String[] sigs = arrs[i].split(ConstProp.COLON);
                if(StringUtils.isNotEmpty(product_code) && product_code.contains(sigs[1])){
                    em = sigs[0].trim();
                }
            }else{
                em = arrs[i].trim();
            }
            if(StringUtils.isNotEmpty(em)){
                emailList.add(em); // 发送地址
                log.info("保全邮件发送（收件人Email-"+(i+1)+"）:"+em);
            }
        }
        if(emailList.size()>0){
            emailModel.setTo(emailList);
            SendEmailAndMsgUtil.sendEmail(emailModel);
        }
    }

    private void removeErrorList(List<InsPreservationDetailVo> list,String  oid,String webType,List<InsPreservationDetailVo>  rightList) {
        //去除 购买的其他产品
        for(InsPreservationDetailVo vo:list){
//			boolean flag=sysUserAPIService.getUserPermission(oid,vo.getIdCard(), DateUtil.getDate("yyyy-MM-dd HH:mm:ss"),webType,vo.getType());
            boolean flag= false;
            if(flag){
                rightList.add(vo);
            }
        }
    }

    /**
     * 根据订单id去查询对应产品的保全生效限制日期
     * @param policyId
     * @return 2017-05-05,2017-05-08(区间)
     */
    @Override
    public String getEffectiveByPolicyId(Long policyId){
        String result = ConstProp.BLANK_CHAR;
        OrderFormVo order = policyService.accordingToOrderIDToGetPolicyDto(policyId);
        ProductVo productVo = productService.getProduct(Long.parseLong(order.getProduct_oid()));
        try {
            //1提交起次日生效 2提交前几日生效 3提交后几日内生效 4提交前及提交后几日内生效
            String sta_time,end_time;
            if(order.getProduct_code().contains(ConstProp.GZZRX)||order.getProduct_code().contains(ConstProp.TYX_RB)){
                return DateUtil.getTomorrow()+","+DateUtil.getTomorrow();
            }
            if(StringUtils.isNotBlank(productVo.getEffective_date())){
                String nowDate_str = DateUtil.getCurrentDateTime(DateUtil.FORMAT2);
                if(ConstProp.DIGIT_ONE.equals(productVo.getEffective_date())){
                    sta_time = DateUtil.getTomorrow();
                    end_time = DateUtil.getTomorrow();
                }else if(ConstProp.DIGIT_TWO.equals(productVo.getEffective_date())){
                    sta_time = DateUtil.dateAdd(0,nowDate_str,-Integer.parseInt(productVo.getEffective_date_before_n()));
                    end_time = DateUtil.dateAdd(0,nowDate_str,-1);

                }else if(ConstProp.DIGIT_THREE.equals(productVo.getEffective_date())){
                    sta_time = DateUtil.dateAdd(0,nowDate_str,1);
                    end_time = DateUtil.dateAdd(0,nowDate_str,Integer.parseInt(productVo.getEffective_date_after_n()));
                }else{
                    sta_time = DateUtil.dateAdd(0,nowDate_str,-Integer.parseInt(productVo.getEffective_date_before_n()));
                    end_time = DateUtil.dateAdd(0,nowDate_str,Integer.parseInt(productVo.getEffective_date_after_n()));
                }
                result = sta_time+","+end_time;
            }else{
                result = "1900-01-01,2099-12-31";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 查询所有4已审核并且当前时间大于生效时间的保全申请单列表并变更状态为5已生效
     */
    @Override
    public void setInsPreservationRecordStatus(){
//        List<InsPreservationRecord> iprList = insPreservationRecordAPIDao.findInsPreservationRecordByStatusAndTime();
//        for(InsPreservationRecord ipr : iprList){
//            ipr.setRevise_status(DictConst.REVISE_STATUS_SX);
//            updateById(ipr);
//        }
        List<String> idList = insPreservationRecordAPIDao.findInsPreservationRecordIdsByStatusAndTime();

        if(idList.size()>0){
            insPreservationRecordAPIDao.updateStatusById(DictConst.REVISE_STATUS_SX,idList);
        }
    }

    /**
     * 根据订单id及保全申请单状态查询对应保全申请单id列表
     * @param policyId
     * @param status
     * @return
     */
    @Override
    public List<String> selectRecordIdByPolicyIdAndStatus(Long policyId, String status, String resType){
        return insPreservationRecordAPIDao.selectRecordIdByPolicyIdAndStatus(policyId,status, resType);
    }

    /**
     * 筛选为外部平台并且未推送过的已审核或已生效保全申请单id
     * @return
     */
    @Override
    public List<String> selectRecordIdByWebType(String type){
        return insPreservationRecordAPIDao.selectRecordIdByWebType(type);
    }

    /**
     * 推送给外部平台的保全申请单做标记
     * @param recordId
     * @return
     */
    @Override
    public boolean updateRecordByIsPush(String recordId){
        boolean flag = true;
        try {
            insPreservationRecordAPIDao.updateIsPushById(Long.parseLong(recordId),ConstProp.INT_NUMBER_ONE);
        }catch (Exception e){//回滚
            flag = false;
            log.error("标记保全申请单过程事务发现异常，回滚数据",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return flag;
    }

    /**
     * <b> 
     *     组装批单报文请求接口批改，返回结果部分存session
     * </b>
     * @param iprVo 页面提交的保全申请单信息
     * @param sign 提交审核（1）或者暂存（0）
     * @author ZXF
     * @create 2018/06/06 0006 11:17
     * @version
     * @注意事项 </b>
     */
    @Override
    public Map<String,String> recordRestToRB(InsPreservationRecordVo iprVo, String sign){
        Map<String,String> map = null;
        //要请求接口
        if(!ConstProp.DIGIT_ONE.equals(sign)){
            return map;
        }
        OrderFormVo vo = policyService.accordingToOrderIDToGetPolicyDto(Long.parseLong(iprVo.getIns_insurance_slip_id()));
        //如果缓存中数据不全就清理缓存重新加载
        if(StringUtils.isEmpty(vo.getPremium())){
            JedisUtils.batchDel(ConstProp.REDIS_HEAD_POLICY_ID+vo.getOid());
            vo = policyService.accordingToOrderIDToGetPolicyDto(Long.parseLong(iprVo.getIns_insurance_slip_id()));
        }
        if(StringUtils.isEmpty(vo.getProduct_code())){
            return map;
        }
        if(!vo.getProduct_code().contains(ConstProp.GZZRX_RB)
                &&!vo.getProduct_code().contains(ConstProp.GZZRX_ZH)
                &&!vo.getProduct_code().contains(ConstProp.GZZRX_PAC)
                &&!vo.getProduct_code().contains(ConstProp.GZZRX_CA)
                &&!vo.getProduct_code().contains(ConstProp.GZZRX_QH)
                &&!vo.getProduct_code().contains(ConstProp.GZZRX_TB)
                &&!vo.getProduct_code().contains(ConstProp.TYX_CA)
                &&!vo.getProduct_code().contains(ConstProp.TYX_RB)
                &&!vo.getProduct_code().contains(ConstProp.TYX_HT)
                &&!vo.getProduct_code().contains(ConstProp.TYX_PAC)){
            return map;
        }
        try {
            iprVo.setStart_time(DateUtil.getCurrentDateTime());
            List<InsPreservationDetailVo> dList = iprVo.getInsPreservationDetailVoList();
            List<InsPreservationDetailVo> idList = Lists.newArrayList();
            if(ConstProp.DIGIT_ONE.equals(iprVo.getRevise_type())){
                //增员
                for(InsPreservationDetailVo dvo : dList){
                    dvo.setRevise_type(ConstProp.DIGIT_ONE);
                    idList.add(dvo);
                }
            }else if(ConstProp.DIGIT_TWO.equals(iprVo.getRevise_type())){
                //减员
                for(InsPreservationDetailVo dvo : dList){
                    dvo.setRevise_type(ConstProp.DIGIT_TWO);
                    if(StringUtils.isEmpty(dvo.getBusiness_id())){
                        Long setId = insPreservationResultSetAPIService.getIdByIdCardAndOrderId(dvo.getId_card(), Long.parseLong(iprVo.getIns_insurance_slip_id()));
                        dvo.setBusiness_id(setId!=null?String.valueOf(setId):ConstProp.BLANK_CHAR);
                        dvo.setBusiness_type(ConstProp.PRESERVE);
                    }
                    //目前就太保减员的保障期间需要这么处理
                    if(vo.getProduct_code().contains(ConstProp.GZZRX_TB)){
                        //获取被减员人员当前起保日期
                        String business_inception_date = insPreservationResultSetAPIService.getBusinessInceptionDateByBusinessId(dvo.getBusiness_id());
                        if(StringUtils.isEmpty(business_inception_date)){
                            business_inception_date = vo.getInception_date();
                        }
                        dvo.setBusiness_inception_date(business_inception_date);
                    }
                    idList.add(dvo);
                }
            }else if(ConstProp.DIGIT_THREE.equals(iprVo.getRevise_type())){
                //替换
                for(InsPreservationDetailVo dvo : dList){
                    InsPreservationDetailVo ipdVo = new InsPreservationDetailVo();
                    InsPreservationResultSet resultSet = insPreservationResultSetAPIService.selectById(Long.parseLong(dvo.getBusiness_id()));
                    MyConverUtil.map2PO(MyConverUtil.PO2Map(resultSet), ipdVo);
                    ipdVo.setRevise_type(ConstProp.DIGIT_TWO);
                    dvo.setRevise_type(ConstProp.DIGIT_ONE);
                    dvo.setBusiness_vo(ipdVo);
                    //获取被减员人员当前起保日期
//                    String business_inception_date = insPreservationResultSetAPIService.getBusinessInceptionDateByBusinessId(dvo.getBusiness_id());
//                    if(StringUtils.isEmpty(business_inception_date)){
//                        business_inception_date = vo.getInception_date();
//                    }
//                    dvo.setBusiness_inception_date(business_inception_date);
                    idList.add(dvo);
                }
            }
            iprVo.setInsPreservationDetailVoList(idList);
            String result = ConstProp.BLANK_CHAR;
            if(vo.getProduct_code().contains(ConstProp.GZZRX_RB)){
                result = gZZRX_RBRequestService.request_rb_gzzrx(Long.parseLong(iprVo.getIns_insurance_slip_id()), TransTypeEnum.PD.getValue(),iprVo);
            }else if(vo.getProduct_code().contains(ConstProp.TYX_RB)){
                result = rBRequestService.request_rb_tyx(Long.parseLong(iprVo.getIns_insurance_slip_id()), TransTypeEnum.PD.getValue(),iprVo);
            }else if(vo.getProduct_code().contains(ConstProp.GZZRX_TB)){//太平洋保险 雇主责任险 批单
                if(StringUtils.isEmpty(iprVo.getRevise_serial_number())){
                    IdWorker idWorker = new IdWorker(ConstProp.INT_NUMBER_WORKERID, ConstProp.INT_NUMBER_ZERO);
                    iprVo.setRevise_serial_number(String.valueOf(idWorker.nextId()));
                }

                String premium = "0.00";
                if(!ConstProp.DIGIT_THREE.equals(iprVo.getRevise_type())){
                    int syDay = DateUtil.getDistDates(DateUtil.convertStringToDate(iprVo.getInception_date()),DateUtil.convertStringToDate(vo.getPlanned_end_date()))+1;
                    BigDecimal tolP = (BigDecimal.valueOf(syDay).divide(BigDecimal.valueOf(Double.parseDouble("365")),9,BigDecimal.ROUND_DOWN)).multiply(BigDecimal.valueOf(Double.parseDouble(vo.getPremium()))).setScale(2, BigDecimal.ROUND_DOWN).multiply(BigDecimal.valueOf(Double.parseDouble(String.valueOf(iprVo.getInsPreservationDetailVoList().size())))).setScale(2, BigDecimal.ROUND_HALF_UP);
                    premium = ConstProp.DIGIT_TWO.equals(iprVo.getRevise_type())? "-"+tolP : String.valueOf(tolP);
                }
                iprVo.setTotal_premium(premium);
                //计算保费/保额变化值
                changeAP(iprVo,vo);
                result = gZZRX_TBRequestService.request_tb_gzzrx(Long.parseLong(iprVo.getIns_insurance_slip_id()), TransTypeEnum.PD.getValue(),iprVo);
            }else if(vo.getProduct_code().contains(ConstProp.TYX_PAC)){
                if(StringUtils.isEmpty(iprVo.getRevise_serial_number())){
                    IdWorker idWorker = new IdWorker(ConstProp.INT_NUMBER_WORKERID, ConstProp.INT_NUMBER_ZERO);
                    iprVo.setRevise_serial_number(String.valueOf(idWorker.nextId()));
                }
                result = pACRequestService.requestPAC(Long.parseLong(iprVo.getIns_insurance_slip_id()), TransTypeEnum.PD.getValue(),iprVo);
                //如果增减员需要再调批单确认接口
                if((ConstProp.DIGIT_ONE.equals(iprVo.getRevise_type())||ConstProp.DIGIT_TWO.equals(iprVo.getRevise_type()))
                        &&result.startsWith("200#")){
                    result = result + ConstProp.POUND_SIGN + iprVo.getRevise_serial_number();
                    result = pACRequestService.pdqr(TransTypeEnum.PDQR.getValue(),result);
                }
            }else if(vo.getProduct_code().contains(ConstProp.TYX_HT)){
                iprVo.setRelease_time(DateUtil.getCurrentDateTime());
                result = tYX_HTRequestService.request_ht_tyx(Long.parseLong(iprVo.getIns_insurance_slip_id()), TransTypeEnum.PD.getValue(),iprVo);
                //如果增减员需要再调批单确认接口
                if(result.startsWith("200#")){
                    //订单号
                    iprVo.setRevise_serial_number(result.split(ConstProp.POUND_SIGN)[2]);
                    iprVo.setTotal_premium(result.split(ConstProp.POUND_SIGN)[3]);
                    /*result = tYX_HTRequestService.request_ht_tyx(Long.parseLong(iprVo.getIns_insurance_slip_id()), TransTypeEnum.PDQR.getValue(),iprVo);
                    if(result.startsWith("200#") && ConstProp.DIGIT_ONE.equals(iprVo.getRevise_type()) && (new BigDecimal(iprVo.getTotal_premium())).compareTo(BigDecimal.ZERO)>0){
                        result = result + ConstProp.POUND_SIGN + iprVo.getTotal_premium();
                        String zfResult = tYX_HTRequestService.request_ht_tyx(Long.parseLong(vo.getOid()), TransTypeEnum.PDZF.getValue(),iprVo);
                        String[] strs = zfResult.split(ConstProp.POUND_SIGN);
                        if(ConstProp.CODE_SUCCESS.equals(strs[0])){
                            result = result + ConstProp.POUND_SIGN + strs[1];
                        }
                    }*/
                }
            }else if(vo.getProduct_code().contains(ConstProp.GZZRX_PAC)){
                if(StringUtils.isEmpty(iprVo.getRevise_serial_number())){
                    IdWorker idWorker = new IdWorker(ConstProp.INT_NUMBER_WORKERID, ConstProp.INT_NUMBER_ZERO);
                    iprVo.setRevise_serial_number(String.valueOf(idWorker.nextId()));
                }
                result = gZZRX_PACRequestService.requestPAC(Long.parseLong(iprVo.getIns_insurance_slip_id()), TransTypeEnum.PD.getValue(),iprVo);
            }else if(vo.getProduct_code().contains(ConstProp.GZZRX_CA)){
                if(StringUtils.isEmpty(iprVo.getRevise_serial_number())||iprVo.getRevise_serial_number().startsWith("315162")){
                    IdWorker idWorker = new IdWorker(ConstProp.INT_NUMBER_WORKERID, ConstProp.INT_NUMBER_ZERO);
                    iprVo.setRevise_serial_number(String.valueOf(idWorker.nextId()));
                }
                iprVo.setExternal_reference(vo.getExternal_reference());
                //统计批单次数（长安批单接口需要）
                iprVo.setSerialNo(insPreservationRecordAPIDao.countRecordByEx(iprVo.getExternal_reference()));
                String premium = "0.00";
                if(!ConstProp.DIGIT_THREE.equals(iprVo.getRevise_type())){
                    int syDay = DateUtil.getDistDates(DateUtil.convertStringToDate(iprVo.getInception_date()),DateUtil.convertStringToDate(vo.getPlanned_end_date()))+1;
                    BigDecimal tolP = (BigDecimal.valueOf(syDay).divide(BigDecimal.valueOf(Double.parseDouble("365")),9,BigDecimal.ROUND_DOWN)).multiply(BigDecimal.valueOf(Double.parseDouble(vo.getPremium()))).setScale(2, BigDecimal.ROUND_DOWN).multiply(BigDecimal.valueOf(Double.parseDouble(String.valueOf(iprVo.getInsPreservationDetailVoList().size())))).setScale(2, BigDecimal.ROUND_HALF_UP);
                    //每人保费
//                    BigDecimal perPremium = (BigDecimal.valueOf(Double.parseDouble(vo.getPremium())).divide(BigDecimal.valueOf(Double.parseDouble("365")),9,BigDecimal.ROUND_DOWN)).multiply(BigDecimal.valueOf(Double.parseDouble(String.valueOf(syDay)))).setScale(2, BigDecimal.ROUND_HALF_UP);
                    //保全保费
//                    BigDecimal tolP = perPremium.multiply(BigDecimal.valueOf(Double.parseDouble(String.valueOf(iprVo.getInsPreservationDetailVoList().size()))));
                    premium = ConstProp.DIGIT_TWO.equals(iprVo.getRevise_type())? "-"+tolP : String.valueOf(tolP);
                }
                iprVo.setTotal_premium(premium);
                //TODO 需要确定批单保费长安是否提供？
                result = gZZRX_CARequestService.request_ca_gzzrx(Long.parseLong(iprVo.getIns_insurance_slip_id()), TransTypeEnum.PD.getValue(),iprVo);
                if(result.contains("200#")){
//                    result = result.replace("200#","200#"+vo.getExternal_reference()+"#")+"#"+premium;
//                    System.out.println("重新计算批单返回值："+result);
                    String[] arr = result.split("#");
//                    iprVo.setRevise_serial_num_ins(arr[1]);
                    map = Maps.newHashMap();
                    map.put("ret",arr[0]);
                    //保单号
                    map.put("proposalNo",vo.getExternal_reference());
                    //批单号
                    map.put("batchNumber",arr[1]);
                    map.put("premium",premium);
                    return map;
                }
            }else if(vo.getProduct_code().contains(ConstProp.TYX_CA)){
                if(StringUtils.isEmpty(iprVo.getRevise_serial_number())||iprVo.getRevise_serial_number().startsWith("315162")){
                    IdWorker idWorker = new IdWorker(ConstProp.INT_NUMBER_WORKERID, ConstProp.INT_NUMBER_ZERO);
                    iprVo.setRevise_serial_number(String.valueOf(idWorker.nextId()));
                }
                iprVo.setExternal_reference(vo.getExternal_reference());
                String premium = "0.00";
                if(!ConstProp.DIGIT_THREE.equals(iprVo.getRevise_type())){
                    int syDay = DateUtil.getDistDates(DateUtil.convertStringToDate(iprVo.getInception_date()),DateUtil.convertStringToDate(vo.getPlanned_end_date()))+1;
                    BigDecimal tolP = (BigDecimal.valueOf(syDay).divide(BigDecimal.valueOf(Double.parseDouble("365")),9,BigDecimal.ROUND_DOWN)).multiply(BigDecimal.valueOf(Double.parseDouble(vo.getPremium()))).multiply(BigDecimal.valueOf(Double.parseDouble(String.valueOf(iprVo.getInsPreservationDetailVoList().size())))).setScale(2, BigDecimal.ROUND_HALF_UP);
                    //每人保费
//                    BigDecimal perPremium = (BigDecimal.valueOf(Double.parseDouble(vo.getPremium())).divide(BigDecimal.valueOf(Double.parseDouble("365")),9,BigDecimal.ROUND_DOWN)).multiply(BigDecimal.valueOf(Double.parseDouble(String.valueOf(syDay)))).setScale(2, BigDecimal.ROUND_HALF_UP);
                    //保全保费
//                    BigDecimal tolP = perPremium.multiply(BigDecimal.valueOf(Double.parseDouble(String.valueOf(iprVo.getInsPreservationDetailVoList().size()))));
                    premium = ConstProp.DIGIT_TWO.equals(iprVo.getRevise_type())? "-"+tolP : String.valueOf(tolP);
                }
                iprVo.setTotal_premium(premium);
                //TODO 需要确定批单保费长安是否提供？
                result = tYX_CARequestService.request_ca_tyx(Long.parseLong(iprVo.getIns_insurance_slip_id()), TransTypeEnum.PD.getValue(),iprVo);
                //不是替换的话，就走下面查询批单结果流程
                if(!ConstProp.DIGIT_THREE.equals(iprVo.getRevise_type())){
                    if(result.contains("200#")) {
                        String[] arr = result.split("#");
                        iprVo.setRevise_serial_number(arr[1]);
                        result = tYX_CARequestService.request_ca_tyx(Long.parseLong(iprVo.getIns_insurance_slip_id()), TransTypeEnum.PDJG.getValue(), iprVo);
                    }
                }
                if(result.contains("200#")){
//                    result = result.replace("200#","200#"+vo.getExternal_reference()+"#")+"#"+premium;
//                    System.out.println("重新计算批单返回值："+result);
                    String[] arr = result.split("#");
//                    iprVo.setRevise_serial_num_ins(arr[1]);
                    map = Maps.newHashMap();
                    map.put("ret",arr[0]);
                    //保单号
                    map.put("proposalNo",vo.getExternal_reference());
                    //批单号
                    map.put("batchNumber",arr[2]);
                    map.put("eurl",arr[4]);//电子批单
                    map.put("premium",premium);
                    return map;
                }
            }else if(vo.getProduct_code().contains(ConstProp.GZZRX_QH)){
                //批改上送保险接口前项进行待审核批单补偿 前海保险程序bug的特殊修复机制
                compensateRecord(Long.parseLong(iprVo.getIns_insurance_slip_id()));

                if(StringUtils.isEmpty(iprVo.getRevise_serial_number())){
                    IdWorker idWorker = new IdWorker(ConstProp.INT_NUMBER_WORKERID, ConstProp.INT_NUMBER_ZERO);
                    iprVo.setRevise_serial_number(String.valueOf(idWorker.nextId()));
                }
                iprVo.setExternal_reference(vo.getExternal_reference());
                String numPer = String.valueOf(iprVo.getInsPreservationDetailVoList().size());
                BigDecimal tolP;
                if(ConstProp.DIGIT_ONE.equals(vo.getInception_type())){
                    //年度
                    int syDay = DateUtil.getDistDates(DateUtil.convertStringToDate(vo.getInception_date()),DateUtil.getTodayStart())+1;
                    int tolDay = DateUtil.getDistDates(DateUtil.convertStringToDate(vo.getInception_date()),DateUtil.convertStringToDate(vo.getPlanned_end_date()))+1;

                    BigDecimal liDay = BigDecimal.valueOf(1).subtract(BigDecimal.valueOf(syDay).divide(BigDecimal.valueOf(tolDay),10, BigDecimal.ROUND_HALF_UP).setScale(6, BigDecimal.ROUND_HALF_UP));
                    tolP = BigDecimal.valueOf(Double.parseDouble(vo.getPremium())).multiply(new BigDecimal(numPer)).multiply(liDay).setScale(2, BigDecimal.ROUND_HALF_UP);
                    System.out.println("=====> syDay:"+syDay+",tolDay:"+tolDay+",liDay:"+liDay+",tolP:"+tolP);
//                    int syDay = DateUtil.getDistDates(DateUtil.convertStringToDate(iprVo.getInception_date()),DateUtil.convertStringToDate(vo.getPlanned_end_date()))+1;
//                    tolP = (BigDecimal.valueOf(syDay).divide(BigDecimal.valueOf(Double.parseDouble("365")),9,BigDecimal.ROUND_DOWN)).multiply(BigDecimal.valueOf(Double.parseDouble(vo.getPremium()))).multiply(BigDecimal.valueOf(Double.parseDouble(String.valueOf(iprVo.getInsPreservationDetailVoList().size())))).setScale(2, BigDecimal.ROUND_HALF_UP);
                }else{
                    //月度
                    tolP = BigDecimal.valueOf(Double.parseDouble(vo.getPremium())).multiply(new BigDecimal(numPer)).setScale(2, BigDecimal.ROUND_HALF_UP);
                }
                String premium = ConstProp.DIGIT_TWO.equals(iprVo.getRevise_type())? "-"+tolP : String.valueOf(tolP);
                iprVo.setTotal_premium(premium);
                result = gZZRX_QHRequestService.request_qh_gzzrx(Long.parseLong(iprVo.getIns_insurance_slip_id()), TransTypeEnum.PD.getValue(),iprVo);
                //如果保费对不上，截取报文中的保费作为标准再次提交
                if(StringUtils.isNotEmpty(result)&&result.contains("计算变化保费为:")){
                    String aomStr = result.split("计算变化保费为:")[1];
                    tolP = new BigDecimal(numPer).multiply(new BigDecimal(aomStr));
                    premium = ConstProp.DIGIT_TWO.equals(iprVo.getRevise_type())? "-"+tolP : String.valueOf(tolP);
                    iprVo.setTotal_premium(premium);
                    result = gZZRX_QHRequestService.request_qh_gzzrx(Long.parseLong(iprVo.getIns_insurance_slip_id()), TransTypeEnum.PD.getValue(),iprVo);
                }
                if(ConstProp.DIGIT_THREE.equals(iprVo.getRevise_type())){
                    iprVo.setTotal_premium("0.00");
                }
                if(StringUtils.isNotEmpty(result)) {
                    String[] arr = result.split("#");
                    map = Maps.newHashMap();
                    if (result.contains("300#")) {
                        //TODO 这里增加超时情况补偿

                        map.put("ret", arr[0]);
                        map.put("msg", arr[1]);
                    }else if(result.contains("200#")){
                        map.put("ret",arr[0]);
                        //保单号
                        map.put("proposalNo",vo.getExternal_reference());
                        //批单号
                        map.put("batchNumber",arr[2]);
                        map.put("eurl",arr[3]);//电子批单
                        map.put("premium",iprVo.getTotal_premium());
                    }
                    return map;
                }

            }else if(vo.getProduct_code().contains(ConstProp.GZZRX_ZH)){
                //与中华对接的线上保全接口业务，暂时注释
                /*if(StringUtils.isEmpty(iprVo.getRevise_serial_number())){
                    IdWorker idWorker = new IdWorker(ConstProp.INT_NUMBER_WORKERID, ConstProp.INT_NUMBER_ZERO);
                    iprVo.setRevise_serial_number(String.valueOf(idWorker.nextId()));
                }
                iprVo.setTotal_premium("0.01");
                result = gZZRX_ZHRequestService.request_zh_gzzrx(Long.parseLong(iprVo.getIns_insurance_slip_id()), RB_TT.PD.getValue(),iprVo);
                if(result.contains("300#保费计算错误，请核实！计算为")){
                    iprVo.setTotal_premium(result.split("：")[1]);
                    result = gZZRX_ZHRequestService.request_zh_gzzrx(Long.parseLong(iprVo.getIns_insurance_slip_id()), RB_TT.PD.getValue(),iprVo);
                }*/
                //TODO 中华模拟线上保全替代后台人工审批（等中华线上批单功能上线就换掉）
                String premium = "0.00";
                if(!ConstProp.DIGIT_THREE.equals(iprVo.getRevise_type())){
                    int syDay = DateUtil.getDistDates(DateUtil.convertStringToDate(iprVo.getInception_date()),DateUtil.convertStringToDate(vo.getPlanned_end_date()))+1;
                    //每人保费
                    BigDecimal perPremium = (BigDecimal.valueOf(Double.parseDouble(vo.getPremium())).divide(BigDecimal.valueOf(Double.parseDouble("365")),9,BigDecimal.ROUND_DOWN)).multiply(BigDecimal.valueOf(Double.parseDouble(String.valueOf(syDay)))).setScale(2, BigDecimal.ROUND_HALF_UP);
                    //保全保费
                    BigDecimal tolP = perPremium.multiply(BigDecimal.valueOf(Double.parseDouble(String.valueOf(iprVo.getInsPreservationDetailVoList().size()))));
                    premium = ConstProp.DIGIT_TWO.equals(iprVo.getRevise_type())? "-"+tolP : String.valueOf(tolP);
                }
                result = "200#"+iprVo.getExternal_reference()+"##"+premium+"#"+iprVo.getInception_date()+"#";
            }
            if(StringUtils.isNotEmpty(result)){
                String[] arr = result.split("#");
                map = Maps.newHashMap();
                if(arr.length == 2){
                    map.put("ret",arr[0]);
                    map.put("msg",arr[1]);
                }else if(arr.length == 4||arr.length == 5){
                    map.put("ret",arr[0]);
                    //保单号
                    map.put("proposalNo",arr[1]);
                    //批单号
                    map.put("batchNumber",arr[2]);
                    map.put("premium",arr[3]);
                }else if(arr.length == 6){
                    map.put("ret",arr[0]);
                    //保单号
                    map.put("proposalNo",arr[1]);
                    //批单号
                    map.put("batchNumber",arr[2]);
                    //保费(如果是替换保费默认0.00)
                    if(!NumberUtils.isDigits(arr[3]) && NumberUtils.isDigits(iprVo.getTotal_premium())){

                        map.put("premium",iprVo.getTotal_premium());

                    }else {
                        map.put("premium", ConstProp.DIGIT_THREE.equals(iprVo.getRevise_type()) ? "0.00" : arr[3]);
                    }
                    //退保生效日期
                    map.put("tbsxsj",arr[4]);
                    //电子批单
                    map.put("eurl",arr[5]);
                }else if(arr.length == 7){
                    map.put("ret",arr[0]);
                    //保单号
                    map.put("proposalNo",arr[1]);
                    //批单号
                    map.put("batchNumber",arr[2]);
                    //批单申请号
                    map.put("batchApplyNumber",arr[4]);
                    //保费(如果是替换保费默认0.00)
                    if(!NumberUtils.isDigits(arr[3]) && NumberUtils.isDigits(iprVo.getTotal_premium())){

                        map.put("premium",iprVo.getTotal_premium());

                    }else {
                        map.put("premium", ConstProp.DIGIT_THREE.equals(iprVo.getRevise_type()) ? "0.00" : arr[3]);
                    }

                    //电子批单
                    map.put("eurl",arr[5]);
                    //支付地址
                    map.put("payurl",arr[6]);
                }
                //增加判断是否存在待审核环节，控制返回内容展示
                if(vo.getProduct_code().contains(ConstProp.TYX_HT)||vo.getProduct_code().contains(ConstProp.GZZRX_TB)){
                    map.put("isPendingApproval","1");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    private void changeAP(InsPreservationRecordVo iprVo,OrderFormVo vo){
        if(ConstProp.DIGIT_THREE.equals(iprVo.getRevise_type())){
            iprVo.setAmount_change("0");
            iprVo.setPremium_change("0");
            iprVo.setTotal_amount("0.00");
        }
        Map<String,String> sumMap = insPreservationRecordAPIDao.sumRecordNumAndPremiumByEx(vo.getExternal_reference());
        //转太保银行编码
        iprVo.setBankMap(insRoleInpolicyService.getTBBankByOrderId(Long.parseLong(vo.getOid())));
        String perNum = sumMap.get("perNum");
        //历史保费
        String ljPremium = sumMap.get("premium");
        String product_code = vo.getProduct_code();
        String eam = "GZZRX-TB-1".equals(product_code) ? "400000"
                : "GZZRX-TB-2".equals(product_code) ? "500000"
                : "GZZRX-TB-3".equals(product_code) ? "600000"
                : "GZZRX-TB-4".equals(product_code) ? "700000"
                : "GZZRX-TB-5".equals(product_code) ? "800000"
                : "0";
        //剩余保费
        BigDecimal sypremium = (BigDecimal.valueOf(Double.parseDouble(vo.getGross_premium()))).add(BigDecimal.valueOf(Double.parseDouble(ljPremium))).add(BigDecimal.valueOf(Double.parseDouble(iprVo.getTotal_premium())));

        //历史保额
        BigDecimal aom = (BigDecimal.valueOf(Double.parseDouble(eam))).multiply(BigDecimal.valueOf(Double.parseDouble(perNum)));
        String type = ConstProp.DIGIT_TWO.equals(iprVo.getRevise_type())?"-":"";
        //当次保额
        BigDecimal aom2 = (BigDecimal.valueOf(Double.parseDouble(eam))).multiply(BigDecimal.valueOf(Double.parseDouble(type+iprVo.getInsPreservationDetailVoList().size())));
        //剩余保额
        BigDecimal syaom = (BigDecimal.valueOf(Double.parseDouble(vo.getInsured_amount()))).add(aom).add(aom2);

        iprVo.setAmount_change(syaom.toPlainString());
        iprVo.setPremium_change(sypremium.toPlainString());
        iprVo.setTotal_amount(aom2.toPlainString());
        System.out.println("保单保费："+vo.getGross_premium()+"，历史保费："+ljPremium+"，当次保费："+iprVo.getTotal_premium()+"，剩余保费："+iprVo.getPremium_change());
        System.out.println("保单保额："+vo.getInsured_amount()+"，历史保额："+aom+"，当次保额："+aom2+"，剩余保额："+iprVo.getAmount_change());
    }

    /**
     * <b> 最新批单漏单情况，比对补偿 </b>
     * @author ZXF
     * @create 2023/08/17 0017 13:34
     * @version
     * @注意事项 </b>
     */
    @Override
    public boolean addFindPDTask(String record_id){
        log.info("====================> 进入 最新批单漏单情况，比对补偿 --------------------------------");
        String result = "";
        InsPreservationRecordVo iprVo = findInsPreservationRecordVoById(Long.parseLong(record_id));
        if(DictConst.REVISE_STATUS_BTG.equals(iprVo.getRevise_status())||DictConst.REVISE_STATUS_FQ.equals(iprVo.getRevise_status())||DictConst.REVISE_STATUS_TG.equals(iprVo.getRevise_status())||DictConst.REVISE_STATUS_SX.equals(iprVo.getRevise_status())){
            return true;
        }
        OrderFormVo orderFormVo = policyService.accordingToOrderIDToGetPolicyDto(Long.parseLong(iprVo.getIns_insurance_slip_id()));
        //排除前海以外的产品
        if(!orderFormVo.getProduct_code().contains(ConstProp.GZZRX_QH) && !orderFormVo.getProduct_code().contains(ConstProp.TYX_QH)){
            return true;
        }
        //单子滞留超过半小时自动审批退回
        try {
            if(DateUtil.compareDates(DateUtil.convertStringToDate(DateUtil.dateAdd(5,iprVo.getStart_time(),30)),new Date())){
                insPreservationRecordAPIDao.updateRecordFail(iprVo.getOid(),DictConst.REVISE_STATUS_BTG,"批改异常，请重新提交！");
                return true;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        try {
            //先通过保单查下最新的3个批单
//            gZZRX_QHRequestService.request_qh_gzzrx(Long.parseLong(iprVo.getIns_insurance_slip_id()), TransTypeEnum.ZXPG.getValue(),iprVo);
//            try {
//                Thread.sleep(10000);
//                System.out.println("======== > 重复查步骤休眠间隔:10S");
//            } catch (InterruptedException ex) {
//                throw new RuntimeException(ex);
//            }
            //再组装要查的批单号查询具体的批单信息
            //查数据库最新批改号+1
            String pdNo = insPreservationRecordAPIDao.getLastPDNoByPolicyNo(iprVo.getExternal_reference());
            String newPDNo = "";
            if(StringUtils.isEmpty(pdNo)){
                newPDNo = iprVo.getExternal_reference()+"-1";
            }else{
                newPDNo = iprVo.getExternal_reference()+"-"+(Integer.parseInt(pdNo.split("-")[1])+1);
            }
            iprVo.setRevise_serial_num_ins(newPDNo);
            if(orderFormVo.getProduct_code().contains(ConstProp.GZZRX_QH)){
                result = gZZRX_QHRequestService.request_qh_gzzrx(Long.parseLong(iprVo.getIns_insurance_slip_id()), TransTypeEnum.ZXPG.getValue(),iprVo);
            }else if(orderFormVo.getProduct_code().contains(ConstProp.TYX_QH)){
                result = tYX_QHRequestService.request_qh_tyx(Long.parseLong(iprVo.getIns_insurance_slip_id()), TransTypeEnum.ZXPG.getValue(),iprVo);
            }
            if(StringUtils.isNotEmpty(result)) {
                String[] arr = result.split("#");
                if(result.contains("200#")){
                    String idcards = arr[4];
                    //当前批改单跟查询的批改单，批改人员都能对得上就走补单流程，否则继续轮询
                    int sign = 0;
                    for(InsPreservationDetailVo vo : iprVo.getInsPreservationDetailVoList()){
                        if(!idcards.contains(vo.getId_card())){
                            sign = 1;
                            break;
                        }
                    }
                    //批单补单流程
                    if(sign == 0){
                        Map<String,String> map = Maps.newHashMap();
                        //200#批单号#保费#电子批单#投保人员身份证数组
                        //保单号
                        map.put("proposalNo",iprVo.getExternal_reference());
                        //批单号
                        map.put("batchNumber",arr[1]);
                        map.put("eurl",arr[3]);//电子批单
                        map.put("premium",arr[2]);
                        if(plyNoMap.getOrDefault(arr[1], 0)>0){
                            return true;
                        }
                        plyNoMap.put(arr[1],1);
                        updateRecordStatus(iprVo.getOid(), map);
                        return true;
                    }
                    String resultN = result;
                    myAsyncExecutor.execute(()->{
                        //如果没比对到 去查保单的所有待审批单做比对，注意可能存在重复批单（这种情况删除最新单补充最早单）
                        otherCheckRecord(Long.parseLong(iprVo.getIns_insurance_slip_id()),resultN);
                    });
                }
            }
        } catch (Exception e) {
           log.error("最新批单漏单情况，比对补偿,ERR:"+e.getMessage());
        }finally {
            //最终不管是否成功，都发起保单号查询，让渠道方完成补偿
            try {
                //先通过保单查下最新的3个批单
                iprVo.setRevise_serial_num_ins("");
                if(orderFormVo.getProduct_code().contains(ConstProp.GZZRX_QH)){
                    gZZRX_QHRequestService.request_qh_gzzrx(Long.parseLong(iprVo.getIns_insurance_slip_id()), TransTypeEnum.ZXPG.getValue(),iprVo);
                }else if(orderFormVo.getProduct_code().contains(ConstProp.TYX_QH)){
                    tYX_QHRequestService.request_qh_tyx(Long.parseLong(iprVo.getIns_insurance_slip_id()), TransTypeEnum.ZXPG.getValue(),iprVo);
                }
            } catch (Exception e) {
                log.error("最新批单漏单情况，比对补偿,最后3个批改查询，ERR:"+e.getMessage());
//                throw new RuntimeException(e);
            }
        }
        comTaskResidualAPIService.saveComTaskResidual("addFindPDTask","批改超时补偿","com.bcxin.ins.service.preservation.InsPreservationRecordAPIService",1,"String",record_id);
        return false;
    }

    /**
     * <b> 根据批单ID查询最后一个批单号 </b>
     * @author ZXF
     * @create 2023/09/18 0018 15:21
     * @version
     * @注意事项 </b>
     */
    public String last3Record(String record_id,String reNo){
        InsPreservationRecordVo iprVo = findInsPreservationRecordVoById(Long.parseLong(record_id));
        OrderFormVo orderFormVo = policyService.accordingToOrderIDToGetPolicyDto(Long.parseLong(iprVo.getIns_insurance_slip_id()));
        try {
            if("0".equals(reNo)){
                reNo = "";
            }
            //先通过保单查下最新的3个批单
            iprVo.setRevise_serial_num_ins(reNo);
            if(orderFormVo.getProduct_code().contains(ConstProp.GZZRX_QH)){
                return gZZRX_QHRequestService.request_qh_gzzrx(Long.parseLong(iprVo.getIns_insurance_slip_id()), TransTypeEnum.ZXPG.getValue(),iprVo);
            }else if(orderFormVo.getProduct_code().contains(ConstProp.TYX_QH)){
                return tYX_QHRequestService.request_qh_tyx(Long.parseLong(iprVo.getIns_insurance_slip_id()), TransTypeEnum.ZXPG.getValue(),iprVo);
            }
            return "";
        } catch (Exception e) {
            return "最新批单查询，ERR:"+e.getMessage();
        }
    }

    private void otherCheckRecord(Long policyId,String result){
        List<String> list = selectRecordIdByPolicyIdAndStatus(policyId, "2", "");
        InsPreservationRecordVo iprVo;
        for (String str:list) {
            iprVo = findInsPreservationRecordVoById(Long.parseLong(str));
            String[] arr = result.split("#");
            String idcards = arr[4];
            //当前批改单跟查询的批改单，批改人员都能对得上就走补单流程，否则继续轮询
            int sign = 0;
            for(InsPreservationDetailVo vo : iprVo.getInsPreservationDetailVoList()){
                if(!idcards.contains(vo.getId_card())){
                    sign = 1;
                    break;
                }
            }
            //批单补单流程
            if(sign == 0){
                int count = insPreservationRecordAPIDao.selectRecordByPdNo(arr[1]);
                if(count>0){
                    //批单号已存在，将当前单状态设置为废弃
                    insPreservationRecordAPIDao.deleteRecord(iprVo.getOid());
                    return;
                }
                Map<String,String> map = Maps.newHashMap();
                //200#批单号#保费#电子批单#投保人员身份证数组
                //保单号
                map.put("proposalNo",iprVo.getExternal_reference());
                //批单号
                map.put("batchNumber",arr[1]);
                map.put("eurl",arr[3]);//电子批单
                map.put("premium",arr[2]);
                if(plyNoMap.getOrDefault(arr[1], 0)>0){
                    return;
                }
                plyNoMap.put(arr[1],1);
                updateRecordStatus(iprVo.getOid(), map);
                return;
            }
        }
    }

    // 使用ConcurrentHashMap存储用户余额
    private static ConcurrentHashMap<String, Integer> plyNoMap = new ConcurrentHashMap<>();

    public void modifyPlyNo(String plyNo, Integer countNo){
        plyNoMap.compute(plyNo, (key, oldValue) -> {
            if (oldValue == null) {
                return 0;
            } else {
                return countNo;
            }
        });
    }

    public static void main(String[] args) {
//        OrderFormVo vo = new OrderFormVo();
//        vo.setInception_date("2023-03-29 00:00:00");
//        vo.setPlanned_end_date("2024-03-28 23:59:59");
//        vo.setPremium("552.00");
//
//        //年度
//        int syDay = DateUtil.getDistDates(DateUtil.convertStringToDate(vo.getInception_date()),DateUtil.convertStringToDate("2023-05-08 00:00:00"))+1;
//        int tolDay = DateUtil.getDistDates(DateUtil.convertStringToDate(vo.getInception_date()),DateUtil.convertStringToDate(vo.getPlanned_end_date()))+1;
//        BigDecimal liDay = BigDecimal.valueOf(1).subtract(BigDecimal.valueOf(syDay).divide(BigDecimal.valueOf(tolDay),6, BigDecimal.ROUND_HALF_UP));
//        BigDecimal tolP = BigDecimal.valueOf(Double.parseDouble(vo.getPremium())).multiply(BigDecimal.valueOf(2.0)).multiply(liDay).setScale(2, BigDecimal.ROUND_HALF_UP);
//        System.out.println("=====> syDay:"+syDay+",tolDay:"+tolDay+",liDay:"+liDay+",tolP:"+tolP);
        String start_time = "2023-09-18 14:39:11";
        try {
            Date d = new Date();
            if(DateUtil.compareDates(DateUtil.convertStringToDate(DateUtil.dateAdd(5,start_time,30)),new Date())){
                System.out.println("=====> 当前大于开始+30");
            }else{
                System.out.println("=====> 当前小于开始+30");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * <b> 创建保全单并更新状态生成保全缴费记录业务 </b>
     * @author ZXF
     * @create 2019/05/10 0010 16:00
     * @version
     * @注意事项 </b>
     */
    @Override
    public boolean recordRest(InsPreservationRecordVo vo) {
        InsPreservationRecordVo initVo = vo;
        try {
            //数据更新创建保全申请单
            if(createInsPreservationRecord(1,vo,vo.getInsPreservationDetailVoList())){
                updateRecordStatus(vo.getOid(), vo.getRecordRest());
                return true;
            }else{
                throw new RuntimeException("创建保全申请单发生异常");
            }
        } catch(Exception e) {
            log.info("===========[recordRest](异常)："+e);
            log.info("===========[recordRest](RecordRest)："+vo.getRecordRest());
            //如果保险公司业务完成但是百联保业务出现异常回滚，就记录任务定时跑
            if(vo.getRecordRest() != null){
                //如果需要添加残留任务，先删除已有任务再添加任务，防止重复添加多条相同属性任务
                String val = JSONObject.toJSONString(initVo);
                Map<String, Object> map = Maps.newHashMap();
			    map.put("method_name","recordRest");
			    map.put("param_value_arr",val);
                comTaskResidualAPIService.deleteByMap(map);

                comTaskResidualAPIService.saveComTaskResidual("recordRest","SASS做减员业务","com.bcxin.ins.service.preservation.InsPreservationRecordAPIService",1,"InsPreservationRecordVo",val);
            }
        }
        return false;
    }

    /**
     * <b> 如果是平安财雇主的就给加入暂存，方便之后补单 </b>
     * @author ZXF
     * @create 2021/05/20 0020 14:34
     * @version
     * @注意事项 </b>
     */
    @Override
    public boolean recordRestPAC(InsPreservationRecordVo iprvo) {
        OrderFormVo vo = policyService.accordingToOrderIDToGetPolicyDto(Long.parseLong(iprvo.getIns_insurance_slip_id()));
        if(vo.getProduct_code().contains(ConstProp.GZZRX_PAC) || vo.getProduct_code().contains(ConstProp.GZZRX_QH)){
            return recordRest(iprvo);
        }
        return false;
    }

    /**
     * <b> 特殊情况修改批单号(人保用) </b>
     * @author ZXF
     * @create 2020/01/07 0007 17:34
     * @version
     * @注意事项 </b>
     */
    @Override
    public boolean updateBatchNumber(String json) {
        if(StringUtils.isEmpty(json)){
            return false;
        }
        Map<String,String> map = JSON.parseObject(json,Map.class);
        if(map == null){
            return false;
        }
        String batch_number = PackageMessageRB.getPdh(map.get("batch_number"));
        if(StringUtils.isNotEmpty(batch_number)){
            insPreservationRecordAPIDao.updateBatchNumber(map.get("record_id"),batch_number);
            return true;
        }
        return false;
    }

    /**
     * <b> 保存同步业务支撑后台返回的id </b>
     * @author ZXF
     * @create 2020/02/26 0026 13:59
     * @version
     * @注意事项 </b>
     */
    @Override
    public void saveYWZCId(String record_id, String record_zc_id){
        insPreservationRecordAPIDao.saveYWZCId(record_id, record_zc_id);
    }

    /**
     * <b> 根据在保id查询批改单号</b>
     * @author ZXF
     * @create 2023/08/30 0030 14:13
     * @version
     * @注意事项 </b>
     */
    public String getRecordByResultId(String result_id){
        return insPreservationRecordAPIDao.getRecordByResultId(result_id);
    }

    /**
     * <b> 订单对账数据入库(定时器跑) </b>
     * @author ZXF
     * @create 2024/05/10 0010 18:16
     * @version
     * @注意事项 </b>
     */
    public void loadReconciliation() throws Exception {
        List<InsOrderReconciliation> list = gZZRX_TBRequestService.loadReconciliation("20240510");
        if(list.size()>0){
            insPreservationRecordAPIDao.batchOrderReconciliation(list);
        }
    }
}
