package com.yifu.cloud.plus.v1.yifu.insurances.util;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yifu.cloud.plus.v1.yifu.archives.vo.EmpIdCardAndDeptVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.EmpStatusVo;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.BigDecimalUtils;
import com.yifu.cloud.plus.v1.yifu.common.core.util.*;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.ArchivesDaprUtil;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.SalaryDaprUtil;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.SocialDaprUtils;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import com.yifu.cloud.plus.v1.yifu.ekp.constant.EkpConstants;
import com.yifu.cloud.plus.v1.yifu.insurances.constants.InsurancesConstants;
import com.yifu.cloud.plus.v1.yifu.insurances.entity.*;
import com.yifu.cloud.plus.v1.yifu.insurances.mapper.ekp.EkpInsurancesInfoMapper;
import com.yifu.cloud.plus.v1.yifu.insurances.mapper.insurances.TInsuranceDetailMapper;
import com.yifu.cloud.plus.v1.yifu.insurances.mapper.insurances.TUpdateStatusErrorMapper;
import com.yifu.cloud.plus.v1.yifu.insurances.service.ekp.EkpSettleService;
import com.yifu.cloud.plus.v1.yifu.insurances.service.insurance.TInsuranceEkpService;
import com.yifu.cloud.plus.v1.yifu.insurances.service.insurance.TInsuranceSettleCancelService;
import com.yifu.cloud.plus.v1.yifu.insurances.service.insurance.TInsuranceSettleService;
import com.yifu.cloud.plus.v1.yifu.insurances.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 主要执行商险的异步推送
 * @author huyc
 * @Date 2022-11-30
 * @Description 多线程的执行
 */
@Slf4j
@Component
public class DoJointInsuranceTask {

    @Resource
	private TInsuranceSettleService tInsuranceSettleService;

	@Autowired
	private TInsuranceEkpService tInsuranceEkpService;

	@Autowired
	private TInsuranceSettleCancelService tInsuranceSettleCancelService;

	@Autowired
	private EkpSettleService ekpSettleService;

	@Autowired
	private TInsuranceDetailMapper insuranceDetailMapper;

	@Autowired
	private SocialDaprUtils socialDaprUtils;

	@Autowired
	private SalaryDaprUtil salaryDaprUtil;

	@Autowired
	private TUpdateStatusErrorMapper updateStatusErrorMapper;

	@Autowired
	private ArchivesDaprUtil archivesDaprUtil;

	@Autowired
	private EkpInsurancesInfoMapper insurancesInfoMapper;


	/**
     * @Description: 商险明细推送
     * @Author: huyc
     * @Date: 2022-11-30
     * @return: void
     **/
    public void asynchronousEkpInfo(TInsuranceDetail detail, TInsuranceSettle settle, Integer type) {
        log.info("推送商险明细到EKP-线程开始");
        try {
			String s = pushEstimate(detail,type);
			if(StringUtils.isNotBlank(s)){
				if (type == CommonConstants.ONE_INT) {
					settle.setIsEstimatePush(CommonConstants.ONE_INT);
					settle.setEstimatePushTime(LocalDateTime.now());
				} else {
					settle.setIsActualPush(CommonConstants.ONE_INT);
					settle.setActualPushTime(LocalDateTime.now());
				}
				tInsuranceSettleService.updateById(settle);
			}
        } catch (Exception e) {
            log.error("推送商险明细到EKP错误", e);
        }
        log.info("推送商险明细到EKP结束");
    }

	/**
	 * 保存失败信息
	 *
	 * @author zhaji
	 * @param
	 * @return {@link String}
	 */
	private void saveInsuranceEkp(EkpInteractiveParam param, Integer pushType){
		TInsuranceEkp ekp = new TInsuranceEkp();
		BeanCopyUtils.copyProperties(param,ekp);
		ekp.setId(null);
		ekp.setCreateTime(LocalDateTime.now());
		ekp.setPushType(pushType);
		TInsuranceDetail byId = insuranceDetailMapper.selectById(param.getDetailId());
		ekp.setSettleType(byId.getSettleType().toString());
		tInsuranceEkpService.save(ekp);
	}

	/**
	 * 推送EKP
	 *
	 * @author zhaji
	 * @param
	 * @return {@link String}
	 */
	private String pushEstimate(TInsuranceDetail tInsuranceDetail,Integer type){
		YifuUser user = SecurityUtils.getUser();
		Integer pushType = null;
		//1,推送预估保费，2，推送实际保费，3推送预估冲正保费，4更新实际保费
		EkpInteractiveParam param = new EkpInteractiveParam();
		TInsuranceSettleCancel cancel = new TInsuranceSettleCancel();
		BeanCopyUtils.copyProperties(tInsuranceDetail,param);
		param.setDetailId(tInsuranceDetail.getId());
		Integer settleType = tInsuranceDetail.getSettleType();
		if(CommonConstants.ZERO_INT == settleType){
			param.setEstimateStatus(EkpConstants.HAVE);
		}else {
			param.setEstimateStatus(EkpConstants.NOTHING);
		}
		if (Common.isNotNull(tInsuranceDetail.getUnitName())) {
			param.setCustomerName(tInsuranceDetail.getUnitName());
		}
		if (Common.isNotNull(tInsuranceDetail.getUnitNo())) {
			param.setCustomerCode(tInsuranceDetail.getUnitNo());
		}
		//1,推送预估保费(用户办理成功，推送预估保费)
		if(CommonConstants.ONE_INT == type){
			param.setInteractiveType(InsurancesConstants.NEW_SETTLE_BILL);
			param.setSettleType(InsurancesConstants.ESTIMATE_SETTLE_BILL);
			pushType = CommonConstants.ONE_INT;
		}
		//2，推送实际保费(用于登记保单保费未推送过实缴保费)
		if(CommonConstants.TWO_INT == type){
			param.setInteractiveType(InsurancesConstants.NEW_SETTLE_BILL);
			param.setSettleType(InsurancesConstants.ACTUAL_SETTLE_BILL);
			pushType = CommonConstants.TWO_INT;
		}
		//3推送预估冲正保费(用于投保退回场景)
		if(CommonConstants.THREE_INT == type){
			String defaultSettleId = tInsuranceDetail.getDefaultSettleId();
			TInsuranceSettle byId = tInsuranceSettleService.getById(defaultSettleId);
			//冲正取负数
			if(null != byId.getEstimatePremium()){
				param.setEstimatePremium(byId.getEstimatePremium());
			}
			param.setInteractiveType(InsurancesConstants.CORRECT_SETTLE_BILL);
			param.setSettleType(InsurancesConstants.ESTIMATE_SETTLE_BILL);
			pushType = CommonConstants.FIVE_INT;
		}
		//6推送实缴红冲(用于投保退回场景)
		if(CommonConstants.SIX_INT == type){
			String defaultSettleId = tInsuranceDetail.getDefaultSettleId();
			TInsuranceSettle byId = tInsuranceSettleService.getById(defaultSettleId);
			//冲正取负数
			if(null != byId.getActualPremium()){
				param.setActualPremium(byId.getActualPremium());
			}
			param.setInteractiveType(InsurancesConstants.CORRECT_SETTLE_BILL);
			param.setSettleType(InsurancesConstants.ACTUAL_SETTLE_BILL);
			pushType = CommonConstants.SIX_INT;
		}
		//4更新实际保费(用于登记保单保费场景推送过实缴保费)
		if(CommonConstants.FOUR_INT == type){
			param.setInteractiveType(InsurancesConstants.UPDATE_SETTLE_BILL);
			param.setSettleType(InsurancesConstants.ACTUAL_SETTLE_BILL);
			pushType = CommonConstants.THREE_INT;
		}
		//作废
		if(CommonConstants.FIVE_INT == type){
			cancel.setDeptNo(tInsuranceDetail.getDeptNo());
			cancel.setInsDetailId(tInsuranceDetail.getId());
			cancel.setSettleId(tInsuranceDetail.getDefaultSettleId());
			cancel.setCreateUesr(user.getId());
			cancel.setCreateTime(LocalDateTime.now());
			cancel.setDeptName(param.getDeptName());
			cancel.setIsCancelPush(CommonConstants.ZERO_INT);
			tInsuranceSettleCancelService.save(cancel);
			param.setInteractiveType(InsurancesConstants.ABOLISH_SETTLE_BILL);
			param.setSettleType(CommonConstants.EMPTY_STRING);
			pushType = CommonConstants.FOUR_INT;
		}
		String s = this.insertInsrancesDetail(param);
		if(StringUtils.isBlank(s)){
			saveInsuranceEkp(param,pushType);
			return null;
		}else {
			return s;
		}
	}

	@Async
	public void updateInsuranceSettleStatus(EkpStatusParamVo vo) {
		try {
			//根据结算单号获取明细id和结算状态
			List<EkpInsuranceViewVo> viewVoList;
			TInsuranceDetail detail;
			viewVoList = ekpSettleService.selectViewBySettleNo(vo.getSettleNo(), vo.getPayFlag());
			if (viewVoList != null && !viewVoList.isEmpty()) {
				String insuranceId;
				for (EkpInsuranceViewVo viewVo : viewVoList) {
					//获取所有的明细id
					if (Common.isNotNull(viewVo.getId())) {
						insuranceId = viewVo.getId().substring(0, 19);
						detail = insuranceDetailMapper.selectById(insuranceId);
						if (Common.isNotNull(detail)) {
							//判断订单类型是预估还是实缴
							if (InsurancesConstants.ACTUAL_SETTLE_BILL.equals(viewVo.getOrderType())) {
								//判断是收入还是支出结算单号
								if (CommonConstants.ZERO_STRING.equals(vo.getPayFlag())) {
									detail.setSincomeSettleFlag(viewVo.getIncomeSettleFlag());
									detail.setSincomeCollectFlag(viewVo.getIncomeCollectFlag());
								} else {
									detail.setSpaySettleFlag(viewVo.getPaySettleFlag());
									detail.setSpayCollectFlag(viewVo.getPayCollectFlag());
								}
							} else {
								if (CommonConstants.ZERO_STRING.equals(vo.getPayFlag())) {
									detail.setIncomeSettleFlag(viewVo.getIncomeSettleFlag());
									detail.setIncomeCollectFlag(viewVo.getIncomeCollectFlag());
								} else {
									detail.setPaySettleFlag(viewVo.getPaySettleFlag());
									detail.setPayCollectFlag(viewVo.getPayCollectFlag());
								}
							}
							insuranceDetailMapper.updateById(detail);
						}
					}
				}
			}
		} catch (Exception e) {
			TUpdateStatusError error = new TUpdateStatusError();
			error.setSettleNo(vo.getSettleNo());
			error.setStatus(CommonConstants.ZERO_INT);
			error.setTitle(e.getMessage());
			error.setTypeFlag(CommonConstants.FOUR_STRING);
			error.setCreateTime(DateUtil.getCurrentDateTime());
			error.setSettleType(vo.getPayFlag());
			updateStatusErrorMapper.insert(error);
			log.error("推送商险明细到EKP错误", e);
		}
	}

	@Async
	public void updateSocialSettleStatus(EkpStatusParamVo vo) {
		List<EkpSocialViewVo> viewVo;
		try {
			//根据结算单号获取明细id和结算状态
			if (CommonConstants.ZERO_STRING.equals(vo.getTypeFlag())) {
				viewVo = ekpSettleService.selectSocialViewBySettleNo(vo.getSettleNo(), vo.getPayFlag());
			} else {
				viewVo = ekpSettleService.selectFundViewBySettleNo(vo.getSettleNo(), vo.getPayFlag());
			}
			if (viewVo != null && !viewVo.isEmpty()) {
				viewVo.forEach(e -> e.setPayFlag(vo.getPayFlag()));
				R<Boolean> flag = socialDaprUtils.updateSocialSettleStatus(viewVo);
				if (Common.isEmpty(flag) || Boolean.TRUE.equals(!flag.getData())) {
					TUpdateStatusError error = new TUpdateStatusError();
					error.setSettleNo(vo.getSettleNo());
					error.setStatus(CommonConstants.ZERO_INT);
					error.setTitle("社保结算状态同步失败");
					error.setTypeFlag(vo.getTypeFlag());
					error.setCreateTime(DateUtil.getCurrentDateTime());
					error.setSettleType(vo.getPayFlag());
					updateStatusErrorMapper.insert(error);
				}
			}
		} catch (Exception e) {
			TUpdateStatusError error = new TUpdateStatusError();
			error.setSettleNo(vo.getSettleNo());
			error.setStatus(CommonConstants.ZERO_INT);
			error.setTitle("社保结算状态同步失败");
			error.setTypeFlag(vo.getTypeFlag());
			error.setCreateTime(DateUtil.getCurrentDateTime());
			error.setSettleType(vo.getPayFlag());
			updateStatusErrorMapper.insert(error);
			log.error("社保结算状态更新异常", e);
		}
	}

	@Async
	public void updateIncomeSettleStatus(EkpStatusParamVo vo) {
		List<EkpInsuranceViewVo> viewVo;
		try {
			//根据结算单号获取明细id和结算状态
			//根据结算单号获取明细id和结算状态；判断是管理费还是风险金
			if (CommonConstants.ZERO_STRING.equals(vo.getTypeFlag())) {
				viewVo = ekpSettleService.selectIncomelViewBySettleNo(vo.getSettleNo());
			} else {
				viewVo = ekpSettleService.selectFIncomelViewBySettleNo(vo.getSettleNo());
			}
			if (viewVo != null && !viewVo.isEmpty()) {
				R<Boolean> flag = socialDaprUtils.updateIncomeSettleStatus(viewVo);
				if (Common.isEmpty(flag) || Boolean.TRUE.equals(!flag.getData())) {
					TUpdateStatusError error = new TUpdateStatusError();
					error.setSettleNo(vo.getSettleNo());
					error.setStatus(CommonConstants.ZERO_INT);
					error.setTitle("收入结算状态同步失败");
					error.setTypeFlag(CommonConstants.ZERO_STRING.equals(vo.getTypeFlag()) ? "2" : "3");
					error.setCreateTime(DateUtil.getCurrentDateTime());
					error.setSettleType(vo.getPayFlag());
					updateStatusErrorMapper.insert(error);
				}
			}
		} catch (Exception e) {
			TUpdateStatusError error = new TUpdateStatusError();
			error.setSettleNo(vo.getSettleNo());
			error.setStatus(CommonConstants.ZERO_INT);
			error.setTitle("收入结算状态同步失败");
			error.setTypeFlag(CommonConstants.ZERO_STRING.equals(vo.getTypeFlag()) ? "2" : "3");
			error.setCreateTime(DateUtil.getCurrentDateTime());
			error.setSettleType(vo.getPayFlag());
			updateStatusErrorMapper.insert(error);
			log.error("收入结算状态更新异常", e);
		}
	}

	@Async
	public void updateSalarySettleStatus(EkpStatusParamVo vo) {
		List<EkpSocialViewVo> viewVo;
		try {
			//薪资结算状态同步暂时解决方案为定时任务去更新
			/*TUpdateStatusError error = new TUpdateStatusError();
			error.setSettleNo(vo.getSettleNo());
			error.setStatus(CommonConstants.ZERO_INT);
			error.setTitle("薪资结算状态同步成功");
			error.setTypeFlag(CommonConstants.FIVE_STRING);
			error.setCreateTime(DateUtil.getCurrentDateTime());
			error.setSettleType(vo.getPayFlag());
			updateStatusErrorMapper.insert(error);*/
			TUpdateStatusError error = new TUpdateStatusError();
			error.setSettleNo(vo.getSettleNo());
			error.setCreateTime(DateUtil.getCurrentDateTime());
			error.setSettleType(vo.getPayFlag());
			error.setTypeFlag(CommonConstants.FIVE_STRING);
			//根据结算单号获取明细id和结算状态
			viewVo = ekpSettleService.selectSalarylViewBySettleNo(vo.getSettleNo(), vo.getPayFlag());
			if (viewVo != null && !viewVo.isEmpty()) {
				viewVo.forEach(e -> e.setPayFlag(vo.getPayFlag()));
				R<Boolean> flag = salaryDaprUtil.updateSalarySettleStatus(viewVo);
				if (Common.isEmpty(flag) || Boolean.TRUE.equals(!flag.getData())) {

					error.setStatus(CommonConstants.ZERO_INT);
					error.setTitle("薪资结算状态同步失败");
					updateStatusErrorMapper.insert(error);
				}else {
					error.setStatus(CommonConstants.ZERO_INT);
					error.setTitle("薪资结算状态同步成功");
					updateStatusErrorMapper.insert(error);
				}
			}
		} catch (Exception e) {
			TUpdateStatusError error = new TUpdateStatusError();
			error.setSettleNo(vo.getSettleNo());
			error.setStatus(CommonConstants.ZERO_INT);
			error.setTitle("薪资结算状态同步失败");
			error.setTypeFlag(CommonConstants.FIVE_STRING);
			error.setCreateTime(DateUtil.getCurrentDateTime());
			error.setSettleType(vo.getPayFlag());
			updateStatusErrorMapper.insert(error);
			log.error("薪资结算状态更新异常", e);
		}
	}

	public void aUpdateInsuranceSettleStatus(TUpdateStatusError error) {
		try {
			//根据结算单号获取明细id和结算状态
			List<EkpInsuranceViewVo> viewVoList;
			TInsuranceDetail detail;
			viewVoList = ekpSettleService.selectViewBySettleNo(error.getSettleNo(), error.getSettleType());
			if (viewVoList != null && !viewVoList.isEmpty()) {
				String insuranceId;
				for (EkpInsuranceViewVo viewVo : viewVoList) {
					//获取所有的明细id
					if (Common.isNotNull(viewVo.getId())) {
						insuranceId = viewVo.getId().substring(0, 19);
						detail = insuranceDetailMapper.selectById(insuranceId);
						if (Common.isNotNull(detail)) {
							//判断订单类型是预估还是实缴
							if (InsurancesConstants.ACTUAL_SETTLE_BILL.equals(viewVo.getOrderType())) {
								//判断是收入还是支出结算单号
								if (CommonConstants.ZERO_STRING.equals(error.getSettleType())) {
									detail.setSincomeSettleFlag(viewVo.getIncomeSettleFlag());
									detail.setSincomeCollectFlag(viewVo.getIncomeCollectFlag());
								} else {
									detail.setSpaySettleFlag(viewVo.getPaySettleFlag());
									detail.setSpayCollectFlag(viewVo.getPayCollectFlag());
								}
							} else {
								if (CommonConstants.ZERO_STRING.equals(error.getSettleType())) {
									detail.setIncomeSettleFlag(viewVo.getIncomeSettleFlag());
									detail.setIncomeCollectFlag(viewVo.getIncomeCollectFlag());
								} else {
									detail.setPaySettleFlag(viewVo.getPaySettleFlag());
									detail.setPayCollectFlag(viewVo.getPayCollectFlag());
								}
							}
							insuranceDetailMapper.updateById(detail);
						}
					}
				}
				error.setStatus(CommonConstants.ONE_INT);
				error.setTitle(InsurancesConstants.AGAIN_UPDATE_STATUS);
				updateStatusErrorMapper.updateById(error);
			}
		} catch (Exception e) {
			log.error("更新商险结算状态错误", e);
		}
	}

	public void aUpdateSocialSettleStatus(TUpdateStatusError error) {
		List<EkpSocialViewVo> viewVo;
		try {
			//根据结算单号获取明细id和结算状态
			if (CommonConstants.ZERO_STRING.equals(error.getTypeFlag())) {
				viewVo = ekpSettleService.selectSocialViewBySettleNo(error.getSettleNo(), error.getSettleType());
			} else {
				viewVo = ekpSettleService.selectFundViewBySettleNo(error.getSettleNo(), error.getSettleType());
			}
			if (viewVo != null && !viewVo.isEmpty()) {
				viewVo.forEach(e -> e.setPayFlag(error.getSettleType()));
				R<Boolean> flag = socialDaprUtils.updateSocialSettleStatus(viewVo);
				if (!Common.isEmpty(flag) || Boolean.TRUE.equals(flag.getData())) {
					error.setStatus(CommonConstants.ONE_INT);
					error.setTitle(InsurancesConstants.AGAIN_UPDATE_STATUS);
					updateStatusErrorMapper.updateById(error);
				}
			}
		} catch (Exception e) {
			log.error("社保结算状态更新异常", e);
		}
	}

	public void aUpdateIncomeSettleStatus(TUpdateStatusError error) {
		List<EkpInsuranceViewVo> viewVo;
		try {
			//根据结算单号获取明细id和结算状态
			//根据结算单号获取明细id和结算状态；判断是管理费还是风险金
			if (CommonConstants.TWO_STRING.equals(error.getTypeFlag())) {
				viewVo = ekpSettleService.selectIncomelViewBySettleNo(error.getSettleNo());
			} else {
				viewVo = ekpSettleService.selectFIncomelViewBySettleNo(error.getSettleNo());
			}
			if (viewVo != null && !viewVo.isEmpty()) {
				R<Boolean> flag = socialDaprUtils.updateIncomeSettleStatus(viewVo);
				if (!Common.isEmpty(flag) || Boolean.TRUE.equals(flag.getData())) {
					error.setStatus(CommonConstants.ONE_INT);
					error.setTitle(InsurancesConstants.AGAIN_UPDATE_STATUS);
					updateStatusErrorMapper.updateById(error);
				}
			}
		} catch (Exception e) {
			log.error("收入结算状态更新异常", e);
		}
	}

	public void aUpdateSalarySettleStatus(TUpdateStatusError error) {
		List<EkpSocialViewVo> viewVo;
		try {
			//根据结算单号获取明细id和结算状态
			viewVo = ekpSettleService.selectSalarylViewBySettleNo(error.getSettleNo(), error.getSettleType());
			if (viewVo != null && !viewVo.isEmpty()) {
				viewVo.forEach(e -> e.setPayFlag(error.getSettleType()));
				R<Boolean> flag = salaryDaprUtil.updateSalarySettleStatus(viewVo);
				if (!Common.isEmpty(flag) && Boolean.TRUE.equals(flag.getData())) {
					error.setStatus(CommonConstants.ONE_INT);
					error.setTitle("再次同步状态成功");
					error.setTypeFlag(CommonConstants.FIVE_STRING);
					updateStatusErrorMapper.updateById(error);
				}
			}
		} catch (Exception e) {
			log.error("薪资结算状态更新异常", e);
		}
	}

	/**
	 * @param sourceList
	 * @Description: // 同步操作档案的 商险状态为：3失效（0无2正常3失效4处理中）
	 * @Author: hgw
	 * @Date: 2022/11/23 15:46
	 * @return: void
	 **/
	@Async
	public void updateEmpInfp(List<TInsuranceDetail> sourceList, String status) {
		EmpStatusVo empStatusVo = new EmpStatusVo();
		EmpIdCardAndDeptVo empIdCardAndDeptVo;
		List<EmpIdCardAndDeptVo> voList = new ArrayList<>();
		for (TInsuranceDetail d : sourceList) {
			empIdCardAndDeptVo = new EmpIdCardAndDeptVo();
			empIdCardAndDeptVo.setIdCard(d.getEmpIdcardNo());
			empIdCardAndDeptVo.setDeptNo(d.getDeptNo());
			empIdCardAndDeptVo.setStatus(status);
			voList.add(empIdCardAndDeptVo);
		}
		empStatusVo.setEmpInfo(voList);
		archivesDaprUtil.updateEmployeeInsuranceStatus(empStatusVo);
		archivesDaprUtil.updateEmployeeInfoInsuranceStatus(empStatusVo);
	}

	/**
	 * @Description: 商险明细推送
	 * @Author: huyc
	 * @Date: 2022-11-30
	 * @return: void
	 **/
	@Async
	public void pushEstime(List<TInsuranceDetail> successList) {
		//根据结算类型是合并结算，推送预估保费到ekp(上面已经算好，这里直接判断有预估保费的就推送)
		for (TInsuranceDetail tInsuranceDetail : successList) {
			//如果是合并计算则推送至EKP
			if (CommonConstants.ZERO_INT == tInsuranceDetail.getSettleType()) {
				//存储成功后发送给EKP
				String s = pushEstimate(tInsuranceDetail, CommonConstants.ONE_INT);
				if (StringUtils.isNotBlank(s)) {
					LambdaUpdateWrapper<TInsuranceSettle> settleWrapper = new LambdaUpdateWrapper<>();
					settleWrapper.eq(TInsuranceSettle::getId, tInsuranceDetail.getDefaultSettleId())
							.set(TInsuranceSettle::getIsEstimatePush, CommonConstants.ONE_INT)
							.set(TInsuranceSettle::getEstimatePushTime, LocalDateTime.now());
					//更新结算信息表
					tInsuranceSettleService.update(settleWrapper);
				}
			}
		}
	}

	/**
	 * 商险接口表单触发重写
	 *
	 * @author huych
	 * @param param 转换类
	 * @return {@link TInsuranceSettlePushParam}
	 */
	public String insertInsrancesDetail(EkpInteractiveParam param) {
		try {
			//作废
			if (InsurancesConstants.ABOLISH_SETTLE_BILL.equals(param.getInteractiveType())) {
				insurancesInfoMapper.delete(Wrappers.<EkpInsurancesInfo>query().lambda()
						.eq(EkpInsurancesInfo::getFd_3b0a5743acab7e, param.getDetailId()+CommonConstants.DOWN_LINE_STRING + (null == param.getDefaultSettleId() ? "" :param.getDefaultSettleId()))
						.eq(EkpInsurancesInfo::getFd_3adfe6ec6a8cbe, "未结算"));
			}
			//查询项目信息
			EkpInsuranceDeptInfoVo deptInfoVo = ekpSettleService.getInsuranceEkpDeptInfo(param.getDeptNo());
			if (null == deptInfoVo) {
				return null;
			}
			//新建商险订单明细
			if (InsurancesConstants.NEW_SETTLE_BILL.equals(param.getInteractiveType())) {
				EkpInsurancesInfo pushParam = new EkpInsurancesInfo();
				String code = "";
				if (InsurancesConstants.ESTIMATE_SETTLE_BILL.equals(param.getSettleType())) {
					code = "1";
				} else if (InsurancesConstants.ACTUAL_SETTLE_BILL.equals(param.getSettleType())) {
					code = "2";
				}
				initValues(pushParam, deptInfoVo, param,code);
				//应收
				double ys = 0L;
				if (!"是".equals(deptInfoVo.getIsBpo())) {
					if (InsurancesConstants.ACTUAL_SETTLE_BILL.equals(param.getSettleType()) && "有".equals(pushParam.getFd_3af9d1441ef7b6())) {
						ys = BigDecimalUtils.safeSubtract(false, param.getActualPremium(), param.getEstimatePremium()).doubleValue();
					} else if (InsurancesConstants.ACTUAL_SETTLE_BILL.equals(param.getSettleType()) && "无".equals(pushParam.getFd_3af9d1441ef7b6())) {
						ys = param.getActualPremium().doubleValue();
					} else {
						ys = param.getEstimatePremium().doubleValue();
					}
				}
				pushParam.setFd_3adfe6e30f2a3c(ys);
				//付款状态
				pushParam.setFd_3adfe6f05531ec("未付");
				//是否bpo客户
				pushParam.setFd_3b178fab62d196(null != param.getBpoFlag() ? param.getBpoFlag() : CommonConstants.EMPTY_STRING);
				//派单客服姓名
				pushParam.setFd_3c6f0108e05c84(null != param.getCreateName() ? param.getCreateName() : CommonConstants.EMPTY_STRING);
				//商险封面抬头
				pushParam.setFd_3b941cbcea3e1a(deptInfoVo.getInsurancesTitle());
				//是否启用BPO结算模式
				pushParam.setFd_usebpo_settle("否".equals(deptInfoVo.getIsBpo()) ? "否" : deptInfoVo.getBpoSettle());
				insurancesInfoMapper.insert(pushParam);
				//更新预估单实缴数据（新增预估实缴单时）
				if (InsurancesConstants.ACTUAL_SETTLE_BILL.equals(param.getSettleType())) {
					EkpInsurancesInfo info = insurancesInfoMapper.getEkpInsurancesInfoYg(param.getDetailId()+
							CommonConstants.DOWN_LINE_STRING + (null == param.getDefaultSettleId() ? "" :param.getDefaultSettleId()));
					if (Common.isNotNull(info)) {
						initValueUpdate(info, deptInfoVo, param);
					}
				}
			}
			//红冲
			if (InsurancesConstants.CORRECT_SETTLE_BILL.equals(param.getInteractiveType()) && "否".equals(param.getBpoFlag())) {
				EkpInsurancesInfo pushParam = new EkpInsurancesInfo();
				String code = "";
				if (InsurancesConstants.ESTIMATE_SETTLE_BILL.equals(param.getSettleType())) {
					code = "3";
				} else if (InsurancesConstants.ACTUAL_SETTLE_BILL.equals(param.getSettleType())) {
					code = "4";
				}
				initValues(pushParam, deptInfoVo, param,code);
				//应收
				pushParam.setFd_3adfe6e30f2a3c(InsurancesConstants.ACTUAL_SETTLE_BILL.equals(param.getSettleType()) ? param.getActualPremium().doubleValue() :param.getEstimatePremium().doubleValue());
				insurancesInfoMapper.insert(pushParam);
			}
			//更新
			if (InsurancesConstants.UPDATE_SETTLE_BILL.equals(param.getInteractiveType())) {
				//更新商险订单明细数据（应收金额不更新）
				List<EkpInsurancesInfo> list = insurancesInfoMapper.getEkpInsurancesInfoList(param.getDetailId()+CommonConstants.DOWN_LINE_STRING +
						(null == param.getDefaultSettleId() ? "" :param.getDefaultSettleId()));
				if (Common.isNotNull(list) && !list.isEmpty()) {
					for (EkpInsurancesInfo info: list) {
						initValueUpdate(info, deptInfoVo, param);
					}
				}
				//更新实缴单据应收金额
				EkpInsurancesInfo info = insurancesInfoMapper.getEkpInsurancesInfo(param.getDetailId()
						+CommonConstants.DOWN_LINE_STRING + (null == param.getDefaultSettleId() ? "" :param.getDefaultSettleId()));
				if (Common.isNotNull(info)) {
					//实际保费
					info.setFd_3adfe6610c0d2c(null != param.getActualPremium() ? param.getActualPremium().doubleValue() : null);
					//应收
					info.setFd_3adfe6e30f2a3c("是".equals(param.getBpoFlag()) ? 0 : BigDecimalUtils.safeSubtract(false,param.getActualPremium(),param.getEstimatePremium()).doubleValue());
					//应支
					info.setFd_3adfe6e3911ffe(param.getActualPremium().doubleValue());
					insurancesInfoMapper.updateById(info);
				}
			}
			return "sucess";
		}catch (Exception e) {
			log.error("执行异常", e);
			return null;
		}
	}

	/**
	 * 更新商险订单明细
	 *
	 * @author huych
	 * @param param 转换类
	 * @return {@link TInsuranceSettlePushParam}
	 */
	@Async
	public void updateInsrancesDetail(EkpUpdateParam param) {
		try {
			//更新商险变更记录已结算
			List<EkpInsurancesInfo> infoList = insurancesInfoMapper.getEkpInsurancesInfoNotSettle(param.getFd_3b5bf032d7a822());
			if (Common.isNotNull(infoList)) {
				for (EkpInsurancesInfo info :infoList) {
					//保单开始时间
					info.setFd_3b5bf17ae91f9c(DateUtil.stringToDate(param.getFd_3b5bf02d3b8fc4()));
					//保单结束时间
					info.setFd_3b5bf17c6df310(DateUtil.stringToDate(param.getFd_3b5bf02e1d47cc()));
					//投保类型
					info.setFd_3b5bf17d9297c2(param.getFd_3b5bf02fa14596());
					//变更发票号
					info.setFd_3b5bf17f2fc25c(param.getFd_3b5bf030ab1a56());
					//变更购买标准
					info.setFd_3b5bf180e08fbe(param.getFd_3b5bf031b52314());
					//商险变更记录
					String updateInfo = "";
					if (Common.isNotNull(info.getFd_3b3e4653122c9e())) {
						updateInfo = info.getFd_3b3e4653122c9e() + "\\n";
					}
					info.setFd_3b5bf1628c5a68(updateInfo + param.getFd_3b5bf0b7b4c058());
					insurancesInfoMapper.updateById(info);
				}
			}
			//更新商险变更记录未结算
			List<EkpInsurancesInfo> unInfoList = insurancesInfoMapper.getEkpInsurancesInfoSettle(param.getFd_3b5bf032d7a822());
			if (Common.isNotNull(unInfoList)) {
				for (EkpInsurancesInfo unInfo :unInfoList) {
					//发票号
					if (Common.isNotNull(param.getFd_3b5bf030ab1a56())) {
						unInfo.setFd_3adfe65e0cd094(param.getFd_3b5bf030ab1a56());
					}
					//保单号
					if (Common.isNotNull(param.getFd_3bb431933ee968())) {
						unInfo.setFd_3adfe65e60e110(param.getFd_3bb431933ee968());
					}
					//保险开始日期
					unInfo.setFd_3adfe6b7e0ede8(DateUtil.stringToDate(param.getFd_3b5bf02d3b8fc4()));
					//保险结束日期
					unInfo.setFd_3adfe6b847bfe6(DateUtil.stringToDate(param.getFd_3b5bf02e1d47cc()));
					//购买标准
					unInfo.setFd_3adfe6d55384c6(Double.parseDouble(null == param.getFd_3b5bf031b52314() ? "0" : param.getFd_3b5bf031b52314()));
					//保单开始时间
					unInfo.setFd_3b5bf17ae91f9c(DateUtil.stringToDate(param.getFd_3b5bf02d3b8fc4()));
					//保单结束时间
					unInfo.setFd_3b5bf17c6df310(DateUtil.stringToDate(param.getFd_3b5bf02e1d47cc()));
					//投保类型
					unInfo.setFd_3b5bf17d9297c2(param.getFd_3b5bf02fa14596());
					//变更发票号
					if (Common.isNotNull(param.getFd_3b5bf030ab1a56())) {
						unInfo.setFd_3b5bf17f2fc25c(param.getFd_3b5bf030ab1a56());
					}
					//变更购买标准
					unInfo.setFd_3b5bf180e08fbe(param.getFd_3b5bf031b52314());
					//商险变更记录
					String updateInfo = "";
					if (Common.isNotNull(unInfo.getFd_3b3e4653122c9e())) {
						updateInfo = unInfo.getFd_3b3e4653122c9e() + "\\n";
					}
					unInfo.setFd_3b5bf1628c5a68(updateInfo + param.getFd_3b5bf0b7b4c058());
					insurancesInfoMapper.updateById(unInfo);
				}
			}
		}catch (Exception e) {
			log.error("执行异常", e);
		}
	}

	public static String dateStringInsert(String month) {
		if (month.length() == 6) {
			StringBuilder sb = new StringBuilder(month);
			sb.insert(4, "-");
			return sb.toString();
		}
		return month;
	}

	//商险新增初始化
	public void initValues(EkpInsurancesInfo pushParam,EkpInsuranceDeptInfoVo deptInfoVo,EkpInteractiveParam param,String code) throws ParseException {
		//单号,sxdd + 商险id + 标识
		pushParam.setFd_3adfe67a9f6364("SXDD" + LocalDateTimeUtils.formatTime(LocalDateTime.now(),DateUtil.ISO_DATE_FORMAT)
				+ param.getDetailId() + code );
		//项目id 项目编码
		pushParam.setFd_3b16dfb32778f2(deptInfoVo.getFdId());
		pushParam.setFd_3b16dfb32778f2_text(deptInfoVo.getDeptNo());
		//实际结算月份DateUtil.parseDate(dateStringInsert(param.getSettleMonth()),"yyyy-MM")
		if ("结算月本月数据".equals(deptInfoVo.getInsurancesType())) {
			pushParam.setFd_3af9d11088facc(DateUtil.parseDate(param.getSettleMonth(), DateUtil.DATETIME_YYYY_MM));
		} else if ("结算月上月数据".equals(deptInfoVo.getInsurancesType())) {
			pushParam.setFd_3af9d11088facc(DateUtil.addMonthByDate(DateUtil.parseDate(param.getSettleMonth(), DateUtil.DATETIME_YYYY_MM), -1));
		} else {
			pushParam.setFd_3af9d11088facc(null);
		}
		//是否全部结算
		pushParam.setFd_3b13b2ecc164aa("全量未结算数据".equals(deptInfoVo.getInsurancesType()) ? "是" : "否");
		//ekpId
		if (null != param.getDetailId() && null != param.getDefaultSettleId()) {
			pushParam.setFd_3b0a5743acab7e(param.getDetailId() + CommonConstants.DOWN_LINE_STRING + param.getDefaultSettleId());
		} else {
			pushParam.setFd_3b0a5743acab7e(CommonConstants.EMPTY_STRING);
		}
		//单据类型
		pushParam.setFd_3adfe6af71a1cc(null != param.getSettleType() ? param.getSettleType() : CommonConstants.EMPTY_STRING);
		//项目编码
		pushParam.setFd_3adfe658c6229e(null != param.getDeptNo() ? param.getDeptNo() : CommonConstants.EMPTY_STRING);
		//项目名称
		pushParam.setFd_3adfe6592b4158(null != param.getDeptName() ? param.getDeptName() : CommonConstants.EMPTY_STRING);
		//客户编码
		pushParam.setFd_3adfe6598281e8(null != param.getCustomerCode() ? param.getCustomerCode() : CommonConstants.EMPTY_STRING);
		//客户名称
		pushParam.setFd_3adfe7a2688902(null != param.getCustomerName() ? param.getCustomerName() : CommonConstants.EMPTY_STRING);
		//发生日期
		pushParam.setFd_3adfe67c24dace(DateUtil.getCurrentDateTime());
		//姓名
		pushParam.setFd_3adfe65d759650(null != param.getEmpName() ? param.getEmpName() : CommonConstants.EMPTY_STRING);
		//身份证号
		pushParam.setFd_3adfe65dbd9f68(null != param.getEmpIdcardNo() ? param.getEmpIdcardNo() : CommonConstants.EMPTY_STRING);
		//发票号
		pushParam.setFd_3adfe65e0cd094(null != param.getInvoiceNo() ? param.getInvoiceNo() : CommonConstants.EMPTY_STRING);
		//险种
		pushParam.setFd_3adfe65f6599e4(null != param.getInsuranceTypeName() ? param.getInsuranceTypeName() : CommonConstants.EMPTY_STRING);
		//保险公司
		pushParam.setFd_3adfe65ea04728(null != param.getInsuranceCompanyName() ? param.getInsuranceCompanyName() : CommonConstants.EMPTY_STRING);
		//保单号
		pushParam.setFd_3adfe65e60e110(null != param.getPolicyNo() ? param.getPolicyNo() : CommonConstants.EMPTY_STRING);
		//保险开始日期
		pushParam.setFd_3adfe6b7e0ede8(null != param.getPolicyStart() ? DateUtil.stringToDate(param.getPolicyStart().toString()) : null);
		//保险结束日期
		pushParam.setFd_3adfe6b847bfe6(null != param.getPolicyEnd() ? DateUtil.stringToDate(param.getPolicyEnd().toString()) : null);
		//购买标准
		pushParam.setFd_3adfe6d55384c6(Common.isNotNull(param.getBuyStandard()) ? Double.parseDouble(param.getBuyStandard()) : null);
		//实际保费
		pushParam.setFd_3adfe6610c0d2c(null != param.getActualPremium() ? param.getActualPremium().doubleValue() : null);
		//医保
		pushParam.setFd_3adfe66041a996(Common.isNotNull(param.getMedicalQuota()) ? Double.parseDouble(param.getMedicalQuota()) : null);
		//事故或残疾
		pushParam.setFd_3adfe6609aa810(Common.isNotNull(param.getDieDisableQuota()) ? param.getDieDisableQuota() : CommonConstants.EMPTY_STRING);
		//预估保费
		pushParam.setFd_3af9d15f7018fa(null != param.getEstimatePremium() ? param.getEstimatePremium().doubleValue() : null);
		//hro结算月
		pushParam.setFd_3b13b3076af5a0(null != param.getSettleMonth() ? DateUtil.parseDate(param.getSettleMonth(), DateUtil.DATETIME_YYYY_MM) : null);
		//有无预估
		pushParam.setFd_3af9d1441ef7b6(null != param.getEstimateStatus() ? param.getEstimateStatus() : CommonConstants.EMPTY_STRING);
		//结算状态
		pushParam.setFd_3adfe6ec6a8cbe("未结算");
		//收款状态
		pushParam.setFd_3adfe6ef5dfaac("未收");
		//支出结算状态
		pushParam.setFd_3adfe6eda67236("未结算");
		//创建时间
		pushParam.setCreateTime(DateUtil.getCurrentDateTime());
		//应支出
		pushParam.setFd_3adfe6e3911ffe(InsurancesConstants.ACTUAL_SETTLE_BILL.equals(param.getSettleType()) ? pushParam.getFd_3adfe6610c0d2c() : 0);
	}

	//商险更新赋值
	public void initValueUpdate(EkpInsurancesInfo info,EkpInsuranceDeptInfoVo deptInfoVo,EkpInteractiveParam param) throws ParseException {
		//实际结算月份
		info.setFd_3af9d11088facc(!"全量未结算数据".equals(deptInfoVo.getInsurancesType()) ? DateUtil.parseDate(param.getSettleMonth(), DateUtil.DATETIME_YYYY_MM) : null);
		//是否全部结算
		info.setFd_3b13b2ecc164aa("全量未结算数据".equals(deptInfoVo.getInsurancesType()) ? "是" : "否");
		//预估保费
		info.setFd_3af9d15f7018fa(null != param.getEstimatePremium() ? param.getEstimatePremium().doubleValue() : null);
		//发票号
		if (Common.isNotNull(param.getInvoiceNo())) {
			info.setFd_3adfe65e0cd094(param.getInvoiceNo());
		}
		//险种
		info.setFd_3adfe65f6599e4(null != param.getInsuranceTypeName() ? param.getInsuranceTypeName() : CommonConstants.EMPTY_STRING);
		//保险公司
		info.setFd_3adfe65ea04728(null != param.getInsuranceCompanyName() ? param.getInsuranceCompanyName() : CommonConstants.EMPTY_STRING);
		//保单号
		if (Common.isNotNull(param.getPolicyNo())) {
			info.setFd_3adfe65e60e110(param.getPolicyNo());
		}
		info.setFd_3adfe65e60e110(null != param.getPolicyNo() ? param.getPolicyNo() : CommonConstants.EMPTY_STRING);
		//保险开始日期
		info.setFd_3adfe6b7e0ede8(null != param.getPolicyStart() ? DateUtil.stringToDate(param.getPolicyStart().toString()) : null);
		//保险结束日期
		info.setFd_3adfe6b847bfe6(null != param.getPolicyEnd() ? DateUtil.stringToDate(param.getPolicyEnd().toString()) : null);
		//购买标准
		info.setFd_3adfe6d55384c6(Common.isNotNull(param.getBuyStandard()) ? Double.parseDouble(param.getBuyStandard()) : null);
		//实际保费
		info.setFd_3adfe6610c0d2c(Common.isNotNull(param.getActualPremium()) ? param.getActualPremium().doubleValue() : null);
		//医保
		info.setFd_3adfe66041a996(Common.isNotNull(param.getMedicalQuota()) ? Double.parseDouble(param.getMedicalQuota()) : null);
		//事故或残疾
		info.setFd_3adfe6609aa810(Common.isNotNull(param.getDieDisableQuota()) ? param.getDieDisableQuota() : CommonConstants.EMPTY_STRING);
		//hro结算月
		info.setFd_3b13b3076af5a0(null != param.getSettleMonth() ? DateUtil.parseDate(param.getSettleMonth(), DateUtil.DATETIME_YYYY_MM) : null);
		insurancesInfoMapper.updateById(info);
	}
}
