package com.yd.api.commission.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yd.api.commission.service.LifeCommissionService;
import com.yd.api.commission.vo.lifecommission.*;
import com.yd.api.result.CommonResult;
import com.yd.dal.entity.commission.AgPoOrderCommission;
import com.yd.dal.entity.commission.OrderCommissonCheck;
import com.yd.dal.entity.customer.AclCustomerFortune;
import com.yd.dal.entity.customer.AclInsurerBranch;
import com.yd.dal.entity.customer.AclPractitionerSubordinateSystem;
import com.yd.dal.entity.meta.MdDropOptions;
import com.yd.dal.entity.order.PoOrder;
import com.yd.dal.mapper.commission.AgPoOrderCommissionMapper;
import com.yd.dal.mapper.customer.AclPractitionerMapper;
import com.yd.dal.mapper.lifecommission.LifeCommissionMapper;
import com.yd.dal.service.customer.AclCustomerFortuneDALService;
import com.yd.dal.service.customer.AclPractitionerSubordinateSystemDALService;
import com.yd.dal.service.order.PoOrderDALService;
import com.yd.rmi.ali.send.service.SendService;
import com.yd.rmi.cache.SystemConfigService;
import com.yd.util.HttpUtil;
import com.yd.util.JsonUtil;
import com.yd.util.config.ZHBErrorConfig;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


@Service
public class LifeCommissionServiceImpl implements LifeCommissionService {

    @Autowired
    private LifeCommissionMapper lifeCommissionMapper;
    @Autowired
    private AclCustomerFortuneDALService customerFortuneDalService;
    @Autowired
    private PoOrderDALService poOrderDALService;
    @Autowired
    private SystemConfigService systemConfigService;
    @Autowired
    private SendService sendService;
    @Autowired
    private AgPoOrderCommissionMapper orderCommissionMapper;
    @Autowired
    private AclPractitionerSubordinateSystemDALService aclPractitionerSubordinateSystemDALService;
    @Autowired
    private AclPractitionerMapper aclPractitionerMapper;


    @Override
    public ComeCommissionListResponseVO queryComeCommissionList(QueryComeCommissionListRequestVO requestVO) {
        ComeCommissionListResponseVO resp = new ComeCommissionListResponseVO();
        String commissionType = requestVO.getCommissionType();
        try {
//            if (StringUtils.isBlank(commissionType)) {
//                resp.setCommonResult(new CommonResult(false, "佣金类型不能为空"));
//                return resp;
//            }
//            if ("2".equals(commissionType)) {
//                this.querySpecialCommission(requestVO, resp);
//            } else {
//                this.queryBaseCommission(requestVO, resp);
//            }

            this.queryBaseCommission(requestVO, resp);

            // 设置佣金项目名称
            this.setCommissionItemName(resp);

            resp.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));
        } catch (Exception e) {
            e.printStackTrace();
            resp.setCommonResult(new CommonResult(false, e.getMessage()));
        }
        return resp;
    }

    private void setCommissionItemName(ComeCommissionListResponseVO resp) {
        List<ComeCommissionVO> list = resp.getDataList();

        MdDropOptions dropOption = null;
        String masterCode = null;
        for (ComeCommissionVO item : list) {
            if ("1".equals(item.getCommissionType())) {
                dropOption = systemConfigService.getDropOption("Base_Commission_Item", item.getCommissionItem());
                item.setCommissionTypeName("基础来佣");
            } else {
                dropOption = systemConfigService.getDropOption("Special_Commission_Type", item.getCommissionItem());
                item.setCommissionTypeName("特殊激励来佣");
            }
            if (dropOption != null) {
                item.setCommissionItemName(dropOption.getDropOptionName());
            }
        }
    }

    private void querySpecialCommission(QueryComeCommissionListRequestVO requestVO, ComeCommissionListResponseVO resp) {
        PageInfo<ComeCommissionVO> page = requestVO.getPage();

        String orderBy = "orderDate desc";

        PageHelper.startPage(page.getPageNum(), page.getPageSize(), orderBy);

        List<ComeCommissionVO> dataList = lifeCommissionMapper.querySpecialCommissionList(requestVO);

        PageInfo<ComeCommissionVO> pageInfo = new PageInfo<>(dataList);

        resp.setDataList(pageInfo.getList());
        pageInfo.setList(null);
        resp.setPage(pageInfo);
    }

    private void queryBaseCommission(QueryComeCommissionListRequestVO requestVO, ComeCommissionListResponseVO resp) {
        // 分页结果集
        PageInfo<ComeCommissionVO> pageInfo = this.queryComeCommissionListPage(requestVO);
        resp.setDataList(pageInfo.getList());
        pageInfo.setList(null);
        resp.setPage(pageInfo);
        // 不分页结果集统计总单数，总保费，总来佣，待来佣总数，已比对总数，已退保总数
        Map<String, Object> summaries = lifeCommissionMapper.getSummaries(requestVO);
        // 不分页结果集统计总寿险经纪人人数
        Integer lifePractitionerCount = lifeCommissionMapper.queryLifePractitionerCount(requestVO);
        resp.setLifePractitionerCount(String.valueOf(lifePractitionerCount));
        resp.setTotalOrderPrice(summaries.get("totalOrderPrice").toString());
        resp.setTotalCommission(summaries.get("totalCommission").toString());
        resp.setTotalSingular(summaries.get("totalSingular").toString());
        resp.setTotalDaiLaiYong(summaries.get("totalDaiLaiYong").toString());
        resp.setTotalYiBiDui(summaries.get("totalYiBiDui").toString());
        resp.setTotalYiTuiBao(summaries.get("totalYiTuiBao").toString());
    }

    @Override
    public CheckComeCommissionResponseVO updateCommissionCheckStatus(CheckComeCommissionRequestVO requestVO) {
        CheckComeCommissionResponseVO resp = new CheckComeCommissionResponseVO();
        List<ComeCommissionParams> paramsList = requestVO.getParamsList();
        String status = requestVO.getCheckStatus();
        String loginId = requestVO.getLoginId();
        String checkBatch = requestVO.getCheckBatch();

        if (StringUtils.isBlank(checkBatch)) {
            resp.setCommonResult(new CommonResult(false, "检核日期不能为空"));
            return resp;
        }
        // 已退保时，提示不能修改已比对的数据
        if ("3".equals(status)) {
            StringBuffer stringBuffer = new StringBuffer();
            for (ComeCommissionParams params: paramsList) {
                if (StringUtils.isNotBlank(params.getCommissionNo())) {
                    AgPoOrderCommission agPoOrderCommission = orderCommissionMapper.selectByCommissionNo(params.getCommissionNo());
                    if (agPoOrderCommission != null && "2".equals(agPoOrderCommission.getCommissionStatus())) {
                        stringBuffer.append(params.getCommissionNo()).append(" ");
                    }
                }
            }
            if (StringUtils.isNotBlank(stringBuffer.toString())) {
                stringBuffer.append(" :已比对的数据不能改为已退保");
                resp.setCommonResult(new CommonResult(false, stringBuffer.toString()));
                return resp;
            }
        }

        try {
            // 1.检核续年佣金时先判断，前面期数的佣金是否检核过
//            this.validateContinuePremium(paramsList);

            // 2.更新财富等信息
            this.processOrderAndFortune(paramsList, status, loginId, checkBatch);

            // 3.更新多年期佣金
            this.updateOrderCommission(paramsList, status, loginId, checkBatch);

            resp.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));

        } catch (Exception e) {
            e.printStackTrace();
            resp.setCommonResult(new CommonResult(false, e.getMessage()));
        }
        return resp;
    }

    private void validateContinuePremium(List<ComeCommissionParams> paramsList) throws Exception {
        // 提示信息
        StringBuffer stringBuffer = new StringBuffer("以下来佣未检核： ");

        List<String> commissionNos = new ArrayList<>();
        for (ComeCommissionParams params: paramsList) {
            if (StringUtils.isNotBlank(params.getCommissionNo())) {
                commissionNos.add(params.getCommissionNo());
            }
        }
        String str ="";
        String prefix ="";
        String suffix ="";
        boolean flag = false;
        for (String commissionNo: commissionNos) {

            str = commissionNo;

            if (!"1".equals(suffix)) {

                prefix = str.substring(0, str.length() -1);
                suffix = str.substring(str.length()-1) ;
                // 前一期的来佣编号
                String preCommissionNo = prefix + (Integer.valueOf(suffix) - 1);

                AgPoOrderCommission agPoOrderCommission = orderCommissionMapper.selectByCommissionNo(preCommissionNo);
                if (agPoOrderCommission != null && "1".equals(agPoOrderCommission.getCommissionStatus())) {
                    stringBuffer.append(preCommissionNo).append(" ");
                    flag = true;
                }
            }
        }

        if (flag) {
            throw new Exception(stringBuffer.toString());
        }
    }

    private void processOrderAndFortune(List<ComeCommissionParams> paramsList, String status, String loginId, String checkBatch) {
        // 获取首年度佣金的orderId， 只有首年佣金才更新order记录和fortune记录
        List<Long> orderIds = new ArrayList<>();
        Long orderId;
        for (ComeCommissionParams params : paramsList) {
            // 查询对应订单记录
            orderId = params.getOrderId();
            if (orderId != null) {
                PoOrder order = poOrderDALService.findByOrderId(orderId);
                if (order != null && "1".equals(params.getCommissionPeriod())) {
                    orderIds.add(orderId);
                    // 只有首年记录更新order表
                    this.updateOrder(order, status, loginId, checkBatch);
                }
            }
            this.updateFortune(params.getCommissionId(), status, loginId, checkBatch);
        }

        if (orderIds.size() != 0 && "3".equals(status)) {
            // 订单已退保后发送邮件通知运营
            List<PoOrder> orders = poOrderDALService.findByIds(orderIds);
            this.orderCommissionCheckCancelSendMail(orders);
        }
    }

    private void updateOrderCommission(List<ComeCommissionParams> paramsList, String status, String loginId, String checkBatch) {
        // 获取批次号（如2020-11的字符串）
        Long checkBatchId = this.getOrderCommissionCheckBatch(checkBatch, loginId);
        Set<Long> commissionCancelorderIdSet = new HashSet<>();
        Set<Long> commissionComparedorderIdSet = new HashSet<>();

        // 更新检核状态
        Long commissionId= null;
        for (ComeCommissionParams params: paramsList) {
            commissionId = params.getCommissionId();
            if ("3".equals(status)) {
                // 来佣比对进行“已退保”操作时，当前状态为待来佣时才修改
                AgPoOrderCommission agPoOrderCommission = orderCommissionMapper.selectByPrimaryKey(commissionId);
                if ("1".equals(agPoOrderCommission.getCommissionStatus())) {
                    AgPoOrderCommission orderCommission = new AgPoOrderCommission();
                    orderCommission.setId(commissionId);
                    orderCommission.setCommissionCheckId(checkBatchId);
                    orderCommission.setCommissionStatus(status);
                    orderCommission.setCommissionTime("");
                    orderCommission.setUpdatedBy(Long.valueOf(loginId));
                    orderCommission.setUpdatedAt(new Date());

                    orderCommissionMapper.updateByPrimaryKeySelective(orderCommission);
                    // 退保的orderId
                    if (null != agPoOrderCommission.getOrderId()) {
                        commissionCancelorderIdSet.add(agPoOrderCommission.getOrderId());
                    }
                }
            } else {
                AgPoOrderCommission orderCommission = new AgPoOrderCommission();
                orderCommission.setId(commissionId);
                orderCommission.setCommissionCheckId(checkBatchId);
                orderCommission.setCommissionStatus(status);
                if ("2".equals(status)) {
                    orderCommission.setCommissionTime(checkBatch);
                    if (null != params.getOrderId()) {
                        commissionComparedorderIdSet.add(params.getOrderId());
                    }
                } else {
                    orderCommission.setCommissionTime("");
                }
                orderCommission.setUpdatedBy(Long.valueOf(loginId));
                orderCommission.setUpdatedAt(new Date());

                orderCommissionMapper.updateByPrimaryKeySelective(orderCommission);
            }
        }
        // 如果是已退保，将后续期数的待来佣记录都改为已退保
        for (Long orderId : commissionCancelorderIdSet) {
            List<AgPoOrderCommission> list = orderCommissionMapper.selectByOrderId(orderId);
            for (AgPoOrderCommission item : list) {
                if ("1".equals(item.getCommissionStatus())) {

                    AgPoOrderCommission orderCommission = new AgPoOrderCommission();
                    orderCommission.setCommissionNo(item.getCommissionNo());
                    orderCommission.setCommissionCheckId(checkBatchId);
                    orderCommission.setCommissionStatus("3");
                    orderCommission.setCommissionTime("");
                    orderCommission.setUpdatedBy(Long.valueOf(loginId));
                    orderCommission.setUpdatedAt(new Date());

                    orderCommissionMapper.updateByPrimaryKeySelective(orderCommission);
                }
            }
        }

		try {
	        // 如果是已比对，自动重新计算该保单的最新发佣数据
			if (CollectionUtils.isNotEmpty(commissionComparedorderIdSet)) {
				Long [] orderIds = new Long[commissionComparedorderIdSet.size()];
				commissionComparedorderIdSet.toArray(orderIds);
		        Map<String, Object> req = new HashMap<>(16);
		        req.put("loginId", StringUtils.isEmpty(loginId) == true ? "-1" : loginId);
		        req.put("orderIds", orderIds);
		        req.put("ruleType", "2");
				String requestJson = JsonUtil.objToJson(req);
				String SYSTEM_URL = systemConfigService.getSingleConfigValue("SYSTEM_URL");
				ExecutorService executor = Executors.newSingleThreadExecutor();
				executor.execute(new Runnable() {
					@Override
					public void run(){
						HttpUtil.postForJson(SYSTEM_URL + "/api/settlementRule/calculateCommissionByOrderIds", requestJson);
					}
				});
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
    }

    @Override
    public QuerycheckBatchListResponseVO querycheckBatchList() {
        QuerycheckBatchListResponseVO resp = new QuerycheckBatchListResponseVO();
        try {
            PageHelper.clearPage();//偶然遇到了这个问题，同一个查询结果一会是10个（预期），一会是真实个数（刷新/重启应用就又变成真实个数）  查看日志，发现了问题：结果为10个时查询SQL自动加上了Limit 10
            List<String> checkBatchList = lifeCommissionMapper.querycheckBatchList();

            // 将["2020-12","2020-11"]转为[{“key”:"2020-12","value":null}]
            List<Map<String, String>> dataList = new ArrayList<>();
            for (int i = 0; i < checkBatchList.size(); i++) {
                Map<String, String> map = new HashMap<>();
                map.put("key", checkBatchList.get(i));
                map.put("value", null);
                dataList.add(map);
            }

            resp.setCheckBatchList(dataList);
            resp.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));
        } catch (Exception e) {
            e.printStackTrace();
            resp.setCommonResult(new CommonResult(false, e.getMessage()));
        }
        return resp;
    }

    @Override
    public ExportComeCommissionResponseVO exportComeCommission(QueryComeCommissionListRequestVO requestVO, HttpServletResponse response) {

        ExportComeCommissionResponseVO responseVO = new ExportComeCommissionResponseVO();

        List<ComeCommissionVO> dataList = lifeCommissionMapper.queryComeCommissionList(requestVO);
        // 查询体系架构信息
        queryOrganization(dataList);

        createCSV(dataList, response);
        responseVO.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));
        return responseVO;
    }

    private void queryOrganization(List<ComeCommissionVO> dataList) {
        List<AclPractitionerSubordinateSystem> subordinateSystemList = aclPractitionerSubordinateSystemDALService.findAll();
        Map<Long, AclPractitionerSubordinateSystem> subordinateSystemMap = new HashMap<>();
        if (subordinateSystemList != null && subordinateSystemList.size() > 0) {
            for (AclPractitionerSubordinateSystem item : subordinateSystemList) {
                subordinateSystemMap.put(item.getId(), item);
            }
        }
        Map<Long, AclInsurerBranch> aclInsurerBranchMap = systemConfigService.getAclInsurerBranchMap();

        //所属体系
        AclPractitionerSubordinateSystem subordinateSystem = null;
        //分公司
        AclInsurerBranch insurerBranch = null;

        ComeCommissionVO comeCommissionVO = null;
        MdDropOptions dropOption = null;

        for (int i = 0; i < dataList.size(); i++) {
            comeCommissionVO = dataList.get(i);

            if ("1".equals(comeCommissionVO.getCommissionType())) {
                dropOption = systemConfigService.getDropOption("Base_Commission_Item", comeCommissionVO.getCommissionItem());
                comeCommissionVO.setCommissionTypeName("基础来佣");
            } else {
                dropOption = systemConfigService.getDropOption("Special_Commission_Type", comeCommissionVO.getCommissionItem());
                comeCommissionVO.setCommissionTypeName("特殊激励来佣");
            }
            if (dropOption != null) {
                comeCommissionVO.setCommissionItemName(dropOption.getDropOptionName());
            }

            if (comeCommissionVO.getS1Id() != null) {
                subordinateSystem = subordinateSystemMap.get(comeCommissionVO.getS1Id());
                if (subordinateSystem != null) {
                    comeCommissionVO.setSubordinateSystemName(subordinateSystem.getName());

                    if ("S2".equals(subordinateSystem.getSystemType())) {
                        comeCommissionVO.setS2SubordinateSystemName(subordinateSystem.getName());
                    }
                }
            }

            if (null != comeCommissionVO.getS2Id()) {
                subordinateSystem = subordinateSystemMap.get(comeCommissionVO.getS2Id());
                comeCommissionVO.setS2SubordinateSystemName(subordinateSystem != null ? subordinateSystem.getName() : null);
            }
            if (null != comeCommissionVO.getS3Id()) {
                subordinateSystem = subordinateSystemMap.get(comeCommissionVO.getS3Id());
                comeCommissionVO.setS3SubordinateSystemName(subordinateSystem != null ? subordinateSystem.getName() : null);
            }
            if (null != comeCommissionVO.getYdBranchId()) {
                insurerBranch = aclInsurerBranchMap.get(Long.valueOf(comeCommissionVO.getYdBranchId()));
                comeCommissionVO.setYdBranchName(insurerBranch != null ? insurerBranch.getBranchName() : "总公司直属");
            } else {
                comeCommissionVO.setYdBranchName("总公司直属");
            }
        }
    }

    private void orderCommissionCheckCancelSendMail(List<PoOrder> orders) {
        //发送邮件
        List<String> ccList = systemConfigService.getListConfigValue("CancelPolicyNotifyCommissionChecking");
        List<String> arrList = new ArrayList(ccList);
        String email = arrList.remove(0);
        String[] ccAddresses = arrList.toArray(new String[arrList.size()]);

        StringBuilder messageText = new StringBuilder();
        for (PoOrder order:orders) {
            messageText.append("保单号:").append(order.getPolicyNo()).append("<br>");
        }
        messageText.append("<br>");
        messageText.append("来佣比对已退保，请知悉");

        String subject = "来佣比对已退保";
        sendService.sendEmailOrSMS("email", email, "3", messageText.toString(), null, subject, ccAddresses, "来佣比对已退保", 99, null, null);
    }

    private void updateFortune(Long commissionId, String status, String loginId, String checkBatch) {
        // 查询对应的fortune记录
        List<AclCustomerFortune> fortuneList = customerFortuneDalService.queryLifeFortuneListByCommissionId(commissionId);
        // 更新fortune记录是否可发放
        String fortuneCommissionPayoutStatus = "3".equals(status) ? "1" : "0";//旧发佣检核状态字段

        if (fortuneList.size() > 0) {
            // 批量设置fortune为可发佣
            for (AclCustomerFortune f : fortuneList) {
                f.setCommissionPayoutStatus(fortuneCommissionPayoutStatus);
                f.setCommissionPayoutAt(new Date());
                f.setCommissionPayoutBy(Long.valueOf(loginId));
            }
            customerFortuneDalService.updateBatch(fortuneList);
        }
    }

    private void updateOrder(PoOrder order, String status, String loginId, String checkBatch) {
        // 获取批次号（如2020-11的字符串）
        Long checkBatchId = this.getOrderCommissionCheckBatch(checkBatch, loginId);
        // 设置order记录的CommissionCheckId
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("checkId", checkBatchId);
        paramMap.put("status", status);
        paramMap.put("checkAt", new Date());
        paramMap.put("checkBy", loginId);

        /**检核选择退保时先查看原来的来佣状态，若原来的是”已比对“则不改成已退保，若是“待来佣”和“保留”就改成”已退保“*/
        if ("3".equals(status)) {
            if (!"2".equals(order.getCommissionCheckStatus())) {
                lifeCommissionMapper.setOrderCommissionCheckId(Arrays.asList(order.getId()), paramMap);
            }
        } else {
            lifeCommissionMapper.setOrderCommissionCheckId(Arrays.asList(order.getId()), paramMap);
        }
    }
    private void validateClosed(List<PoOrder> orders, List<AclCustomerFortune> fortuneList, String status) throws Exception {
        StringBuilder stringBuilder = new StringBuilder();
        Map<Long, String> orderIdPolicyNoMap = new HashMap<>();
        for (PoOrder o:orders) {
            orderIdPolicyNoMap.put(o.getId(), o.getPolicyNo());
        }
        for (AclCustomerFortune f:fortuneList) {
            if ("4".equals(f.getCommissionPayoutStatus())) {
                stringBuilder.append(orderIdPolicyNoMap.get(f.getOrderId())+" ");
            }
        }
        if (StringUtils.isNotEmpty(stringBuilder.toString())) {
            stringBuilder.append("订单下存在已发放的财富记录，不能改状态");
            if (!"3".equals(status)) {
                throw new Exception(stringBuilder.toString());
            }
        }
    }

    private PageInfo<ComeCommissionVO> queryComeCommissionListPage(QueryComeCommissionListRequestVO requestVO) {
        PageInfo<ComeCommissionVO> page = requestVO.getPage();

        PageHelper.startPage(page.getPageNum(), page.getPageSize(), null);

        List<ComeCommissionVO> dataList = lifeCommissionMapper.queryComeCommissionList(requestVO);

        PageInfo<ComeCommissionVO> pageInfo = new PageInfo<>(dataList);

        return pageInfo;
    }

    private void setOrderCommissionCheckId(Long orderId, String status, Long checkBatchId, String loginId) {
        // 更新参数
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("checkId", checkBatchId);
        paramMap.put("status", status);
        paramMap.put("checkAt", new Date());
        paramMap.put("checkBy", loginId);

        /**检核选择退保时先查看原来的来佣状态，若原来的是”已比对“则不改成已退保，若是”待来佣“就改成”已退保“*/
        if ("3".equals(status)) {
            PoOrder order = poOrderDALService.findByOrderId(orderId);
            if ("1".equals(order.getCommissionCheckStatus())) {
                lifeCommissionMapper.setOrderCommissionCheckId(Arrays.asList(orderId), paramMap);
            }
        } else {
            lifeCommissionMapper.setOrderCommissionCheckId(Arrays.asList(orderId), paramMap);
        }
    }

    private Long getOrderCommissionCheckBatch(String OrderCommissionCheckBatch, String loginId) {
        List<OrderCommissonCheck> list = lifeCommissionMapper.findByCheckYearmonth(OrderCommissionCheckBatch);
        OrderCommissonCheck orderCommissonCheck = null;
        if (list.size() > 0) {
            orderCommissonCheck = list.get(0);
        }
        if (orderCommissonCheck == null){
            // 获取当前时间
            Date curDate = new Date();
            orderCommissonCheck = new OrderCommissonCheck();
            orderCommissonCheck.setCheckYearmonth(OrderCommissionCheckBatch);
            orderCommissonCheck.setCreatedAt(curDate);
            orderCommissonCheck.setCreatedBy(loginId);
            orderCommissonCheck.setUpdatedAt(curDate);
            orderCommissonCheck.setUpdatedBy(loginId);
            lifeCommissionMapper.insertOrderCommissionCheck(orderCommissonCheck);
        }
        return orderCommissonCheck.getId();
    }

    private void createCSV(List<ComeCommissionVO> dataList, HttpServletResponse response) {
        String charset = "UTF-8"; // 读取字符编码
        String[] columnName = new String[]{"序号", "来佣编号", "预计来佣年月", "实际来佣年月", "检核年月", "银盾出单机构", "保险公司", "保险分公司",
                "保单号", "保费", "来佣类型", "来佣项目", "来佣率", "来佣金额", "来佣状态 ", "经纪人", "S3纵队", "S2体系", "S1分部", "经纪人类型",
                "下单时间", "购买方案", "产品险种", "保险种类", "缴费年限", "保障期间","保单跟踪状态","保单出单来源","备注"
        };
        String tableName = "YD_Export_ComeCommission";
        String CSV_COLUMN_SEPARATOR = ",";//CSV文件列分隔符
        String CSV_ROW_SEPARATOR = "\r\n";//CSV文件行分隔符
        // 保证线程安全
        StringBuilder buf = new StringBuilder();
        // 组装表头
        for (String title : columnName) {
            buf.append(title).append(CSV_COLUMN_SEPARATOR);
        }
        buf.append(CSV_ROW_SEPARATOR);
        // 组装数据
        if (CollectionUtils.isNotEmpty(dataList)) {
            for (int i = 0; i < dataList.size(); i++) {
                ComeCommissionVO info = dataList.get(i);//遍历每个对象
                buf.append(i + 1).append(CSV_COLUMN_SEPARATOR);
                buf.append(info.getCommissionNo()).append(CSV_COLUMN_SEPARATOR);
                buf.append("\t").append(info.getCommissionYear()).append("\t").append(CSV_COLUMN_SEPARATOR);
                buf.append("\t").append(info.getCommissionTime()).append("\t").append(CSV_COLUMN_SEPARATOR);
                buf.append("\t").append(info.getCheckDate()).append("\t").append(CSV_COLUMN_SEPARATOR);
                buf.append(info.getYdBranchName()).append(CSV_COLUMN_SEPARATOR);
                buf.append(info.getInsurerName()).append(CSV_COLUMN_SEPARATOR);
                buf.append(info.getInsurerBranchName()).append(CSV_COLUMN_SEPARATOR);
                buf.append("\t").append(info.getPolicyNo()).append("\t").append(CSV_COLUMN_SEPARATOR);
                buf.append(info.getOrderPrice()).append(CSV_COLUMN_SEPARATOR);

                buf.append(info.getCommissionTypeName()).append(CSV_COLUMN_SEPARATOR);
                buf.append(info.getCommissionItemName()).append(CSV_COLUMN_SEPARATOR);

                buf.append(info.getCommissionRate()).append(CSV_COLUMN_SEPARATOR);
                buf.append(info.getCommissionAmount()).append(CSV_COLUMN_SEPARATOR);
                buf.append(this.transferCommissionCheckStatus(info.getCommissionCheckStatus())).append(CSV_COLUMN_SEPARATOR);
                buf.append(info.getName()).append(CSV_COLUMN_SEPARATOR);
                buf.append(info.getS3SubordinateSystemName()).append(CSV_COLUMN_SEPARATOR);
                buf.append(info.getS2SubordinateSystemName()).append(CSV_COLUMN_SEPARATOR);
                buf.append(info.getSubordinateSystemName()).append(CSV_COLUMN_SEPARATOR);

                if ("27".equals(info.getPractitionerTypeId())) {
                    buf.append("产险").append(CSV_COLUMN_SEPARATOR);
                } else if ("28".equals(info.getPractitionerTypeId())) {
                    buf.append("寿险").append(CSV_COLUMN_SEPARATOR);
                } else {
                    buf.append("/").append(CSV_COLUMN_SEPARATOR);
                }
                buf.append("\t").append(info.getOrderDate()).append("\t").append(CSV_COLUMN_SEPARATOR);
                buf.append(info.getPlanName()).append(CSV_COLUMN_SEPARATOR);
                buf.append(info.getPlanCategoryName()).append(CSV_COLUMN_SEPARATOR);
                buf.append(info.getCategoryName()).append(CSV_COLUMN_SEPARATOR);
                buf.append(info.getPayTerm()).append(CSV_COLUMN_SEPARATOR);
                buf.append(info.getCoverageTerm() == null ? "/" : info.getCoverageTerm()).append(CSV_COLUMN_SEPARATOR);
                buf.append(info.getPolicyTrackingStatus() == null ? "/" : handlePolicyTrackingStatus(info.getPolicyTrackingStatus())).append(CSV_COLUMN_SEPARATOR);
                MdDropOptions dropOption = systemConfigService.getDropOption("policy_input_source", info.getPolicyInputSource());
                buf.append(dropOption == null ? "/" : dropOption.getDropOptionName()).append(CSV_COLUMN_SEPARATOR);
                buf.append(info.getRemark() == null ? "" : info.getRemark()).append(CSV_COLUMN_SEPARATOR);


                buf.append(CSV_ROW_SEPARATOR);
            }
        }
        // 设置文件后缀
        String fn = tableName + System.currentTimeMillis() + ".csv";
        String headStr = "attachment; filename=\"" + fn + "\"";
        // 设置响应
        response.setContentType("APPLICATION/ms-csv.numberformat");
        response.setCharacterEncoding(charset);
        response.setHeader("Content-Disposition", headStr);
        response.setHeader("Cache-Control", "max-age=30");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Pragma", "public");
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            os.write(buf.toString().getBytes("GBK"));
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private String transferCommissionCheckStatus(String commissionCheckStatus) {
        if ("1".equals(commissionCheckStatus)) {
            return "待来佣";
        } else if ("2".equals(commissionCheckStatus)) {
            return "已比对";
        } else if ("3".equals(commissionCheckStatus)) {
            return "已退保";
        } else if ("4".equals(commissionCheckStatus)) {
            return "保留";
        } else {
            return "";
        }
    }
    public static String handlePolicyTrackingStatus(Long policyTrackingStatus) {
        String ret = null;
        if (policyTrackingStatus == 1L) {
            ret = "承保件";
        } else if (policyTrackingStatus == 2L) {
            ret = "契撤件";
        } else if (policyTrackingStatus == 3L) {
            ret = "减额缴清";
        } else if (policyTrackingStatus == 4L) {
            ret = "失效件";
        } else if (policyTrackingStatus == 5L) {
            ret = "协议退保/解约件";
        }else if (policyTrackingStatus == 6L) {
            ret = "退保件";
        }else if (policyTrackingStatus == 7L) {
            ret = "终止件";
        }else if (policyTrackingStatus == 8L) {
            ret = "豁免保费";
        }else if (policyTrackingStatus == 9L) {
            ret = "犹退件";
        }else if (policyTrackingStatus == 10L) {
            ret = "保全件";
        }else if (policyTrackingStatus == 11L) {
            ret = "理赔件";
        }
        return ret;
    }

}
