package com.funde.gras.allot.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.funde.gras.api.utils.*;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.funde.gras.api.common.MyConstant;
import com.funde.gras.api.common.PaasHttpRequest;
import com.funde.gras.api.common.PageInfo;
import com.funde.gras.api.domain.*;
import com.funde.gras.api.service.*;

/**
 * ClassName:  ResultCheckServiceImpl
 * Description:  []
 * Date:  2018年8月3日 下午4:46:39
 *
 * @author ASUS
 */
@Service(version = "1.0.0", timeout = 15000000, interfaceName = "com.funde.gras.api.service.ResultCheckService")
public class ResultCheckServiceImpl implements ResultCheckService {

    private Integer failedCount = 0;

    private final String SUCCESSFUL_FLAG = "1";

    private final String FAILED_FLAG = "2";

    private Integer succesCount = 0;

    @Reference(version = "1.0.0")
    private OracleGrasSysTempService sysTempService;

    @Reference(version = "1.0.0")
    private OracleBranchInfoService branchInfoService;

    @Reference(version = "1.0.0")
    private OracleRuleDealService ruleDealService;

    @Reference(version = "1.0.0")
    private OraclePolicyPremInfoService premInfoService;

    @Reference(version = "1.0.0")
    private OracleGrasAssignBatchRecordService batchRecordService;

    @Reference(version = "1.0.0")
    private OraclePolicyService policyService;

    @Reference(version = "1.0.0")
    private OracleGrasAssignFailedRecordService failedRecordService;

    //@Reference(version = "1.0.0")
    //private FallingMapService mapService;

    @Reference(version = "1.0.0")
    private OracleStaffInfoService staffInfoService;

    @Reference(version = "1.0.0")
    private OracleEmpStatusService oracleEmpStatusService;

    @Reference(version = "1.0.0")
    private OracleGrasSysTempService tempService;

    @Reference(version = "1.0.0")
    private OracleGrasSysDataTransService transService;

    @Reference(version = "1.0.0")
    private OracleRenewalStaffInfoOtherService otherService;

    @Reference(version = "1.0.0")
    private OracleRnServicerInfoService servicerInfoService;

    @Reference(version = "1.0.0")
    private OracleRNPolicyServicerChgRecordService changeService;

    @Reference(version = "1.0.0")
    private OracleLapsePolicy lapsePolicyService;

    @Reference(version = "1.0.0")
    private OraclePolicyProductService policyProductService;

    @Reference(version = "1.0.0")
    private OraclePolicyPremInfoService policyPremInfoService;
    
    @Reference(version = "1.0.0")
    private ElasticSearchService elasticSearchService;
    

    @Autowired
    private PaasHttpRequest paasHttpRequest;

    private LogUtils logUtils = new LogUtils(getClass());



    @Override
    public List<GrasSysTemp> selectByBranchCode(String branchCode) {
        return sysTempService.selectByBranchCode(branchCode);
    }

    /***
     * MethodName:  [queryStaffs]
     * Description:  [分单结果检查查询查询保单服务人员]
     * @param: [branchCode, flag]
     * @return: java.util.List<com.funde.gras.api.domain.StaffInfo>
     */
    @Override
    public PageInfo<StaffInfo> queryStaffs(String branchCode, String channelType, String flag, Integer pageNum, Integer pageSize,String month) {
        Integer total = 0;
        List<StaffInfo> staffs = new ArrayList<>();
        String nowMonth = DateUtil.getPerFirstDayOfDate(month,DateUtil.DATETIME_DEFAULT_FORMAT);
        String nextMonth = DateUtil.getPerLastDayOfDate(month,DateUtil.DATETIME_DEFAULT_FORMAT);
        //recordList 符合条件的全部的流水号
        List<String> recordList = batchRecordService.batchRecordsByBrancodeAndMoth(branchCode, nowMonth, nextMonth);
        List<String> channelTypeList = Arrays.asList(channelType.split(","));
        if (recordList!=null && recordList.size()>0) {
            //已分单业务员 1为前端传输的标记 意为已分单
            if (flag != null && !flag.equals("") && flag.equals(SUCCESSFUL_FLAG)) {
                staffs = sysTempService.queryHavePolicyStaffs(branchCode, channelTypeList, pageNum, pageSize, recordList);
                total = sysTempService.countServicersForPageInfoSuccess(branchCode, channelTypeList, recordList);
                //未分单业务员 2为前端传输的标记 意为未分单
            } else if (flag != null && !flag.equals("") && flag.equals(FAILED_FLAG)) {
                staffs = sysTempService.queryHaveNoPolicyStaffs(branchCode, channelTypeList, pageNum, pageSize, recordList);
                total = sysTempService.countServicersForPageInfoFailed(branchCode, channelTypeList, recordList);
            }
        }
        return new PageInfo<StaffInfo>(pageNum, pageSize, total, staffs);
    }

    /***
     * MethodName:  [queryPolicy]
     * Description:  [方法注释] 
     * @param: [flag, branchCode, channelType, month]
     * @return: java.util.List<com.alibaba.fastjson.JSONObject>
     */
    @Override
    public PageInfo<Map<String,String>> queryPolicy(String flag, String branchCode, String month, Integer pageNum, Integer pageSize, List channelType) {
        String nowMonth = null;
        String nextMonth = null;
        Integer total = 0;
        List<Map<String,String>> resultList = new ArrayList<>();
        if (month != null && !"".equals(month)) {
            nowMonth = DateUtil.getPerFirstDayOfDate(month,DateUtil.DATETIME_DEFAULT_FORMAT);

            nextMonth = DateUtil.getPerLastDayOfDate(month,DateUtil.DATETIME_DEFAULT_FORMAT);
        }
        //recordList 符合条件的全部的流水号
        List<String> recordList = batchRecordService.batchRecordsByBrancodeAndMoth(branchCode, nowMonth, nextMonth);
        //查询不到机构对应的分单记录流水号
        if (recordList == null || recordList.size() == 0) {
//            JSONObject noresultJSON = new JSONObject();
            Map<String,String> noresultMap = new HashMap<>();
            noresultMap.put("result", "没有该机构的分单记录");
            resultList.add(noresultMap);
            return new PageInfo<Map<String,String>>(0, pageSize, 0, resultList);
        } else {
            if (flag.equals(SUCCESSFUL_FLAG)) {
                resultList = sysTempService.querySuccesPolicy(recordList,branchCode, pageNum, pageSize, channelType);
                total = sysTempService.countPolicyForPageInfoSuccess(recordList, branchCode,channelType);
            } else if (flag.equals(FAILED_FLAG)) {
                resultList = sysTempService.queryFailedPolicy(recordList, branchCode, pageNum, pageSize, channelType);
                total = sysTempService.countPolicyForPageInfoFailed(recordList, branchCode, channelType);
            }
        }
        return new PageInfo<Map<String,String>>(pageNum, pageSize, total, resultList);
    }

    /***
     * MethodName:  [getCount]
     * Description:  [方法注释]
     * @param: [branchCode, channelType, month]
     * @return: java.util.Map<java.lang.String,java.lang.Integer>
     */
    @Override
    public Map<String, Integer> getCount(String branchCode, String month, List channelType) {
        Map<String, Integer> resultMap = new HashMap<>();
        String nowMonth = null;
        String nextMonth = null;
        if (month != null && !"".equals(month)) {
//            Map<String, String> allotMonth = DateUtil.allotMonth(month);
            //起始日
//            nowMonth = allotMonth.get("nowMonth");
            nowMonth = DateUtil.getPerFirstDayOfDate(month,DateUtil.DATETIME_DEFAULT_FORMAT);
            //截止日
//            nextMonth = allotMonth.get("nextMonth");
            nextMonth = DateUtil.getPerLastDayOfDate(month,DateUtil.DATETIME_DEFAULT_FORMAT);
        }
        //分单批次编号组
        List<String> batchRecordsList = batchRecordService.batchRecordsByBrancodeAndMoth(branchCode, nowMonth, nextMonth);
        if (batchRecordsList != null && batchRecordsList.size() != 0) {
            failedCount = sysTempService.getCountForFailed(batchRecordsList, channelType);
            succesCount = sysTempService.getCountForSuccess(batchRecordsList, channelType);
        }
        resultMap.put("success", succesCount);
        resultMap.put("failed", failedCount);
        resultMap.put("count", succesCount + failedCount);
        succesCount = 0;
        failedCount = 0;
        return resultMap;
    }

    @Override
    public Map<String, Integer> getCountForManu(String batchSeq) {
        Map<String, Integer> resultMap = new HashMap<>();
        String channelType = null;
        //成功分单总数
        Integer succesCount = sysTempService.getSuccesCount(batchSeq, channelType, null);
        if (succesCount == null) {
            succesCount = 0;
        }
        //失败分单总数
        Integer failedCount = sysTempService.getFailedCount(batchSeq, channelType, null);
        if (succesCount == null) {
            succesCount = 0;
        }
        resultMap.put("success", succesCount);
        resultMap.put("failed", failedCount);
        resultMap.put("count", succesCount + failedCount);
        return resultMap;
    }

    /**
     * 校验保单和服务人员
     * @param condition
     * @param branchCode
     * @param policyList
     * @return
     */
    @Override
    public JSONObject checkPolicAndServicer(String condition,String branchCode, List<JSONObject> policyList){
        List<Map<String,String>> policyFailedList = new ArrayList<>();
        Map<String,String> policyFailedMap = null;
        List<Map<String,String>> policySuccessList = new ArrayList<>();
        Map<String,String> policySuccessMap = null;
        JSONObject resultJson = new JSONObject();
        List<String> policyNoList = new ArrayList<>();
        try {
            //所有能进行分单的保单号
            //传入的EXCEL中错误的保单的信息
            Set<String> failedList = new HashSet<>();
//            List<String> policies = checkPolicyNo(branchCode);

            //以下这个是符合条件的能进行分单的保单号的数组

            //对保单号与续收人员逐一进行核对
            for (JSONObject policyJson : policyList) {
                //保单号
                String policyNo = policyJson.getString("policyNo");
                //服务人员编号
                String servicerNo = policyJson.getString("servicerNo");
                //判断文件不为空
                if (policyList == null || policyList.size() == 0) {
                    resultJson.put("文件不能为空", failedList);
                    return resultJson;
                }
                //产品层的保单信息
                List<PolicyProduct> policyProducts = policyProductService.selectByPolicyNo(policyNo);
                if(policyProducts == null || policyProducts.size() == 0){
                    policyFailedMap = new HashMap<>();
                    policyFailedMap.put("policyNo",policyNo);
                    policyFailedMap.put("servicerNo",servicerNo);
                    policyFailedMap.put("cause","无效的保单号");
                    policyFailedList.add(policyFailedMap);
//                    policyFailedList.add(policyNo+"无效的保单号");
                    failedList.add(policyNo);
                }else {
                    boolean flag = true;
                    //应缴件判定
                    if("1".equals(condition)){
                        //失效件
                    }else if("2".equals(condition)){
                        //失效条件:POS_lapse_policy表中 的lapse_date 到当天不超过两年
                        PosLapsePolicy posLapsePolicy = null;
                        for (PolicyProduct policyProduct : policyProducts) {
                            //保单产品编号
                            Short prodSeq = policyProduct.getProdSeq();
                            posLapsePolicy = lapsePolicyService.selectByPolicyNoAndProSeq(policyNo, prodSeq);
                            if(posLapsePolicy != null){
                                //失效日期
                                Date lapseDate = posLapsePolicy.getLapseDate();
                                //失效原因
                                String lapseReason = policyProduct.getLapseReason();
                                //如果不是符合规则的失效原因,就不予操作
                                boolean contains = MyConstant.LAPSE_POLICIES.contains(lapseReason);
                                if(contains==true){
                                    //日期要在当天到两年内
                                    Date twoYearsLater = DateUtil.getTwoYearsAgo();
                                    //int fromCompare = lapseDate.compareTo(new Date());
                                    int endCompare = lapseDate.compareTo(twoYearsLater);
                                    if(endCompare == -1){
                                        policyFailedMap = new HashMap<>();
                                        policyFailedMap.put("policyNo",policyNo);
                                        policyFailedMap.put("servicerNo",servicerNo);
                                        policyFailedMap.put("cause","保单失效日期不合要求");
                                        policyFailedList.add(policyFailedMap);
//                                        policyFailedList.add(policyNo + "保单失效日期不合要求");
                                        failedList.add(policyNo);

                                        flag = false;
                                    }
                                }else {
                                    failedList.add(policyNo);
                                    policyFailedMap = new HashMap<>();
                                    policyFailedMap.put("policyNo",policyNo);
                                    policyFailedMap.put("servicerNo",servicerNo);
                                    policyFailedMap.put("cause","保单渠道不合要求");
                                    policyFailedList.add(policyFailedMap);
//                                    policyFailedList.add(policyNo + "保单渠道不合要求");

                                    flag = false;
                                }
                                break;
                            }
                        }
                        if(posLapsePolicy == null) {
                            failedList.add(policyNo);
                            policyFailedMap = new HashMap<>();
                            policyFailedMap.put("policyNo",policyNo);
                            policyFailedMap.put("servicerNo",servicerNo);
                            policyFailedMap.put("cause","保单不是规定的失效件");
                            policyFailedList.add(policyFailedMap);
//                                policyFailedList.add(policyNo + "保单不是规定的失效件");

                            flag = false;
                        }
                        //缓交件
                    }else if("3".equals(condition)){
                        for (PolicyProduct policyProduct : policyProducts) {
                            //缓交件除了人员信息外的条件是有效状态的长险
                            String productCode = policyProduct.getProductCode();
                            boolean contains = MyConstant.ALL_KIND_PROD.contains(productCode);
                            if(contains == false){
                                failedList.add(policyNo);
                                policyFailedMap = new HashMap<>();
                                policyFailedMap.put("policyNo",policyNo);
                                policyFailedMap.put("servicerNo",servicerNo);
                                policyFailedMap.put("cause","保单不是规定的缓交件");
                                policyFailedList.add(policyFailedMap);
//                                policyFailedList.add(policyNo + "保单不是规定的缓交件");

                                flag = false;
                            }
                        }
                    }
                    //如果保单校验没有问题,执行人员校验
                    if (flag) {
                        //服务人员资质确认
                        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(servicerNo);
                        //人员不存在
                        if (staffInfo == null || "".equals(staffInfo)) {
                            failedList.add(policyNo);
//                    servicerFailedList.add(servicerNo + "人员不存在");
                            policyFailedMap = new HashMap<>();
                            policyFailedMap.put("policyNo", policyNo);
                            policyFailedMap.put("servicerNo", servicerNo);
                            policyFailedMap.put("cause", "人员不存在");
                            policyFailedList.add(policyFailedMap);
                            failedCount += 1;
                            continue;
                        } else {
                            String empStatusCode = staffInfo.getEmpStatusCode();
                            boolean ifInPosition = empStatusCode.endsWith("01");
                            //人员资质不是在职
                            if (!ifInPosition == true) {
                                failedList.add(policyNo);
//                        servicerFailedList.add(servicerNo + "人员已离职");
                                policyFailedMap = new HashMap<>();
                                policyFailedMap.put("policyNo", policyNo);
                                policyFailedMap.put("servicerNo", servicerNo);
                                policyFailedMap.put("cause", "人员已离职");
                                policyFailedList.add(policyFailedMap);
                                failedCount += 1;
                                continue;
                            }
                        }
                        //保单的渠道
                        String policyChannel = policyService.selectChannelTypeByPolicyNo(policyNo);
                        //人员的渠道
                        String empChannelType = staffInfoService.selectChannelTypeByEmpNp(servicerNo);
                        //保单对应渠道缺失,错误
                        if (policyChannel == null || "".equals(policyChannel)) {
                            failedList.add(policyNo);
//                    policyFailedList.add(policyNo + "无效保单");
                            policyFailedMap = new HashMap<>();
                            policyFailedMap.put("policyNo", policyNo);
                            policyFailedMap.put("servicerNo", servicerNo);
                            policyFailedMap.put("cause", "无效保单");
                            policyFailedList.add(policyFailedMap);
                            failedCount += 1;
                            continue;
                            //保单为个险渠道
                        } else if (MyConstant.CHANNEL_01.equals(policyChannel)) {
                            //在当前机构不为总共的情况下,个险保单必须与续收人员在同一三级机构下。
                            if (!branchCode.equals("86")) {
                                //员工机构
                                String branchCodeByEmpNo = staffInfoService.getBranchCodeByEmpNo(servicerNo);
                                //保单对应机构
                                String branchCodeByPolicyNo = policyService.selectBranchCodeByPolicyNo(policyNo);
                                BranchInfo empBranchInfo = branchInfoService.selectByPrimaryKey(branchCodeByEmpNo);
                                BranchInfo policyBranchInfo = branchInfoService.selectByPrimaryKey(branchCodeByPolicyNo);
                                String empBranchInfoBranchLevel = empBranchInfo.getBranchLevel();
                                String policyBranchInfoBranchLevel = policyBranchInfo.getBranchLevel();
                                //四级机构的处理
                                //员工机构不是三级机构
                                if (!Arrays.asList(MyConstant.BRANCH_LEVEL_LIST).contains(empBranchInfoBranchLevel)) {
                                    Map paramMap = new HashMap();
                                    paramMap.put("branchCode", branchCodeByEmpNo);
                                    paramMap.put("branchLevel", MyConstant.BRANCH_LEVEL_03);
                                    branchCodeByEmpNo = ruleDealService.queryBranchCodeByLevel(paramMap);
                                }
                                //保单所属机构不是三级机构
                                if (!Arrays.asList(MyConstant.BRANCH_LEVEL_LIST).contains(policyBranchInfoBranchLevel)) {
                                    Map paramMap = new HashMap();
                                    paramMap.put("branchCode", branchCodeByPolicyNo);
                                    paramMap.put("branchLevel", MyConstant.BRANCH_LEVEL_03);
                                    branchCodeByPolicyNo = ruleDealService.queryBranchCodeByLevel(paramMap);
                                }
                                //两者不是一个三级机构 不通过
                                if (branchCodeByEmpNo == null || branchCodeByPolicyNo == null || !branchCodeByEmpNo.equals(branchCodeByPolicyNo)) {
//                            servicerFailedList.add(servicerNo + "人员无权操作此保单(跨机构)");
                                    policyFailedMap = new HashMap<>();
                                    policyFailedMap.put("policyNo", policyNo);
                                    policyFailedMap.put("servicerNo", servicerNo);
                                    policyFailedMap.put("cause", "人员无权操作此保单(跨机构)");
                                    policyFailedList.add(policyFailedMap);
                                    failedList.add(policyNo);
                                    continue;
                                } else {
                                    //个险分几种种情况  1.人员也为个险  2.人员不为个险但是 MARKET_FLAG 为Y 取反例即可 3 人员的职务为续收专员、续收主任、个险兼收、银代兼收 这四种
                             
                                        RenewalStaffInfoOther staffInfoOther = otherService.selectByEmpNo(servicerNo);
                                        //人员的职务
                                        String position = staffInfo.getPosition();
                                        //是否个险兼收人员标示
//                                assignAbility(servicerFailedList,failedList, policyNo, staffInfoOther, position, servicerNo);
                                        assignAbility(policyFailedList, failedList, policyNo, staffInfoOther, position, servicerNo);
                                    
                                }
                                //总公司
                            } else {
                                //个险分几种种情况  1.人员也为个险  2.人员不为个险但是 MARKET_FLAG 为Y 取反例即可 3 人员的职务为续收专员、续收主任、个险兼收、银代兼收 这四种
                          
                                    RenewalStaffInfoOther staffInfoOther = otherService.selectByEmpNo(servicerNo);
                                    //人员的职务
                                    String position = staffInfo.getPosition();
                                    //是否个险兼收人员标示
//                            assignAbility(servicerFailedList,failedList, policyNo, staffInfoOther, position, servicerNo);
                                    assignAbility(policyFailedList, failedList, policyNo, staffInfoOther, position, servicerNo);
                                
                            }
                            //银代
                        } else if (MyConstant.CHANNEL_02.equals(policyChannel)) {
                            //不是总公司
                            if (!branchCode.equals("86")) {
                                //银代保单必须与续收人员在同一三级机构下。银代(仅指保单机构为二级机构的保单)
                                String branchCodeByEmpNo = staffInfoService.getBranchCodeByEmpNo(servicerNo);
                                //人员所属的上级
                                String parentBranchByEmpNo = policyService.selectParentBranchByEmpNo(servicerNo);
                                //保单所属上级公司
                                String branchCodeByPolicyNo = policyService.selectBranchCodeByPolicyNo(policyNo);
                                //人员所属上级公司
                                String policyParentBranch = policyService.selectParentBranchByPolicyNo(policyNo);

                                //保单所属机构信息
                                BranchInfo policyBranchInfo = branchInfoService.selectByPrimaryKey(branchCodeByPolicyNo);
                                //保单属于四级机构
                                if (!Arrays.asList(MyConstant.BRANCH_LEVEL_LIST).contains(policyBranchInfo.getBranchLevel())) {
                                    Map paramMap = new HashMap();
                                    paramMap.put("branchCode", branchCodeByPolicyNo);
                                    paramMap.put("branchLevel", MyConstant.BRANCH_LEVEL_03);
                                    branchCodeByPolicyNo = ruleDealService.queryBranchCodeByLevel(paramMap);
                                }
                                //人员所属机构信息
                                BranchInfo empBranchInfo = branchInfoService.selectByPrimaryKey(branchCodeByEmpNo);
                                if (!Arrays.asList(MyConstant.BRANCH_LEVEL_LIST).contains(empBranchInfo.getBranchLevel())) {
                                    Map paramMap = new HashMap();
                                    paramMap.put("branchCode", branchCodeByEmpNo);
                                    paramMap.put("branchLevel", MyConstant.BRANCH_LEVEL_03);
                                    branchCodeByEmpNo = ruleDealService.queryBranchCodeByLevel(paramMap);
                                }
                                //保单上级公司是总公司 本级机构就是二级机构
                                if (policyParentBranch != null && policyParentBranch.length() == 2) {
                                    //人员也是二级机构的人员
                                    if (parentBranchByEmpNo != null && parentBranchByEmpNo.length() == 2) {
                                        //两者不是一样的
                                        if (!branchCodeByEmpNo.equals(branchCodeByPolicyNo)) {
                                            failedList.add(policyNo);
//                                    servicerFailedList.add(servicerNo + "人员无权操作此保单(跨机构)");
                                            policyFailedMap = new HashMap<>();
                                            policyFailedMap.put("policyNo", policyNo);
                                            policyFailedMap.put("servicerNo", servicerNo);
                                            policyFailedMap.put("cause", "人员无权操作此保单(跨机构)");
                                            policyFailedList.add(policyFailedMap);
                                            continue;
                                        }
                                        //人员的上级机构就是二级机构
                                    } else if (parentBranchByEmpNo != null && parentBranchByEmpNo.length() == 4) {
                                        if (!branchCodeByEmpNo.equals(parentBranchByEmpNo)) {
                                            failedList.add(policyNo);
//                                    servicerFailedList.add(servicerNo + "人员无权操作此保单(跨机构)");
                                            policyFailedMap = new HashMap<>();
                                            policyFailedMap.put("policyNo", policyNo);
                                            policyFailedMap.put("servicerNo", servicerNo);
                                            policyFailedMap.put("cause", "人员无权操作此保单(跨机构)");
                                            policyFailedList.add(policyFailedMap);
                                            continue;
                                        }
                                    }
                                    //三级机构保单
                                } else {
                                    //两者不是一个机构 不通过
                                    if (branchCodeByEmpNo == null || branchCodeByPolicyNo == null || !branchCodeByEmpNo.equals(branchCodeByPolicyNo)) {
                                        failedList.add(policyNo);
//                                servicerFailedList.add(servicerNo+ "人员无权操作此保单(跨机构)");
                                        policyFailedMap = new HashMap<>();
                                        policyFailedMap.put("policyNo", policyNo);
                                        policyFailedMap.put("servicerNo", servicerNo);
                                        policyFailedMap.put("cause", "人员无权操作此保单(跨机构)");
                                        policyFailedList.add(policyFailedMap);
                                        continue;
                                    } else {
                                        verifyBankChannel(policyFailedList, failedList, policyNo, servicerNo, staffInfo, empChannelType);
                                    }
                                }
                                //总公司
                            } else {
                                verifyBankChannel(policyFailedList, failedList, policyNo, servicerNo, staffInfo, empChannelType);
                            }
                            //经代
                        } else if (MyConstant.CHANNEL_03.equals(policyChannel)) {
                            //不是总公司
                            if (!branchCode.equals("86")) {
                                //经代必须与续收人员在同一二级机构下。
                                String serviceBranch = policyService.selectParentBranchByEmpNo(servicerNo);
                                //服务人员所属机构信息
                                BranchInfo servicerBranchInfo = branchInfoService.selectByPrimaryKey(serviceBranch);
                                //保单机构
                                String policyBranch = policyService.selectParentBranchByPolicyNo(policyNo);
                                BranchInfo policyBranchInfo = branchInfoService.selectByPrimaryKey(policyBranch);
                                //保单属于四级机构
                                if (!Arrays.asList(MyConstant.BRANCH_LEVEL_LIST).contains(policyBranchInfo.getBranchLevel())) {
                                    Map paramMap = new HashMap();
                                    paramMap.put("branchCode", policyBranch);
                                    paramMap.put("branchLevel", MyConstant.BRANCH_LEVEL_03);
                                    policyBranch = ruleDealService.queryBranchCodeByLevel(paramMap);
                                }
                                //人员所属机构信息
                                if (!Arrays.asList(MyConstant.BRANCH_LEVEL_LIST).contains(servicerBranchInfo.getBranchLevel())) {
                                    Map paramMap = new HashMap();
                                    paramMap.put("branchCode", serviceBranch);
                                    paramMap.put("branchLevel", MyConstant.BRANCH_LEVEL_03);
                                    serviceBranch = ruleDealService.queryBranchCodeByLevel(paramMap);
                                }
                                //上级公司是总公司 当前公司就是二级公司
                                if (policyBranch.length() == 2) {
                                    policyBranch = policyService.selectBranchCodeByPolicyNo(policyNo);
                                }
                                //两者的二级公司不一样
                                if (serviceBranch == null || policyBranch == null || !serviceBranch.equals(policyBranch)) {
                                    failedList.add(policyNo);
//                            servicerFailedList.add(servicerNo + "人员无权操作此保单(跨机构)");
                                    policyFailedMap = new HashMap<>();
                                    policyFailedMap.put("policyNo", policyNo);
                                    policyFailedMap.put("servicerNo", servicerNo);
                                    policyFailedMap.put("cause", "人员无权操作此保单(跨机构)");
                                    policyFailedList.add(policyFailedMap);
                                } else {
                                    veryfyEcoChannel(policyFailedList, failedList, policyNo, servicerNo, staffInfo, empChannelType);
                                }
                                //总公司无视分公司权限
                            } else {
                                veryfyEcoChannel(policyFailedList, failedList, policyNo, servicerNo, staffInfo, empChannelType);
                            }

                            //收展
                        } else if (MyConstant.CHANNEL_07.equals(policyChannel)) {
                            if (!branchCode.equals("86")) {
                                //收展保单必须与续收人员在同一三级机构下。
                                String branchCodeByEmpNo = staffInfoService.getBranchCodeByEmpNo(servicerNo);
                                String branchCodeByPolicyNo = policyService.selectBranchCodeByPolicyNo(policyNo);
                                //人员机构信息
                                BranchInfo empBranchInfo = branchInfoService.selectByPrimaryKey(branchCodeByEmpNo);
                                //保单机构信息
                                BranchInfo policyBranchInfo = branchInfoService.selectByPrimaryKey(branchCodeByPolicyNo);
                                //保单属于四级机构
                                if (!Arrays.asList(MyConstant.BRANCH_LEVEL_LIST).contains(policyBranchInfo.getBranchLevel())) {
                                    Map paramMap = new HashMap();
                                    paramMap.put("branchCode", branchCodeByPolicyNo);
                                    paramMap.put("branchLevel", MyConstant.BRANCH_LEVEL_03);
                                    branchCodeByPolicyNo = ruleDealService.queryBranchCodeByLevel(paramMap);
                                }
                                //人员所属机构信息
                                if (!Arrays.asList(MyConstant.BRANCH_LEVEL_LIST).contains(empBranchInfo.getBranchLevel())) {
                                    Map paramMap = new HashMap();
                                    paramMap.put("branchCode", empBranchInfo);
                                    paramMap.put("branchLevel", MyConstant.BRANCH_LEVEL_03);
                                    branchCodeByEmpNo = ruleDealService.queryBranchCodeByLevel(paramMap);
                                }
                                //收展保单如保单业务员在职,则不允许调整给其它人。
                                RNPolicyServiceInfo rnPolicyServiceInfo = servicerInfoService.selectByPolicyNo(policyNo);
                                String agentNo = rnPolicyServiceInfo.getAgentNo();
                                StaffInfo staff = staffInfoService.selectByPrimaryKey(agentNo);
                                //在职
                                if (staff!=null && staff.getEmpStatusCode().endsWith("01")) {
                                    //两者不同
                                    if (!agentNo.equals(servicerNo)) {
                                        failedList.add(policyNo);
//                                servicerFailedList.add(servicerNo+ "人员无权操作此保单(收展服务人员在职,不能调整)");
                                        policyFailedMap = new HashMap<>();
                                        policyFailedMap.put("policyNo", policyNo);
                                        policyFailedMap.put("servicerNo", servicerNo);
                                        policyFailedMap.put("cause", "人员无权操作此保单(收展服务人员在职,不能调整)");
                                        policyFailedList.add(policyFailedMap);
                                    }
                                }
                                //两者不是一个机构 不通过
                                if (branchCodeByEmpNo == null || branchCodeByPolicyNo == null || !branchCodeByEmpNo.equals(branchCodeByPolicyNo)) {
                                    failedList.add(policyNo);
//                            servicerFailedList.add(servicerNo+ "人员无权操作此保单(跨机构)");
                                    policyFailedMap = new HashMap<>();
                                    policyFailedMap.put("policyNo", policyNo);
                                    policyFailedMap.put("servicerNo", servicerNo);
                                    policyFailedMap.put("cause", "人员无权操作此保单(跨机构)");
                                    policyFailedList.add(policyFailedMap);
                                } else {
                                    verifyShouzhanChannel(policyFailedList, failedList, policyNo, servicerNo, staffInfo, empChannelType);
                                }
                                //总公司
                            } else {
                                //收展保单如保单业务员在职,则不允许调整给其它人。
                                RNPolicyServiceInfo rnPolicyServiceInfo = servicerInfoService.selectByPolicyNo(policyNo);
                                String agentNo = rnPolicyServiceInfo.getAgentNo();
                                StaffInfo staff = staffInfoService.selectByPrimaryKey(agentNo);
                                //在职
                                if (staff!=null && staff.getEmpStatusCode().endsWith("01")) {
                                    //两者不同
                                    if (!agentNo.equals(servicerNo)) {
                                        failedList.add(policyNo);
//                                servicerFailedList.add(servicerNo+ "人员无权操作此保单(收展服务人员在职,不能调整)");
                                        policyFailedMap = new HashMap<>();
                                        policyFailedMap.put("policyNo", policyNo);
                                        policyFailedMap.put("servicerNo", servicerNo);
                                        policyFailedMap.put("cause", "人员无权操作此保单(收展服务人员在职,不能调整)");
                                        policyFailedList.add(policyFailedMap);
                                    }
                                }
                                verifyShouzhanChannel(policyFailedList, failedList, policyNo, servicerNo, staffInfo, empChannelType);
                            }

                        }
                    }
                }
                policyNoList.add(policyNo);
            }
            policyNoList.removeAll(failedList);

            //处理保单人员离职交接
            policySuccessList=quitAssign(policyNoList,policyList,policyFailedList,failedList);
            policyNoList.removeAll(failedList);


            resultJson.put("policyFailed", policyFailedList);
            resultJson.put("policySuccess",policySuccessList);
            resultJson.put("failedPolicyNo",failedList);
            resultJson.put("successPolicyNo",policyNoList);
            resultJson.put("failed", failedList.size());
            resultJson.put("total", policyList.size());
            resultJson.put("success", policyList.size() - failedList.size());

        }catch (Exception e){
            logUtils.error(e);
        }
        return resultJson;
    }

    /***
     * MethodName:  [adjustFailedPolicy]
     * Description:  根据传入的excel进行保单人员指定
     * @param: [policyList]
     * @return: java.util.Map<java.lang.String,java.lang.Integer>
     */
    @Override
    public JSONObject adjustFailedPolicy(String condition,String branchCode, List<JSONObject> policyList,String user) {

        JSONObject resultJson = new JSONObject();
        try {
            //校验保单和人员
            resultJson = checkPolicAndServicer(condition,branchCode,policyList);
            //校验成功的保单将存到gras_sys_temp表中
            if (resultJson.containsKey("successPolicyNo")){
                //获取校验成功保单号
                List<String> policyNoList = (List<String> )resultJson.get("successPolicyNo");
                //往成功表中添加这些数据
                List<GrasSysTemp> sysTempList = new ArrayList<>();
                List<Map<String,String>> successList = new ArrayList<>();
                //在分单失败表中删除调传入的保单号
                if (policyNoList != null && policyNoList.size() != 0) {
//                    String batchSeq = NumberUtil.random10();
//                    String batchCode = NumberUtil.random4();
                    //向批次申请中添加一个信息
//                GrasAssignBatchRecord batchRecord = new GrasAssignBatchRecord(batchSeq,"N",NumberUtil.random10(),MyConstant.SYS_USER,new Date(),MyConstant.SYS_USER,new Date());
                    for (String policyNo : policyNoList) {
                        //封装参数用于数据库操作
                        //传入的值并不会很多(最多1000个)
                        String servicerNo = "";
                        for (JSONObject inJSON : policyList) {
                            String inPolicyNo = inJSON.getString("policyNo");
                            //找到对应的服务人员
                            if (inPolicyNo != null && !"".equals(inPolicyNo) && inPolicyNo.equals(policyNo)) {
                                servicerNo = inJSON.getString("servicerNo");
                                Map<String,String> itemSuccessMap = new HashMap<>();
                                itemSuccessMap.put("policyNo",policyNo);
                                itemSuccessMap.put("servicerNo",servicerNo);
                                successList.add(itemSuccessMap);
                                break;
                            }
                        }
                        //根据保单号查询保单缴费信息,获得应缴月
                        PolicyPremInfo policyPremInfo = policyPremInfoService.selectByPolicyNo(policyNo);
                        if (policyPremInfo != null) {
                            String dateMonth = policyPremInfo.getPremDueDate();
                            dateMonth = dateMonth.substring(0,7);
                            //根据机构号和应缴月查询分单批次申请,获得流水号
                            GrasAssignBatchRecord grasAssignBatchRecord = batchRecordService.selectBatchRecord(branchCode, dateMonth);
                            if (grasAssignBatchRecord != null) {
                                GrasSysTemp temp = new GrasSysTemp(policyNo, branchCode, servicerNo, MyConstant.ASSIGN_RULE_11, grasAssignBatchRecord.getBatchSeq(),user);
                                temp.setServicerNo(servicerNo);
                                sysTempList.add(temp);
                            }
                        }
                    }
                    //往成功表中添加这些数据 并向批次表中添加数据
                    try {
                        if (sysTempList != null && sysTempList.size() != 0) {
//                        batchRecord.setBranchCode(branchCode);
//                        Date dueMonthDate = DateUtil.getDateFormat(DateUtil.getPerFirstDayOfDate(dueMonth,DateUtil.DATE_DEFAULT_FORMAT));
//                        batchRecord.setDueMonth(dueMonthDate);
//                        batchRecord.setBatchCode(NumberUtil.random4());
//                        batchRecordService.insertBatchRecord(batchRecord);
                            for (List mergeSuccessList : subListPolicyList(sysTempList)) {
                                sysTempService.insertOrUpdateBatch(mergeSuccessList);
                            }
                        }
                        //在失败表中删除这些数据
                        if (policyNoList != null && policyNoList.size() != 0) {
                            for (List listForDelete : subListPolicyList(policyNoList)) {
//                            failedRecordService.deleteList(listForDelete);
                                failedRecordService.updateList("N",listForDelete);
                            }
                        }
                    } catch (Exception e) {
                        resultJson.put("内部错误", e.getMessage());
                        return resultJson;
                    }
                }

                failedCount = 0;
                succesCount = 0;
            }

            return resultJson;
        } catch (Exception e) {
            logUtils.error(e);
            resultJson.put("错误信息:", e.getMessage());
            failedCount = 0;
            succesCount = 0;
            return resultJson;
        }

    }



    /**
     * MethodName:  quitAssign
     * Description:  [保单离职交接规则]
     * @param policyNoList
     * @param policyList
     * @return  String
     *
     * @author  Mamba
     * @date  2019年1月8日 下午2:26:28
     */
    private List<Map<String, String>> quitAssign(List<String> policyNoList, List<JSONObject> policyList, List<Map<String,String>> policyFailedList,Set<String> failedList)
    {
        //key:应缴日(1812)年份加月份   value{现服务人员代码,服务人员代码}
        Map<String, Map> map = new HashMap<String, Map>();
        //{现服务人员代码,服务人员代码}
        Map<String, String> policyMap = new HashMap<String, String>();
        //最后符合条件的保单信息
        List<Map<String, String>> policySuccessList = new ArrayList<>();
        Map<String, String> policySuccessMap = null;
        Date nowDate = new Date();
        //获取当前年份
        int nowYear = DateUtil.getYear(nowDate);
        int nowMonth = DateUtil.getMonth(nowDate);
        Map<String,String> paramMap=new HashMap<String,String>();
      //错误信息
        Map<String,String> policyFailedMap = null;

        for (String item : policyNoList)
        {
            for (JSONObject policyJson : policyList)
            {
                String policyNo = policyJson.getString("policyNo");
                String servicerNo = policyJson.getString("servicerNo");
                try
                {
                    if (item.equals(policyNo))
                    {
                        policySuccessMap = new HashMap<>();
                        /**
                         * 处理离职交接规则
                         */
                        //根据保单号从数据库取现服务人员
                        RNPolicyServiceInfo rnPolicyServiceInfo = servicerInfoService.selectByPolicyNo(policyNo);
                        StaffInfo staffInfo = null;
                        if (rnPolicyServiceInfo != null)
                        {
                            staffInfo = staffInfoService.selectByPrimaryKey(rnPolicyServiceInfo.getServiceNo());
                        }
                        int month = 0;
                        int year = 0;
                        if (staffInfo != null && staffInfo.getLeaveDate() != null)
                        {
                            Date leaveDate = DateUtil.formatDate(staffInfo.getLeaveDate(), "yyyy-MM-dd");
                            month = DateUtil.getMonth(leaveDate);
                            year = DateUtil.getYear(leaveDate);
                        }
                        //1:先判断该保单的现服务人员是否在当月或者上月离职    人员离职时间:STAFF_INFO.LEAVE_DATE
                        if (quitTime(nowYear, nowMonth, year, month))
                        {

                            //3.离职人员名下未收件交接遵循“应缴月为同一个月份的保单只能交接给同一个人,不允许分别交接给多个人员”;未收件:保单缴费状态为1的时候为未收件,即POLICY_PREM_INFO.PREM_STATUS=1
                            //例如:A人员当月离职,他12月名下有3笔保单,分别为1,2,3,分别会出现两种情况,1:A人员应缴日在12月的保单从未有过交接记录     2:A人员应缴日在12月的保单存在交接记录
                            //情况1:上传文件中,把1,2,3分别分配给B,C,D,文件格式如下:

                            //数据库获取保单应缴日,得到应缴月
                            PolicyPremInfo policyPremInfo = premInfoService.selectByPolicyNo(policyNo);
                            Date premDueDate = DateUtil.formatDate(policyPremInfo.getPremDueDate(), "yyyy-MM-dd");
                            int premDueMonth = DateUtil.getMonth(premDueDate);
                            int premDueYear = DateUtil.getYear(premDueDate);
                            //校验考核期
                            if(checkAssessmentPeriod(premDueYear,premDueMonth)){
                                //那么这种情况,1先分给了B,那根据规则同一月保单只能分配给同一人,那么2,3保单就只能B
                                //校验如下,校验保单交出服务人员是否和该保单现服务人员相同,若不相同则没有发生保单离职交接记录
                                //注:数据库获取保单服务人员交接记录表,该保单最近一次交接记录,获取交出服务人员字段   RN_POLICY_SERVICER_CHG_RECORD.EARLIER_AGENT
                                String startMonths = DateUtil.getPerFirstDayOfDate(policyPremInfo.getPremDueDate(), DateUtil.DATETIME_DEFAULT_FORMAT);
                                String endMonth = DateUtil.getPerLastDayOfDate(policyPremInfo.getPremDueDate(), DateUtil.DATETIME_DEFAULT_FORMAT);
    
                                paramMap.put("sreceiveNo", rnPolicyServiceInfo.getServiceNo());
                                paramMap.put("startMonths", startMonths);
                                paramMap.put("endMonth", endMonth);
                                RNPolicyServicerChgRecord record = changeService.queryLastTimeServicerChg(paramMap);
                                /**保       原         接收
                                 * p1  H1  H2
                                 * p2  H1  H3
                                 */
    
                                //交出服务人员代码
                                String outSer = null;
                                //接收服务人员代码
                                String receiveSer = null;
    
                                //现服务人员代码
                                String nowServicerNo = rnPolicyServiceInfo.getServiceNo();
    
                                if (record == null
                                        || DateUtil.compareToDate(staffInfo.getLeaveDate(),
                                        DateUtil.getDateFormat(record.getChangeDate())) != -1)
                                {
    
                                    //情况一:没有记录,或者离职时间大于调整时间(离职之前交接的保单)      小于根据应缴月从map中取值(应缴月值应该每次去查保单的应缴日),从值中取该保单号的现服务人员,
    
                                    Map<String, String> m = map.get(String.valueOf(premDueYear)
                                            + String.valueOf(premDueMonth));
                                    //现服务人员代码
                                    String nowServicer = null;
                                    //准备交接的服务人员代码
                                    String servicer = null;
                                    /**
                                     * map  H1:H2
                                     */
                                    if(m!=null){
                                        for (Map.Entry<String, String> s : m.entrySet())
                                        {
                                            if (s.getKey().equals(nowServicerNo))//H1==1
                                            {
                                                nowServicer = s.getKey();
                                                servicer = s.getValue();//H2
                                            }
    
                                        }
                                    }
                                    //情况1:如果没值,那就符合条件
                                    //情况2:如果有值,根据同月只能分配给同一人员原则,比较收服务人员与上个接收服务人员是否相同为同一人
                                    if (nowServicer != null && !servicerNo.equals(servicer))
                                    {
                                            failedList.add(policyNo);
                                            policyFailedMap = new HashMap<>();
                                            policyFailedMap.put("policyNo", policyNo);
                                            policyFailedMap.put("servicerNo", servicerNo);
                                            policyFailedMap.put("cause", "离职人员下同一应缴月下的保单只能分配给一个人");
                                            policyFailedList.add(policyFailedMap);
                                            break;
                                    }
    
                                }
                                else
                                {
                                    
                                      //情况二:若保单交出服务人员和该保单现服务人员相同,则说明之前有发生过保单离职交接,那根据一个月中只能分给同一个服务人员原则,那只能分配给接收服务人员
                                      //处理脏数据 NextAgent离职      --通过,可以调整      NextAgent 未离职   --保持原服务人员,不可以调整
                                      //如果离职后调整的服务人员也处于离职状态的话,则允许此次操作
                                      StaffInfo staffInfo1 = staffInfoService.selectByPrimaryKey(record.getNextAgent());
                                      //若是离职,则不可调整 break
                                      if(staffInfo1 != null && staffInfo1.getLeaveDate() != null){
                                          failedList.add(policyNo);
                                         
                                          policyFailedMap = new HashMap<>();
                                          policyFailedMap.put("policyNo", policyNo);
                                          policyFailedMap.put("servicerNo", servicerNo);
                                          policyFailedMap.put("cause", "离职人员下同一应缴月下的保单只能分配给一个人");
                                          policyFailedList.add(policyFailedMap);
                                          break;
                                      }
                                }
                                policyMap.put(nowServicerNo, servicerNo);
                                map.put(String.valueOf(premDueYear) + String.valueOf(premDueMonth), policyMap);
                            }  
                        }
                            
                            
                        /**
                         * end
                         */

                        policySuccessMap.put("policyNo", policyNo);
                        policySuccessMap.put("servicerNo", servicerNo);
                        policySuccessList.add(policySuccessMap);
                        break;
                    }
                }

                catch (Exception e)
                {
                    e.printStackTrace();
                    policySuccessMap.put("policyNo", policyNo);
                    policySuccessMap.put("servicerNo", servicerNo);
                    policySuccessList.add(policySuccessMap);
                    break;
                }
            }
        }
        return policySuccessList;

    }
    /**
     * 
     * MethodName:  checkAssessmentPeriod
     * Description:  [校验考核期]  
     *@param premDueYear
     *@param premDueMonth
     *@return  boolean
     * 
     * @author  Mamba
     * @date  2019年5月5日 下午5:33:23
     */
    private boolean checkAssessmentPeriod(int premDueYear, int premDueMonth)
    {
        //例如:当前5月份操作离职交接时,只对应缴月在3月、4月、5月的保单进行规则校验
        Date nowDate=DateUtil.getNowDate();
        int nowYear=DateUtil.getYear(nowDate);
        int nowMonth=DateUtil.getMonth(nowDate);
        
        //最小月
        Date earliestDate=DateUtil.getDateMonthFormat(DateUtil.getDateMonthFormat(DateUtil.getFirstMonth(3)));
        int earliestYear=DateUtil.getYear(earliestDate);
        int earliestMonth=DateUtil.getMonth(earliestDate);
        
        //同年 当前:2019-4  最小月:2019-1 应缴月:2019-3
        if(earliestYear==nowYear){
            //同年 : 小于等于当前月   &&  大于最小月 --3月小于5月,大于2月
            if(nowYear==premDueYear && premDueMonth<=nowMonth && premDueMonth>earliestMonth){
                return true;
            }
        }
        //不同年
        if(earliestYear<nowYear){
            //当前:2019-3  最小月:2018-12  应缴月:2019-3
            //应缴月与当前时间同年  && 应缴月小于等于当前月
            if(nowYear==premDueYear && premDueMonth<=nowMonth){
                return true;
            }
            //应缴月与最小月同年  && 应缴月大于最小月
            if(nowYear==earliestYear && premDueMonth>earliestMonth){
                return true;
            }
        }
        return false;
    }

    private boolean quitTime(int nowYear, int nowMonth, int year, int month)
    {
        //同年--当月&上月
        if (nowYear == year && (nowMonth == month || nowMonth == (month - 1)))
        {
            return true;
        }

        //去年  ---上月
        if ((nowYear - year) == 1 && month == 12)
        {
            return true;
        }

        return false;
    }


    private void verifyShouzhanChannel(List<Map<String,String>> policyFailedList,Set<String> failedList, String policyNo, String servicerNo, StaffInfo staffInfo, String empChannelType) {
        //收展分几种种情况  1.人员也为收展  2.人员不为收展但是 shouzhanflag? 为Y 取反例即可 3 人员的职务为个险收展专员、银代收展专员、收展主任、个险兼收、银代兼收 这四种
        if (!MyConstant.CHANNEL_07.equals(empChannelType)) {
            RenewalStaffInfoOther staffInfoOther = otherService.selectByEmpNo(servicerNo);
            //人员的职务
            String position = staffInfo.getPosition();
            assignAbility(policyFailedList,failedList, policyNo, staffInfoOther, position, servicerNo);
        }
    }

    private void veryfyEcoChannel(List<Map<String,String>> policyFailedList,Set<String> failedList, String policyNo, String servicerNo, StaffInfo staffInfo, String empChannelType) {
        Map<String,String> policyFailedMap = new HashMap<>();
        policyFailedMap.put("policyNo",policyNo);
        policyFailedMap.put("servicerNo",servicerNo);
        policyFailedMap.put("cause","人员无权操作此保单(不能负责该渠道)");

        //经代分几种种情况  1.人员也为经代  2.人员不为经代但是 agentFlag 为Y 取反例即可 3 人员的职务为银代督导、续收主任、个险兼收、银代兼收 这四种
        if (!MyConstant.CHANNEL_03.equals(empChannelType)) {
            RenewalStaffInfoOther staffInfoOther = otherService.selectByEmpNo(servicerNo);
            //人员的职务
            String position = staffInfo.getPosition();
            if (staffInfoOther != null) {
                //个险兼收人员标示
                String marketFlag = staffInfoOther.getMarketFlag();
                //经代兼收标示
                String agentFlag = staffInfoOther.getAgentFlag();
                //银代兼收标示
                String bankFlag = staffInfoOther.getBankFlag();
                //不是兼收人员
                //续收专员、续收主任、个险兼收、银代兼收 这四种都可以分经代的单子
                if ((!"Y".equals(marketFlag)) && (!"Y".equals(bankFlag)) && (!"Y".equals(agentFlag))) {
                    if (position != null && !"".equals(position)) {
                        //续收专员、银代收展专员、续收主任
                        if (!MyConstant.BANK_AGENT_SERVICER.equals(position) && !MyConstant.PERSONAL_INSURANCE_SERVICER.equals(position) && !MyConstant.CD_DIRECTOR.equals(position)) {
                            failedList.add(policyNo);
//                            servicerFailedList.add(servicerNo+ "人员无权操作此保单(不能负责该渠道)");
                            policyFailedList.add(policyFailedMap);
                            failedCount += 1;
                        }
                    } else {
                        failedList.add(policyNo);
//                        servicerFailedList.add(servicerNo+ "人员无权操作此保单(不能负责该渠道)");
                        policyFailedList.add(policyFailedMap);
                        failedCount += 1;
                    }
                }
            } else {
                failedList.add(policyNo);
//                servicerFailedList.add(servicerNo+ "人员无权操作此保单(不能负责该渠道)");
                policyFailedList.add(policyFailedMap);
                failedCount += 1;
            }
        }
    }

    private void verifyBankChannel(List<Map<String,String>> policyFailedList,Set<String> failedList, String policyNo, String servicerNo, StaffInfo staffInfo, String empChannelType) {
        Map<String,String> policyFailedMap = new HashMap<>();
        policyFailedMap.put("policyNo",policyNo);
        policyFailedMap.put("servicerNo",servicerNo);
        policyFailedMap.put("cause","人员无权操作此保单(不能负责该渠道)");
        //银代分几种种情况  1.人员也为银代  2.人员不为银代但是 bank——flag 为Y 取反例即可 3 人员的职务为银代督导、续收主任、个险兼收、银代兼收 这四种
        if (!MyConstant.CHANNEL_02.equals(empChannelType)) {
            RenewalStaffInfoOther staffInfoOther = otherService.selectByEmpNo(servicerNo);
            //人员的职务
            String position = staffInfo.getPosition();
            //是否银代兼收人员标示
            if (staffInfoOther != null) {
                String marketFlag = staffInfoOther.getMarketFlag();
                //银代兼收标示
                String bankFlag = staffInfoOther.getBankFlag();
                //不是兼收人员
                if ((!"Y".equals(marketFlag)) && (!"Y".equals(bankFlag))) {
                    if (position != null && !"".equals(position)) {
                        //银代督导、续收主任、个险兼收、银代兼收 这四种都可以分银代的单子
                        //续收专员、银代收展专员
                        if (!MyConstant.BANK_AGENT_SERVICER.equals(position) && !MyConstant.CD_DIRECTOR.equals(position)) {
                            failedList.add(policyNo);
//                            servicerFailedList.add(servicerNo+ "人员无权操作此保单(不能负责该渠道)");

                            policyFailedList.add(policyFailedMap);
                            failedCount += 1;
                        }
                    } else {
                        failedList.add(policyNo);
//                        servicerFailedList.add(servicerNo + "人员无权操作此保单(不能负责该渠道)");
                        policyFailedList.add(policyFailedMap);
                        failedCount += 1;
                    }
                }
            } else {
                failedList.add(policyNo);
//                servicerFailedList.add(servicerNo);
                policyFailedList.add(policyFailedMap);
                failedCount += 1;
            }
        }
    }

    private void assignAbility(List<Map<String,String>> policyFailedList,Set<String> failedList, String policyNo, RenewalStaffInfoOther staffInfoOther, String position, String servicerNo) {
        Map<String,String> policyFailedMap = new HashMap<>();
        policyFailedMap.put("policyNo",policyNo);
        policyFailedMap.put("servicerNo",servicerNo);
        policyFailedMap.put("cause","人员无权操作此保单(不能负责该渠道)");
        if (staffInfoOther != null) {
            //个险兼收人员标示
            String marketFlag = staffInfoOther.getMarketFlag();
            //银代兼收标示
            String bankFlag = staffInfoOther.getBankFlag();
            //不是兼收人员
            //个险收展专员、收展主任、个险兼收、银代兼收 这四种都可以分收展的单子
            if ((!"Y".equals(marketFlag)) && (!"Y".equals(bankFlag))) {
                if (position != null && !"".equals(position)) {
                    //续收专员、银代收展专员、续收主任
                    if (!MyConstant.PERSONAL_INSURANCE_SERVICER.equals(position) && !MyConstant.CD_DIRECTOR.equals(position)) {
                        failedList.add(policyNo);
//                        servicerFailedList.add(servicerNo + "人员无权操作此保单(不能负责该渠道)");

                        policyFailedList.add(policyFailedMap);
                        failedCount += 1;
                    }
                } else {
                    failedList.add(policyNo);
//                    servicerFailedList.add(servicerNo+ "人员无权操作此保单(不能负责该渠道)");
                    policyFailedList.add(policyFailedMap);
                    failedCount += 1;
                }
            }
        } else {
            failedList.add(policyNo);
//            servicerFailedList.add(servicerNo + "人员无权操作此保单(不能负责该渠道)");
            policyFailedList.add(policyFailedMap);
            failedCount += 1;
        }
    }

    /**
     * 根据保单号查询到能服务该保单的人员
     *
     * @param policyNo
     * @return
     */
    @Override
    public List<StaffInfo> getEmpsByBranchCodeAndchannelType(String policyNo) {
        //保单所属机构号
        String branchCode = policyService.selectBranchCodeByPolicyNo(policyNo);
        //保单渠道
        String channelType = policyService.selectChannelTypeByPolicyNo(policyNo);
        //结果集
        List resultList = new ArrayList();
        //机构信息
        BranchInfo branchInfo = branchInfoService.selectByPrimaryKey(branchCode);
        //机构级别
        String branchLevel = branchInfo.getBranchLevel();
        //如果保单是四级机构,那就找他对应的三级机构
        if (!Arrays.asList(MyConstant.BRANCH_LEVEL_LIST).contains(branchLevel)) {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("branchCode", branchCode);
            paramMap.put("branchLevel", MyConstant.BRANCH_LEVEL_03);
            branchCode = ruleDealService.queryBranchCodeByLevel(paramMap);
        }
        //保单对应的机构下所有符合条件的人员
        List<StaffInfo> empsByBranchCodeAndchannelType = staffInfoService.getEmpsByBranchCodeAndchannelType(branchCode);
        for (StaffInfo staffInfo : empsByBranchCodeAndchannelType) {
            String empNo = staffInfo.getEmpNo();
            //人员能服务的渠道
            Set<String> checkChannelTypes = checkChannelTypes(empNo);
            //人员服务的渠道包含了保单的渠道
            if (checkChannelTypes.contains(channelType)) {
                resultList.add(staffInfo);
            }
        }
        return resultList;
    }

    /**
     * 回写核心数据库的操作
     * @param user
     * @param policyServicerList
     * @param assginRule
     * @return
     */
    @Override
    public JSONObject resultBackRN(String user,List<Map<String,String>> policyServicerList,String assginRule){
        JSONObject resultJson = new JSONObject();
        String transFlag = "传输异常";
        String reason = "";
        List<RNPolicyServicerChgRecord> RNPSCRList=new ArrayList<RNPolicyServicerChgRecord>();
        try{
            List<String> policys = new ArrayList<>();
            JSONArray paramArray = new JSONArray();
            for (Map<String, String> item : policyServicerList) {
                String policyNo = item.get("policyNo");
                String servicerNo = item.get("servicerNo");
                //用于存放给核心系统传输数据的
                JSONObject dataJSON = new JSONObject(){{
                    put("policyNo", policyNo);
                    put("servicerNo", servicerNo);
                    put("orphanMark", "0");
                    put("assignRule", assginRule);
                    put("lastAssignUser", user);
                    put("lastAssignDate", DateUtil.getDateTimeFormat(new Date()));
                }};
                //保单交接记录
                setPolicyServicerChgRecord(policyNo,servicerNo,assginRule,user,RNPSCRList);
                paramArray.add(dataJSON);
                policys.add(policyNo);
            }
            //向核心系统传数据
            logUtils.info("核心系统回写...时间:" + new Date() + "向核心系统传入的参数为:" + paramArray);
            //此处要求是按3000条进行传输一次
            List<JSONArray> jsonArrays = submit3000Datas(paramArray, 3000);
            //传输失败的保单数组
            List<String> failedPolicyNos = new ArrayList<>();
            //传输记录 用于记录
            List<GrasSysDataTrans> transList = new ArrayList<>();
            //分批传输
            for (JSONArray pageDatas : jsonArrays) {
                //每次传输的结果
                JSONObject everyTimeSyncResult = AllotResultsBack.syncPolicyRule(pageDatas);
                logUtils.info(new Date() + "本次回写结果:" + everyTimeSyncResult);
                //传输成功与否的标示
                String flag = everyTimeSyncResult.getString("flag");
                //接口返回的传输失败的保单
                JSONArray failedPolicys = everyTimeSyncResult.getJSONArray("policyNos");
                if("0".equals(flag)){
                    //失败保单处理
                    if (failedPolicys != null && failedPolicys.size() != 0) {
                        for (int i = 0; i < failedPolicys.size(); i++) {
                            //失败的保单,key为policyNo,value为失败的原因
                            JSONObject failedPolicy = failedPolicys.getJSONObject(i);
                            for (String policyNo : failedPolicy.keySet()) {
                                String failedReason = failedPolicy.getString(policyNo);
                                failedPolicyNos.add(policyNo);
                                GrasSysDataTrans transData = new GrasSysDataTrans("GRAS_SYS_TEMP",policyNo,"N","Y",failedReason,user,user);
                                transList.add(transData);
                            }
                        }
                    }
                    //传输成功
                    transFlag = "传输成功";
                }else {
                    transFlag = "传输失败";
                    //传输失败保单处理
                    if (failedPolicys != null && failedPolicys.size() != 0) {
                        for (int i = 0; i < failedPolicys.size(); i++) {
                            //失败的保单,key为policyNo,value为失败的原因
                            JSONObject failedPolicy = failedPolicys.getJSONObject(i);
                            for (String policyNo : failedPolicy.keySet()) {
                                String failedReason = "";
                                failedPolicyNos.add(policyNo);
                                //接口返回的结果 可能长度很长不符合数据库规范
                                if (failedPolicy.getString(policyNo).length() >= 200) {
                                    failedReason = failedPolicy.getString(policyNo).substring(0, 199);
                                } else {
                                    failedReason = failedPolicy.getString(policyNo);
                                }
                                GrasSysDataTrans transData = new GrasSysDataTrans("GRAS_SYS_TEMP",policyNo,"N","Y",failedReason,user,user);
                                transList.add(transData);
                            }
                        }
                    }
                }
            }
            //传输成功的保单的处理 移除失败的就是成功的
            policys.removeAll(failedPolicyNos);
            if (policys != null && policys.size() != 0) {
                for (String policyNo : policys) {
                    GrasSysDataTrans transData = new GrasSysDataTrans("GRAS_SYS_TEMP",policyNo,"Y","Y","传输成功",user,user);
                    transList.add(transData);
                }
            }
            //写入到数据库
            if (transList != null && transList.size() != 0) {
                for (List mergeList : subListPolicyList(transList)) {
                    transService.mergeDataTransList(mergeList);
                }
            }
            //报存保单交接记录
           /* for (RNPolicyServicerChgRecord policyServicer : RNPSCRList)
            {
                if(policys.contains(policyServicer.getPolicyNo())){
                    changeService.insert(policyServicer);
                }
            }*/
            //更新es
            JSONObject jsonObject=new JSONObject();
            List<JSONObject> policyNolist=new ArrayList<JSONObject>();
            for (Object object : paramArray)
            {
                jsonObject=(JSONObject)object;
                for(String policyNo:policys){
                    if(policyNo.equals(jsonObject.get("policyNo"))){
                        String servicerNo=(String) jsonObject.get("servicerNo");
                        StaffInfo staffInfo=staffInfoService.selectByPrimaryKey(servicerNo);
                        if(staffInfo!=null){
                            jsonObject.put("empName", staffInfo.getEmpName());
                            policyNolist.add(jsonObject);
                        }
                       break; 
                    }
                }
            }
            elasticSearchService.updateAssignPolicyInfo(policyNolist);
            
            
        }catch (Exception e){
            logUtils.error(e);
        }
        return resultJson;
    }


    /**
     * MethodName:  setPolicyServicerChgRecord
     * Description:  [设置保单服务人员交接记录信息]  
     *@param policyNo
     *@param servicerNo
     *@param assginRule
     *@param user  void
     * 
     * @author  Mamba
     * @date  2019年2月18日 上午10:58:55
     */
    private void setPolicyServicerChgRecord(String policyNo, String servicerNo, String assginRule, String user,List<RNPolicyServicerChgRecord> RNPSCRList)
    {
        Date nowTime=new Date();
        //交出服务人员--原服务人员
        String earlierAgent=null;
        RNPolicyServiceInfo policyServiceInfo=servicerInfoService.selectByPolicyNo(policyNo);
        if(policyServiceInfo!=null){
            earlierAgent=policyServiceInfo.getServiceNo();
        }
        PolicyPremInfo policyPremInfo=premInfoService.selectByPolicyNo(policyNo);
        Date premDueDate=null; 
        if(policyPremInfo!=null){
            premDueDate= DateUtil.getDateFormat(policyPremInfo.getPremDueDate());
        }
        String branchCode=policyService.selectBranchCodeByPolicyNo(policyNo);
        
        RNPolicyServicerChgRecord policyServicer=new RNPolicyServicerChgRecord();
        policyServicer.setChangeSeq(NumberUtil.random20());
        policyServicer.setPolicyNo(policyNo);
        policyServicer.setBranchCode(branchCode);
        policyServicer.setEarlierAgent(earlierAgent);
        policyServicer.setNextAgent(servicerNo);
        policyServicer.setChangeDate(nowTime);
        //均为业务员
        policyServicer.setChangeMode("0");
        policyServicer.setPremDueDate(premDueDate);
        policyServicer.setCreatedUser(user);
        policyServicer.setCreatedDate(nowTime);
        policyServicer.setUpdatedUser(user);
        policyServicer.setUpdatedDate(nowTime);
        policyServicer.setPkSerial(NumberUtil.random20());
        //policyServicer.setAssignPolicyType(assginRule);
        RNPSCRList.add(policyServicer);
    }

    /**
     * 回写核心数据库的操作
     *
     * @param user    当前用户
     * @param policys 保单号数组
     * @return
     */
    @Override
    public JSONObject resultBack(String user, List<String> policys) {
        JSONObject resultJson = new JSONObject();
        String transFlag = "传输异常";
        String reason = "";
        List<RNPolicyServicerChgRecord> RNPSCRList=new ArrayList<RNPolicyServicerChgRecord>();
        //创建向接口传输数据的数组
        try {
            JSONArray paramArray = new JSONArray();
            //需要传输的参数有,policyNo,servicerNo,orphanMark,assignRule,lastAssignUser,lastAssignDate
            //查询到保单号对应的待分单的保单对应的服务人员等信息
            List<GrasSysTemp> grasSysTempList = new ArrayList<>();
            if (policys != null && policys.size() > 0) {
                List<List> policyLists = subListPolicyList(policys);
                for (List policyList : policyLists) {
                    List policyListResults = tempService.getByPolicyList(policyList);
                    grasSysTempList.addAll(policyListResults);
                }
            }
            //判空 分单成功的这些向数据库传输
            if (grasSysTempList != null && grasSysTempList.size() != 0) {
                for (GrasSysTemp sysTemp : grasSysTempList) {
                    //保单号
                    String policyNo = sysTemp.getPolicyNo();
                    //分单规则
                    String assginRule = sysTemp.getAssignRule();

                    //保单对应服务人员编号
                    String servicerNo = sysTemp.getServicerNo();
                    //保单已经分配了服务人员
                    if (servicerNo != null && !"".equals(servicerNo)) {
                        //用于存放给核心系统传输数据的
                        JSONObject dataJSON = new JSONObject(){{
                            put("policyNo", policyNo);
                            put("servicerNo", servicerNo);
                            put("orphanMark", "0");
                            put("assignRule", assginRule);
                            put("lastAssignUser", user);
                            put("lastAssignDate", DateUtil.getDateTimeFormat(new Date()));
                        }};
//                        //保单号
//                        dataJSON.put("policyNo", policyNo);
//                        //对应服务人员
//                        dataJSON.put("servicerNo", servicerNo);
//                        //孤儿单标记
//                        dataJSON.put("orphanMark", "0");
//                        //对应的分单规则
//                        dataJSON.put("assignRule", assginRule);
//                        //分单操作人,就是当前用户
//                        dataJSON.put("lastAssignUser", user);
//                        //操作日期
//                        dataJSON.put("lastAssignDate", DateUtil.getDateTimeFormat(new Date()));
                        paramArray.add(dataJSON);
                        //保单没有分配人员
                    } else {
                        JSONObject dataJSON = new JSONObject(){{
                            put("policyNo", policyNo);
                            put("servicerNo", "");
                            put("orphanMark", "1");
                            put("assignRule", assginRule);
                            put("lastAssignUser", user);
                            put("lastAssignDate", DateUtil.getDateTimeFormat(new Date()));
                        }};
//                        dataJSON.put("policyNo", policyNo);
//                        dataJSON.put("servicerNo", "");
//                        dataJSON.put("orphanMark", "1");
//                        dataJSON.put("assignRule", assginRule);
//                        dataJSON.put("lastAssignUser", user);
//                        dataJSON.put("lastAssignDate", DateUtil.getDateTimeFormat(new Date()));
                        paramArray.add(dataJSON);
                    }
                    setPolicyServicerChgRecord(policyNo, servicerNo, assginRule, user, RNPSCRList);
                }
            }
            //向核心系统传数据
            logUtils.info("核心系统回写...时间:" + new Date() + "向核心系统传入的参数为:" + paramArray);
            //此处要求是按3000条进行传输一次
            List<JSONArray> jsonArrays = submit3000Datas(paramArray, 3000);
            //传输失败的保单数组
            List<String> failedPolicyNos = new ArrayList<>();
            //传输记录 用于记录
            List<GrasSysDataTrans> transList = new ArrayList<>();
            //分批传输
            for (JSONArray pageDatas : jsonArrays) {
                //每次传输的结果
                JSONObject everyTimeSyncResult = AllotResultsBack.syncPolicyRule(pageDatas);
                logUtils.info(new Date() + "本次回写结果:" + everyTimeSyncResult);
                //传输成功与否的标示
                String flag = everyTimeSyncResult.getString("flag");
                //接口返回的传输失败的保单
                JSONArray failedPolicys = everyTimeSyncResult.getJSONArray("policyNos");
                if("0".equals(flag)){
                    //失败保单处理
                    if (failedPolicys != null && failedPolicys.size() != 0) {
                        for (int i = 0; i < failedPolicys.size(); i++) {
                            //失败的保单,key为policyNo,value为失败的原因
                            JSONObject failedPolicy = failedPolicys.getJSONObject(i);
                            for (String policyNo : failedPolicy.keySet()) {
                                String failedReason = failedPolicy.getString(policyNo);
                                failedPolicyNos.add(policyNo);
                                GrasSysDataTrans transData = new GrasSysDataTrans("GRAS_SYS_TEMP",policyNo,"N","Y",failedReason,user,user);
                                transList.add(transData);
                            }
                        }
                    }
                    //传输成功
                    transFlag = "传输成功";
                }else {
                    transFlag = "传输失败";
                    //传输失败保单处理
                    if (failedPolicys != null && failedPolicys.size() != 0) {
                        for (int i = 0; i < failedPolicys.size(); i++) {
                            //失败的保单,key为policyNo,value为失败的原因
                            JSONObject failedPolicy = failedPolicys.getJSONObject(i);
                            for (String policyNo : failedPolicy.keySet()) {
                                String failedReason = "";
                                failedPolicyNos.add(policyNo);
                                //接口返回的结果 可能长度很长不符合数据库规范
                                if (failedPolicy.getString(policyNo).length() >= 200) {
                                    failedReason = failedPolicy.getString(policyNo).substring(0, 199);
                                } else {
                                    failedReason = failedPolicy.getString(policyNo);
                                }
                                GrasSysDataTrans transData = new GrasSysDataTrans("GRAS_SYS_TEMP",policyNo,"N","Y",failedReason,user,user);
                                transList.add(transData);
                            }
                        }
                    }
                }
            }
            //传输成功的保单的处理 移除失败的就是成功的
            policys.removeAll(failedPolicyNos);
            if (policys != null && policys.size() != 0) {
                for (String policyNo : policys) {
                    GrasSysDataTrans transData = new GrasSysDataTrans("GRAS_SYS_TEMP",policyNo,"Y","Y","传输成功",user,user);
                    transList.add(transData);
                }
            }
            //临时表中数据的剔除 回写成功了的
            if (policys != null && policys.size() != 0) {
                for (List deleteList : subListPolicyList(policys)) {
                    sysTempService.deleteByPolicyList(deleteList);
                }
            }
            //写入到数据库
            if (transList != null && transList.size() != 0) {
                for (List mergeList : subListPolicyList(transList)) {
                    transService.mergeDataTransList(mergeList);
                }
            }
           //报存保单交接记录
            /*for (RNPolicyServicerChgRecord policyServicer : RNPSCRList)
            {
                if(policys.contains(policyServicer.getPolicyNo())){
                    changeService.insert(policyServicer);
                }
            }*/
            
            //更新es
            JSONObject jsonObject=new JSONObject();
            List<JSONObject> policyNolist=new ArrayList<JSONObject>();
            for (Object object : paramArray)
            {
                jsonObject=(JSONObject)object;
                for(String policyNo:policys){
                    if(policyNo.equals(jsonObject.get("policyNo"))){
                        String servicerNo=(String) jsonObject.get("servicerNo");
                        StaffInfo staffInfo=staffInfoService.selectByPrimaryKey(servicerNo);
                        if(staffInfo!=null){
                            jsonObject.put("empName", staffInfo.getEmpName());
                            policyNolist.add(jsonObject);
                        }
                       break; 
                    }
                }
            }
            elasticSearchService.updateAssignPolicyInfo(policyNolist);
            
        } catch (Exception e) {
            transFlag = "传输失败";
            reason = e.getMessage();
            resultJson.put("result", transFlag);
            resultJson.put("reason", reason);
            //错误输出
            logUtils.error(e.toString());
            e.printStackTrace();
        }
        resultJson.put("result", transFlag);
        resultJson.put("reason", reason);
        return resultJson;
    }

    @Override
    public boolean adjustEmp(String branchCode, String policyNo, String empNo,String userName) {

        String batch = "";
        List<GrasAssignBatchRecord> batchRecords = batchRecordService.assignBatchRecordMonth(branchCode);
        if (batchRecords != null && batchRecords.size() > 0) {
            GrasAssignBatchRecord batchRecord = batchRecords.get(0);
            batch = batchRecord.getBatchSeq();
        }
        GrasSysTemp temp = new GrasSysTemp(policyNo,branchCode,empNo,MyConstant.ASSIGN_RULE_11,batch,userName);
        List<GrasSysTemp> tempList = new ArrayList<>();
        tempList.add(temp);
        int mergeResult = sysTempService.insertOrUpdateBatch(tempList);
        if (mergeResult == 1) {
            //成功后要删除失败表的数据
//            failedRecordService.deleteByPolicy(policyNo);
            failedRecordService.updatePolicy("N",policyNo);
            return true;
        }
        return false;
    }

    @Override
    public List<Map<String,String>> selectForExcel(String flag, String branchCode, String month, List channelType) {
        //月份格式化
        List<JSONObject> resultJson = new ArrayList<>();
        String nowMonth = null;
        String nextMonth = null;
        Integer total = 0;
        List<Map<String,String>> resultList = new ArrayList<>();
        if (month != null && !"".equals(month)) {
            //起始日
            nowMonth = DateUtil.getPerFirstDayOfDate(month,DateUtil.DATETIME_DEFAULT_FORMAT);
            //截止日
            nextMonth = DateUtil.getPerLastDayOfDate(month,DateUtil.DATETIME_DEFAULT_FORMAT);
        }
        List<String> batchRecordsList = batchRecordService.batchRecordsByBrancodeAndMoth(branchCode, nowMonth, nextMonth);
        if (batchRecordsList != null && batchRecordsList.size() != 0) {
            if (flag.equals(SUCCESSFUL_FLAG)) {
                //总数
                total = sysTempService.countPolicyForPageInfoSuccess(batchRecordsList, branchCode, channelType);
                //总页数
                int totalPages = (total / 10) + 1;
                for (int i = 1; i <= totalPages; i++) {
                    List<Map<String,String>> pageList = sysTempService.querySuccesPolicy(batchRecordsList, branchCode, i, 10, channelType);
                    resultList.addAll(pageList);
                }
            } else if (flag.equals(FAILED_FLAG)) {
                total = sysTempService.countPolicyForPageInfoFailed(batchRecordsList, branchCode, channelType);
                //总页数
                int totalPages = (total / 10) + 1;
                for (int i = 1; i <= totalPages; i++) {
                    List<Map<String,String>> pageList = sysTempService.queryFailedPolicy(batchRecordsList, branchCode, i, 10, channelType);
                    resultList.addAll(pageList);
                }
            }
        }
        return resultList;
    }

    /**
     * 自动提交保单至核心系统
     * 剩下的所有保单都是要提交的
     */
    @Override
    public void autoResultBack() {
        List<String> policies = sysTempService.selectAllPolicies();
        JSONObject resultBack = resultBack(MyConstant.SYS_USER, policies);
        String result = resultBack.getString("result");
        //传输失败
        if (result == null || !result.equals("传输成功")) {
            //再次提交
            autoResultBack();
        }
    }

    //list长度可能过长 进行截取
    private List<List> subListPolicyList(List policyList) {
        List<List> resultList = new ArrayList();
        if (policyList == null || policyList.size() == 0) {
            return null;
        }
        for (int i = 0; i < policyList.size(); i++) {
            if (i % 999 == 0) {
                int count = i / 999;
                List subList = (List) policyList.stream().limit((count + 1) * 999).skip(count * 999).collect(Collectors.toList());
                resultList.add(subList);
            }
        }
        return resultList;
    }


    //查看人员能服务哪些渠道
    private Set<String> checkChannelTypes(String empNo) {
        Set<String> channelList = new LinkedHashSet<>();
        //人员本身的渠道
        String channelTypeByEmpNp = staffInfoService.selectChannelTypeByEmpNp(empNo);
        channelList.add(channelTypeByEmpNp);
        //兼收范围查看
        RenewalStaffInfoOther staffInfoOther = otherService.selectByEmpNo(empNo);
        //个险兼收标示OK  个险兼收     可服务保单渠道:个险,经代,收展,银代 SFP 区拓 创新拓展
        if (staffInfoOther != null && "Y".equals(staffInfoOther.getMarketFlag())) {
            addChannelTypes(channelList, MyConstant.CHANNEL_02, MyConstant.CHANNEL_03, MyConstant.CHANNEL_04, MyConstant.CHANNEL_05, MyConstant.CHANNEL_09, MyConstant.CHANNEL_07);
        }
        //银代兼收标示OK  可服务保单渠道:个险,经代,收展,银代
        if (staffInfoOther != null && "Y".equals(staffInfoOther.getBankFlag())) {
            addChannelTypes(channelList, MyConstant.CHANNEL_05, MyConstant.CHANNEL_02, MyConstant.CHANNEL_03, MyConstant.CHANNEL_04, MyConstant.CHANNEL_09, MyConstant.CHANNEL_07);
        }
        //人员职位
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(empNo);
        if (staffInfo != null) {
            //人员职位
            String position = staffInfo.getPosition();
            //收展主任 可以负责:个险,经代,收展,银代,SFP(属于银代),区拓(属于个险),创新(属于银代)
            if (position != null && !"".equals(position) && MyConstant.CD_DIRECTOR.equals(position)) {
                addChannelTypes(channelList, MyConstant.CHANNEL_02, MyConstant.CHANNEL_03, MyConstant.CHANNEL_04, MyConstant.CHANNEL_05, MyConstant.CHANNEL_07, MyConstant.CHANNEL_09);
            }
            //个险收展专员  个险,经代,收展
            if (position != null && !"".equals(position) && MyConstant.PERSONAL_INSURANCE_SERVICER.equals(position)) {
                channelList.addAll(Arrays.asList(MyConstant.CHANNEL_01,MyConstant.CHANNEL_03,MyConstant.CHANNEL_05,MyConstant.CHANNEL_07));
            }
            //银代收展专员 银代
            if (position != null && !"".equals(position) && MyConstant.BANK_AGENT_SERVICER.equals(position)) {
                channelList.addAll(Arrays.asList(MyConstant.CHANNEL_02,MyConstant.CHANNEL_04,MyConstant.CHANNEL_09));
            }
        }
        return channelList;
    }

    private void addChannelTypes(Set<String> channelList, String e2, String e3, String e4, String e5, String e6, String e7) {
        channelList.add(MyConstant.CHANNEL_01);
        channelList.addAll(Arrays.asList(e2,e3,e4,e5,e6,e7));
    }

    /**
     * MethodName:  queryPoServerInfoExportToExcel 
     * Description:  [根据应缴月查询机构保单服务信息] 
     *@param branchCode
     *@param channelType
     *@param month
     *@return 
     */
    @Override
    public List<JSONObject> queryPoServerInfoExportToExcel(String branchCode, String channelType, String month)
    {
        Map<String, String> paramMap=new HashMap<String,String>();
        String nowMonth = null;
        String nextMonth = null;
        if (month != null && !"".equals(month)) {
//            Map<String, String> allotMonth = DateUtil.allotMonth(month);
            //起始日
//            nowMonth = allotMonth.get("nowMonth");
            nowMonth = DateUtil.getPerFirstDayOfDate(month,DateUtil.DATETIME_DEFAULT_FORMAT);
            //截止日
//            nextMonth = allotMonth.get("nextMonth");
            nextMonth = DateUtil.getPerLastDayOfDate(month,DateUtil.DATETIME_DEFAULT_FORMAT);
        }
        paramMap.put("branchCode", branchCode);
        paramMap.put("nowMonth", nowMonth);
        paramMap.put("nextMonth", nextMonth);
        
        List<String> channelTypeList = null;
        if(!StringUtils.isEmpty(channelType)){
            String[] channelTpList=channelType.split(",");
            channelTypeList=Arrays.asList(channelTpList);
            
            //paramMap.put("channelType", channelType);
        }
       //List<JSONObject> list=new ArrayList<JSONObject>();
       List<JSONObject> normalAssignList=null;
       //List<JSONObject> spanBranchList=null;
        try
        {
            normalAssignList=servicerInfoService.queryPoSericeInfoByPremDueDate(branchCode,nowMonth,nextMonth,channelTypeList);
            /*if(normalAssignList!=null){
                list.addAll(normalAssignList);
            }*/
            //获取跨机构分单保单
         /*   spanBranchList=servicerInfoService.querySpanBranchAssignPolicy(paramMap);
            if(spanBranchList!=null){
                list.addAll(spanBranchList);
            }*/
            
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        
       
        return normalAssignList;
    }

    /**
     * 数据分3000条一次向RN系统传输
     * @param allDatas 全部数据
     * @param pageData 每次传多少
     * @return
     */
    private List<JSONArray> submit3000Datas(JSONArray allDatas,int pageData){
        List<JSONArray> resultList = new ArrayList();
        if(allDatas == null || allDatas.size() == 0){
            return null;
        }
        int num = 0;
        JSONArray tempArray = new JSONArray();
        for(int i = 0 ; i<allDatas.size();i++){
            JSONObject itemObject = allDatas.getJSONObject(i);
            tempArray.add(itemObject);
            num++;
            if (num == pageData){
                resultList.add(tempArray);
                num = 0;
                tempArray.clear();
            }
//            if(i % pageData == 0){
//                int count = i/pageData;
//                JSONArray subList = JSONArray.parseArray(allDatas.stream().limit((count + 1) * pageData).skip(count * pageData).collect(Collectors.toList()).toString()) ;
//                resultList.add(subList);
//            }
        }
        if (tempArray.size()>0){
            resultList.add(tempArray);
        }
        return resultList;
    }
}