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

import com.google.common.base.Strings;
import com.yd.api.practitioner.vo.opportunity.ApplyForExpertSupportRequestVO;
import com.yd.api.practitioner.vo.opportunity.ApplyForExpertSupportResponseVO;
import com.yd.api.practitioner.vo.organization.*;
import com.yd.api.practitioner.vo.payscale.PayScalePdfRequestVO;
import com.yd.api.practitioner.service.PractitionerBasicInfoService;
import com.yd.api.practitioner.vo.payscale.PayScaleInfo;
import com.yd.api.practitioner.vo.payscale.PayScalePdfResponseVO;
import com.yd.api.practitioner.vo.payscale.PayScaleQueryRequestVO;
import com.yd.api.practitioner.vo.payscale.PayScaleQueryResponseVO;
import com.yd.api.practitioner.vo.policy.PolicyInfo;
import com.yd.api.practitioner.vo.policy.PolicyListQueryRequestVO;
import com.yd.api.practitioner.vo.policy.PolicyListQueryResponseVO;
import com.yd.api.practitioner.vo.policy.policyinfoquery.*;
import com.yd.api.result.CommonResult;
import com.yd.dal.entity.customer.AclFileUpload;
import com.yd.dal.entity.customer.AclPractitioner;
import com.yd.dal.entity.customer.practitioner.PractitionerBasicInfo;
import com.yd.dal.entity.customer.practitioner.PractitionerInfo;
import com.yd.dal.entity.meta.OptionsEGolden;
import com.yd.dal.entity.order.CustomerPolicyInfo;
import com.yd.dal.entity.order.PolicyDetailInfoE;
import com.yd.dal.entity.order.PolicyFactorInfoE;
import com.yd.dal.entity.practitioner.payscale.PayScaleBasicInfo;
import com.yd.dal.entity.product.Product;
import com.yd.dal.entity.product.ProductE;
import com.yd.dal.entity.product.ProductPlan;
import com.yd.dal.service.customer.AclFileUploadDALService;
import com.yd.dal.service.customer.AclPractitionerDALService;
import com.yd.dal.service.meta.MdDropOptionsDALService;
import com.yd.dal.service.order.PoOrderDALService;
import com.yd.dal.service.product.ProductDALService;
import com.yd.dal.service.product.ProductPlanDALService;
import com.yd.rmi.ali.oss.service.OssService;
import com.yd.rmi.ali.oss.vo.OssOperateTypeEnum;
import com.yd.rmi.ali.oss.vo.OssRequestVO;
import com.yd.rmi.ali.oss.vo.OssResponseVO;
import com.yd.rmi.cache.SystemConfigService;
import com.yd.util.CommonUtil;
import com.yd.util.config.ZHBErrorConfig;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.*;

@Service("practitionerBasicInfoService")
public class PractitionerBasicInfoServiceImpl implements PractitionerBasicInfoService {

    @Autowired
    private AclPractitionerDALService aclPractitionerDALService;
    @Autowired
    private PoOrderDALService poOrderDALService;
    @Autowired
    private ProductPlanDALService productPlanDALService;
    @Autowired
    private ProductDALService productDALService;
    @Autowired
    private MdDropOptionsDALService mdDropOptionsDALService;
    @Autowired
    private SystemConfigService systemConfigService;
    @Autowired
    private OssService ossService;
    @Autowired
    private AclFileUploadDALService aclFileUploadDALService;

    @Override
    public PolicyListQueryResponseVO policyListQuery(PolicyListQueryRequestVO requestVO) {
        PolicyListQueryResponseVO responseVO = new PolicyListQueryResponseVO();
        Long practitionerId = requestVO.getPractitionerId();
        if(practitionerId !=null){
            String mobileNo = aclPractitionerDALService.findMobileNoByPractitionerId(practitionerId);
            if(!Strings.isNullOrEmpty(mobileNo) && mobileNo.length() == 11){
                List<PolicyInfo> policyInfoList = new ArrayList<>();
                Integer time = requestVO.getTime();
                //1、线上
                getPolicyListForYD(policyInfoList,practitionerId,time);
                //2、线下
                getPolicyListForEGolden(policyInfoList,mobileNo,time);
                responseVO.setPolicyInfoList(policyInfoList);
                Collections.sort(policyInfoList);
                responseVO.setCommonResult(new CommonResult(true,ZHBErrorConfig.getErrorInfo("800000")));
            }else{
                responseVO.setCommonResult(new CommonResult(false, ZHBErrorConfig.getErrorInfo("820001")));
            }
        }else{
            String[] params = {"practitionerId"};
            responseVO.setCommonResult(new CommonResult(false, ZHBErrorConfig.getErrorInfo("610001", params)));
        }
        return responseVO;
    }

    @Override
    public PolicyInfoQueryResponseVO policyInfoQuery(PolicyInfoQueryRequestVO requestVO) {
        PolicyInfoQueryResponseVO responseVO = new PolicyInfoQueryResponseVO();
        String orderNo = requestVO.getOrderNo();
        String policyNo = requestVO.getPolicyNo();
        if(!Strings.isNullOrEmpty(orderNo) || !Strings.isNullOrEmpty(policyNo)){
            Integer platform = requestVO.getPlatform();
            platform = (platform == null) ? 1 : platform;
            if(platform == 2){//EGolden
                //1、EGolden--获取orderNo
                orderNo = (Strings.isNullOrEmpty(orderNo)) ? getOrderNoE(policyNo) : orderNo;
                //2、根据orderNo获取保单和被保人的相关数据
                List<PolicyDetailInfoE> policyDetailInfoES = poOrderDALService.findPolicyDetailsInfoByOrderNoE(orderNo);
                if(!policyDetailInfoES.isEmpty()){
                    getResponseMessage(responseVO,policyDetailInfoES);
                    responseVO.setCommonResult(new CommonResult(true,ZHBErrorConfig.getErrorInfo("800000")));
                }
            }else if(platform == 1){//YD
                responseVO.setCommonResult(new CommonResult(true,ZHBErrorConfig.getErrorInfo("800000")));
            }
        }else{
            String[] params = {"orderNo,policyNo"};
            responseVO.setCommonResult(new CommonResult(false, ZHBErrorConfig.getErrorInfo("610002", params)));
        }
        return responseVO;
    }

    @Override
    public PayScaleQueryResponseVO payScaleListQuery(PayScaleQueryRequestVO requestVO) {
        PayScaleQueryResponseVO responseVO = new PayScaleQueryResponseVO();
        String practitionerIdEG = requestVO.getPractitionerIdEG();
        if(!Strings.isNullOrEmpty(practitionerIdEG)){
            List<PayScaleInfo> payScaleInfoListAll =  aclPractitionerDALService.findPayScaleByPractitionerEG(practitionerIdEG);
            if(!payScaleInfoListAll.isEmpty()){
                Map<String,String> dtlTypeMap = new HashMap<>();
                Map<String,String> titleMap = new HashMap<>();
                List<OptionsEGolden> optionsEGoldenList = mdDropOptionsDALService.findByMasterIdsE(Collections.singletonList(101));
                optionsEGoldenList.forEach(i->dtlTypeMap.put(i.getOptAttr(),i.getOptName()));
                List<OptionsEGolden> titleList = mdDropOptionsDALService.findAllTitleEG();
                titleList.forEach(i->titleMap.put(i.getTitleCode(),i.getTitleName()));
                Map<Integer,PayScaleInfo> payScaleInfoMap = new HashMap<>();
                PayScaleInfo payScaleInfo;
                Integer time;
                for(PayScaleInfo item : payScaleInfoListAll){
                    time = item.getMonDtlPeriod();
                    if(payScaleInfoMap.containsKey(time)){
                        payScaleInfo = payScaleInfoMap.get(time);
                        calculateRAmount(payScaleInfo,item);
                    }else{
                        calculateRAmount(item,item);
                        item.setMonDtlItem("实发薪水");
                        payScaleInfoMap.put(time,item);
                        item.setDrpTitleCode(titleMap.get(item.getDrpTitleCode()));
                        item.setMonDtlType(dtlTypeMap.get(item.getMonDtlType()));

                    }
                }
                //修改金钱格式
                for(PayScaleInfo item : payScaleInfoListAll){
                    item.setMonDtlRAmount(CommonUtil.doubleFormat(item.getMonDtlRAmount(),2));
                }
                List<PayScaleInfo> resultList = new ArrayList<>(payScaleInfoMap.values());
                resultList.sort(Comparator.comparingInt(PayScaleInfo :: getMonDtlPeriod).reversed());
                responseVO.setPayScaleInfos(resultList);
            }
            responseVO.setCommonResult(new CommonResult(true,ZHBErrorConfig.getErrorInfo("800000")));
        }else{
            String[] params = {"practitionerIdEG"};
            responseVO.setCommonResult(new CommonResult(false, ZHBErrorConfig.getErrorInfo("610002", params)));
        }
        return responseVO;
    }

    @Override
    public PayScalePdfResponseVO payScalePdf(PayScalePdfRequestVO requestVO) {
        PayScalePdfResponseVO responseVO = new PayScalePdfResponseVO();
        Integer monShId = requestVO.getMonShId();
        Long practitionerId = requestVO.getPractitionerId();
        if(monShId != null && practitionerId != null){
            PayScaleBasicInfo payScaleBasicInfo = aclPractitionerDALService.findFilePathByMonShId(monShId);
            if(payScaleBasicInfo != null){
                Integer time = payScaleBasicInfo.getMonDtlPeriod();
                if(time != null){
                    AclFileUpload aclFileUpload = aclFileUploadDALService.findByTargetIdAndRemark(1,practitionerId,time.toString());
                    String url;
                    if(aclFileUpload != null){
                        url = aclFileUpload.getFilePath();
                        if(Strings.isNullOrEmpty(url)){
                            url = checkPractitionerId(payScaleBasicInfo,practitionerId,time.toString());
                        }
                    }else{
                        url = checkPractitionerId(payScaleBasicInfo,practitionerId,time.toString());
                    }
                    if(!Strings.isNullOrEmpty(url)){
                        responseVO.setUrl(url);
                        responseVO.setCommonResult(new CommonResult(true,ZHBErrorConfig.getErrorInfo("800000")));
                        return responseVO;
                    }
                }
            }
        }
        responseVO.setCommonResult(new CommonResult(true,ZHBErrorConfig.getErrorInfo("820001")));
        return responseVO;
    }

    @Override
    public OrganizationQueryResponseVO organizationQuery(OrganizationQueryRequestVO requestVO) {
        OrganizationQueryResponseVO responseVO = new OrganizationQueryResponseVO();
        String practitionerSubordinateSystemIdEG = requestVO.getPractitionerSubordinateSystemIdEG();
        String deptIdEG = requestVO.getDeptIdEG();
        String insurerBranchIdEG = requestVO.getInsurerBranchIdEG();
        List<PractitionerSubordinateSystemInfo> subordinateSystemInfoList;
        List<InsurerBranchDeptInfo> insurerBranchDeptInfoList;
        List<InsurerBranchInfo> insurerBranchInfoList;
        //查询体系
        if(!Strings.isNullOrEmpty(practitionerSubordinateSystemIdEG)){
            subordinateSystemInfoList = mdDropOptionsDALService.findSubordinateSystemInfoByIdEG(Arrays.asList(practitionerSubordinateSystemIdEG));
            if(!subordinateSystemInfoList.isEmpty()){
                deptIdEG = subordinateSystemInfoList.get(0).getDeptIdEG();
            }
        }else{
            subordinateSystemInfoList = mdDropOptionsDALService.findSubordinateSystemInfoEG();
        }
        //查询营业部
        if(!Strings.isNullOrEmpty(deptIdEG)){
            insurerBranchDeptInfoList = mdDropOptionsDALService.findBranchDeptInfoByIdEG(Arrays.asList(deptIdEG));
            if(!insurerBranchDeptInfoList.isEmpty()){
                insurerBranchIdEG = insurerBranchDeptInfoList.get(0).getInsurerBranchIdEG();
            }
        }else{
            insurerBranchDeptInfoList = mdDropOptionsDALService.findBranchDeptInfoEG();
        }
        //查询分公司
        if(!Strings.isNullOrEmpty(insurerBranchIdEG)){
            insurerBranchInfoList = mdDropOptionsDALService.findInsurerBranchInfoByIdEG(Arrays.asList(insurerBranchIdEG));
        }else{
            insurerBranchInfoList = mdDropOptionsDALService.findInsurerBranchInfoEG();
        }
        if(!subordinateSystemInfoList.isEmpty() && !insurerBranchDeptInfoList.isEmpty() && !insurerBranchInfoList.isEmpty()){
            getResponseMessage(responseVO,subordinateSystemInfoList,insurerBranchDeptInfoList,insurerBranchInfoList);
            responseVO.setCommonResult(new CommonResult(true,ZHBErrorConfig.getErrorInfo("800000")));
        }else{
            responseVO.setCommonResult(new CommonResult(false,ZHBErrorConfig.getErrorInfo("820001")));
        }
        return responseVO;
    }

    private void getResponseMessage(OrganizationQueryResponseVO responseVO, List<PractitionerSubordinateSystemInfo> subordinateSystemInfoList, List<InsurerBranchDeptInfo> insurerBranchDeptInfoList, List<InsurerBranchInfo> insurerBranchInfoList) {
        Map<String,List<PractitionerSubordinateSystemInfo>> systemMap = new HashMap<>();
        List<PractitionerSubordinateSystemInfo> systemInfoList;
        Map<String,List<InsurerBranchDeptInfo>> deptMap = new HashMap<>();
        List<InsurerBranchDeptInfo> deptInfoList;
        if(!subordinateSystemInfoList.isEmpty()){
            String deptId;
            for(PractitionerSubordinateSystemInfo systemInfo : subordinateSystemInfoList){
                deptId = systemInfo.getDeptIdEG();
                if(systemMap.containsKey(deptId)){
                    systemInfoList = systemMap.get(deptId);
                    systemInfoList.add(systemInfo);
                }else{
                    systemInfoList = new ArrayList<>();
                    systemInfoList.add(systemInfo);
                    systemMap.put(deptId,systemInfoList);
                }
            }
        }
        if(!insurerBranchDeptInfoList.isEmpty()){
            String branchId,deptId;
            for(InsurerBranchDeptInfo branchDeptInfo : insurerBranchDeptInfoList){
                branchId = branchDeptInfo.getInsurerBranchIdEG();
                deptId = branchDeptInfo.getIdEG();
                branchDeptInfo.setPractitionerSubordinateSystemInfoList(systemMap.get(deptId));
                if(deptMap.containsKey(branchId)){
                    deptInfoList = deptMap.get(branchId);
                    deptInfoList.add(branchDeptInfo);
                }else{
                    deptInfoList = new ArrayList<>();
                    deptInfoList.add(branchDeptInfo);
                    deptMap.put(branchId,deptInfoList);
                }
            }
        }

        if(!insurerBranchInfoList.isEmpty()){
            String branchId;
            for(InsurerBranchInfo branchInfo : insurerBranchInfoList){
                branchId = branchInfo.getInsurerBranchIdEG();
                branchInfo.setInsurerBranchDeptList(deptMap.get(branchId));
            }
            responseVO.setInsurerBranchInfoList(insurerBranchInfoList);
        }
    }

    private String checkPractitionerId(PayScaleBasicInfo payScaleBasicInfo, Long practitionerId,String time){
        if(payScaleBasicInfo != null){
            String practitionerIdEG = payScaleBasicInfo.getSalMstId();
            PractitionerBasicInfo practitionerBasicInfo = aclPractitionerDALService.findByIdEG(practitionerIdEG);
            if(practitionerBasicInfo != null){
                String mobileNo = practitionerBasicInfo.getMobileNo();
                if(!Strings.isNullOrEmpty(mobileNo)){
                    PractitionerInfo practitionerInfo = aclPractitionerDALService.findPractitionerInfoByLogin(mobileNo);
                    if(practitionerInfo != null){
                        Long practitionerIdDB = practitionerInfo.getPractitionerId();
                        if(practitionerIdDB != null && practitionerIdDB.equals(practitionerId)){
                            String filePath = payScaleBasicInfo.getUploadPath();
                            return getPDFUrl(filePath,practitionerId,time);
                        }
                    }
                }
            }
        }
        return null;
    }

    private String getPDFUrl(String filePath,Long practitionerId,String time) {
        String url = null;
        String[] filePathStr = filePath.split("salaryCalculation/");
        if(filePathStr.length == 2) {
            String catalogPath = systemConfigService.getSingleConfigValue("payScalePath");
            filePath = catalogPath + filePathStr[1];//"/home/egolden/shareSalaryCalculation/"
//            filePath = "/users/water/Salary_201908_YDSH00032.pdf";
            File file = new File(filePath);
            if (file.exists()) {// 如果文件名存在，则进行下载
                // 获取文件名和日期
                String[] str = filePath.split("/");
                String fileName = str[str.length-1];
                String timeScale = str[str.length-2];
                String prefix = "payScale/"+timeScale+"/";
                String ossKey = fileName.replaceAll(" ", "").replaceAll("	", "");
                ossKey = prefix+CommonUtil.getRandomNum(5)+ossKey;
                try{
                    OssRequestVO requestVO = new OssRequestVO();
                    requestVO.setOperateType(OssOperateTypeEnum.PUT_OBJECT.getCode());
                    requestVO.setBucketName(systemConfigService.getSingleConfigValue("ALI_OSS_BUCKET_NAME"));
                    requestVO.setKey(ossKey);
                    requestVO.setFile(file);
                    OssResponseVO ossresponseVO = ossService.ossOperate(requestVO);
                    if(ossresponseVO.getCommonResult().isSuccess()){
                        requestVO.setOperateType(OssOperateTypeEnum.GENERATE_URL.getCode());
                        ossresponseVO = ossService.ossOperate(requestVO);
                        url = ossresponseVO.getUrl();
                        AclFileUpload aclFileUpload = new AclFileUpload();
                        aclFileUpload.setTargetType(1);
                        aclFileUpload.setTargetId(practitionerId);
                        aclFileUpload.setTargetNo("payScale");
                        aclFileUpload.setFileType("PDF");
                        aclFileUpload.setFileName(fileName);
                        aclFileUpload.setFilePath(url);
                        aclFileUpload.setTargetUseFor(10);
                        System.out.println("文件大小：" + file.length());
                        aclFileUpload.setFileSize(String.valueOf(file.length()));
                        aclFileUpload.setOssKey(ossKey);
                        aclFileUpload.setIsActive(1);
                        aclFileUpload.setUploadedAt(new Date());
                        aclFileUpload.setUploadedBy(-1L);
                        aclFileUpload.setRemark(time);
                        aclFileUploadDALService.saveFileUpload(aclFileUpload);
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }finally{
                    file.deleteOnExit();
                }
            }
        }
        return url;
    }


//    private void getPayScalePdf(String filePath, HttpServletResponse response) {
//        File file = new File(filePath);
//        // 如果文件名存在，则进行下载
//        if (file.exists()) {
//            // 配置文件下载
//            String[] str = filePath.split("/");
//            String fileName = str[str.length-1];
//            response.setHeader("content-type", "application/pdf");
//            response.setHeader("Cache-Control", "max-age=30");
//            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
//            response.setHeader("Pragma", "public");
//            // 下载文件能正常显示中文
//            try {
//                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//            } catch (UnsupportedEncodingException e) {
//                e.printStackTrace();
//            }
//            response.setContentType("application/pdf");
//            // 实现文件下载
//            byte[] buffer = new byte[1024];
//            FileInputStream fis = null;
//            BufferedInputStream bis = null;
//            try {
//                fis = new FileInputStream(file);
//                bis = new BufferedInputStream(fis);
//                OutputStream os = response.getOutputStream();
//                int i = bis.read(buffer);
//                while (i != -1) {
//                    os.write(buffer, 0, i);
//                    i = bis.read(buffer);
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            } finally {
//                if (bis != null) {
//                    try {
//                        bis.close();
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
//                if (fis != null) {
//                    try {
//                        fis.close();
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//        }
//    }

    private void calculateRAmount(PayScaleInfo payScaleInfoMain, PayScaleInfo payScaleInfoElse) {
        if(payScaleInfoMain != null && payScaleInfoElse != null){
            Integer shIdMain = payScaleInfoMain.getMonShId();
            Integer shIdElse = payScaleInfoElse.getMonShId();
            Double all = payScaleInfoMain.getMonDtlRAmount();
            double allA = (shIdMain.equals(shIdElse))? 0D : payScaleInfoMain.getMonDtlAmount();
            Double temp = payScaleInfoElse.getMonDtlAmount();
            String type = payScaleInfoElse.getMonDtlItem();
            if(!Strings.isNullOrEmpty(type)){
                if(type.startsWith("W")){
                    all =  all - temp;
                }else{
                    all =  all + temp;
                    allA = allA + temp;
                }
                payScaleInfoMain.setMonDtlRAmount(all);
                payScaleInfoMain.setMonDtlAmount(allA);
            }
        }
    }

    private String getOrderNoE(String policyNo) {
        String orderNo = null;
        if(!Strings.isNullOrEmpty(policyNo)){
            orderNo = poOrderDALService.findOrderNoByPolicyNo(policyNo);
        }
        return orderNo;
    }

    private void getResponseMessage(PolicyInfoQueryResponseVO responseVO, List<PolicyDetailInfoE> policyDetailInfoES) {
        if(!policyDetailInfoES.isEmpty()){
            List<Integer> materIds = Arrays.asList(20,16,116,101,19,50); // 20 保单状态，16 缴费频率， 116 发佣状态， 101 保单类别, 19 保额单位，50 与投保人关系
            List<OptionsEGolden> optionsEGoldenList = mdDropOptionsDALService.findByMasterIdsE(materIds);
            Map<Integer,Map<String,String>> masterMap = getMasterMap(optionsEGoldenList);

            //查询保单因子相关信息
            Set<String> orderNoSet = new HashSet<>();
            policyDetailInfoES.forEach(i->orderNoSet.add(i.getOrderNo()));
            List<String>  orderNoList = new ArrayList<>(orderNoSet);
            List<PolicyFactorInfoE> policyFactorInfoES = poOrderDALService.findPolicyFactorByOrderNosE(orderNoList);
            Map<String,PolicyFactorInfoE> policyFactorInfoEMap = new HashMap<>();
            policyFactorInfoES.forEach(i->policyFactorInfoEMap.put(i.getProductId(),i));
            //拼装返回报文
            String productId;
            PolicyFactorInfoE policyFactorInfoE;
            List<PolicyFactorInfo> PolicyFactorInfoList= new ArrayList<>();
            PolicyFactorInfo policyFactorInfo;
            HolderInfo holderInfo;
            List<InsuredInfo> insuredInfos;
            InsuredInfo insuredInfo;
            IDInfo idInfo;
            String relationShip;
            double orderPrice = 0d,commission = 0d;
            boolean success = false;
            for(PolicyDetailInfoE item : policyDetailInfoES){
                productId = item.getProductId();
                policyFactorInfoE = policyFactorInfoEMap.get(productId);
                policyFactorInfo = new PolicyFactorInfo();
                BeanUtils.copyProperties(item,policyFactorInfo);
                BeanUtils.copyProperties(policyFactorInfoE,policyFactorInfo);
                policyFactorInfo.setPolicyType(masterMap.get(101).get(item.getPolicyType()));
                policyFactorInfo.setPayFrequency(masterMap.get(16).get(item.getPayFrequency()));
                policyFactorInfo.setPayCommissionStatus(masterMap.get(116).get(item.getPayCommissionStatus()));
                policyFactorInfo.setAmountUnit(masterMap.get(19).get(policyFactorInfoE.getAmountUnit()));
                policyFactorInfo.setCommissionType(getCommissionType(item.getCommissionType()));
                policyFactorInfo.setRelationship(masterMap.get(50).get(policyFactorInfoE.getRelationship()));
                PolicyFactorInfoList.add(policyFactorInfo);
                relationShip = policyFactorInfoE.getRelationship();
                if(item.getPremium() !=null)
                orderPrice = (item.getPremium() !=null) ? orderPrice + item.getPremium() : orderPrice;
                commission = (item.getCommission() !=null) ? commission + item.getCommission() : commission;
                if(!success){
                    responseVO.setOrderNo(item.getOrderNo());
                    responseVO.setPolicyNo(item.getPolicyNo());
                    responseVO.setOrderDate(item.getOrderDate());
                    responseVO.setStartDate(item.getStartDate());
                    responseVO.setEndDate(item.getEndDate());
                    responseVO.setStatus(masterMap.get(20).get(item.getPolicyStatus()));
                    holderInfo = new HolderInfo();
                    holderInfo.setName(item.getHolderName());
                    holderInfo.setMobileNo(item.getHolderMobileNo());
                    holderInfo.setGender("1".equals(item.getHolderSex()) ? 1 : 2);
                    holderInfo.setBirthDay(item.getHolderBirthday());
                    holderInfo.setAge(CommonUtil.getAge(CommonUtil.stringParseDate(item.getHolderBirthday(),"yyyy-MM-dd")));
                    idInfo = new IDInfo();
                    idInfo.setIdType(getIdType(item.getHolderIdNoType()));
                    idInfo.setIdNo(item.getHolderIdNo());
                    holderInfo.setIdInfo(idInfo);
                    responseVO.setHolderInfo(holderInfo);
                    idInfo = new IDInfo();
                    idInfo.setIdType(getIdType(item.getInsuredIdNoType()));
                    idInfo.setIdNo(item.getInsuredIdNo());
                    insuredInfos = new ArrayList<>();
                    insuredInfo = new InsuredInfo();
                    insuredInfo.setName(item.getInsuredName());
                    insuredInfo.setRelationType(getRelationType(relationShip));
                    insuredInfo.setMobileNo(item.getInsuredMobileNo());
                    insuredInfo.setGender("1".equals(item.getInsuredSex()) ? 1 : 2);
                    insuredInfo.setBirthDay(item.getInsuredBirthday());
                    insuredInfo.setAge(CommonUtil.getAge(CommonUtil.stringParseDate(item.getInsuredBirthday(),"yyyy-MM-dd")));
                    insuredInfo.setIdInfo(idInfo);
                    insuredInfos.add(insuredInfo);
                    responseVO.setInsuredInfos(insuredInfos);
                    success = true;
                }
            }
            responseVO.setPrice(CommonUtil.doubleFormat(orderPrice,2));
            ReferralInfo referralInfo = new ReferralInfo();
            referralInfo.setReferralAmount(CommonUtil.doubleFormat(commission,2));
            responseVO.setReferralInfo(referralInfo);
            responseVO.setPolicyFactorInfos(PolicyFactorInfoList);
        }
    }

    private Long getIdType(String holderIdNoType) {
        //1-身份证,2-护照,3-港澳身份证,4-台胞证,9-其他,20-组织机构代码
        switch(holderIdNoType){
            case "1": return 1L;
            case "2": return 2L;
            case "3": return 9L;
            case "4": return 4L;
            case "5": return 3L;
            case "6": return 20L;
            case "7": return 9L;
        }
        return 9L;
    }

    private String getCommissionType(String commissionType) {
        switch (commissionType){
            case "B01": return "前期欠款";
            case "N01": return "个人直展年终奖";
            case "P01": return "直展营销佣金";
            case "P02": return "保险公司奖励金";
            case "PS1": return "主管第13个月继续率";
            case "PS2": return "主管第25个月继续率";
            case "PS3": return "主管第37个月继续率";
            case "PS4": return "主管第49个月继续率";
            case "R01": return "续年度服务津贴";
            case "S01": return "首年度销售佣金";
            case "S02": return "续年度销售佣金";
            case "S03": return "首年度辅导奖金";
            case "S04": return "续年度辅导奖金";
            case "S05": return "首年度管理奖金";
            case "S06": return "续年度管理奖金";
            case "S07": return "平阶推介奖金";
            case "S08": return "低阶推介奖金";
            case "S09": return "高阶推介奖金";
            case "S10": return "跨体系推介奖金";
            case "S11": return "体系推介奖金";
            case "S12": return "保险公司奖励金";
            case "S13": return "公司活动奖金";
            case "S14": return "特别管理奖金";
            case "S15": return "引荐体系奖金";
            case "S16": return "引荐人奖金";
            case "W01": return "代扣所得税";
            case "W02": return "代扣个人增值税";
            case "W03": return "代扣城建税";
            case "W05": return "邮寄费";
            case "W06": return "保险公司加扣款";
//            case "W06": return "欠款上扣主管";
            case "Y01": return "应税其他加扣款";
//            case "W01": return "代扣所得税";
        }
        return null;
    }

    private Long getRelationType(String relationShip) {
        if("8".equals(relationShip)){
            return 1L;
        }else if("14".equals(relationShip)) {
            return 2L;
        }else if("3".equals(relationShip)) {
            return 4L;
        }else if("6".equals(relationShip)) {
            return 3L;
        }else{
            return 5L;
        }
    }

    private Map<Integer, Map<String, String>> getMasterMap(List<OptionsEGolden> optionsEGoldenList) {
        Map<Integer, Map<String, String>> masterMap = new HashMap<>();
        if(!optionsEGoldenList.isEmpty()){
            Map<String,String> optMap;
            Integer mstId;
            for(OptionsEGolden item : optionsEGoldenList){
                mstId = item.getMstId();
                if(masterMap.containsKey(mstId)){
                    optMap = masterMap.get(mstId);
                    optMap.put(item.getOptAttr(),item.getOptName());
                }else{
                    optMap = new HashMap<>();
                    optMap.put(item.getOptAttr(),item.getOptName());
                    masterMap.put(mstId,optMap);
                }
            }
        }
        return masterMap;
    }

    /**
     * EGolden--查询经纪人保单列表
     * @param policyInfoList 保单列表
     * @param mobileNo 手机号码
     * @param time 时间段
     */
    private void getPolicyListForEGolden(List<PolicyInfo> policyInfoList, String mobileNo, Integer time) {
        if(!Strings.isNullOrEmpty(mobileNo)){
            PolicyInfo policyInfo ;
            List<CustomerPolicyInfo> policyInfos = poOrderDALService.findPolicyInfoByMobileNoE(mobileNo,time);
            if(!policyInfos.isEmpty()){
                String productId ;
                Map<String,String> productNameMap = new HashMap<>();
                List<ProductE> products = productDALService.findAllE();
                products.forEach(i->productNameMap.put(i.getProductId(),i.getProductName()));
                for(CustomerPolicyInfo item : policyInfos){
                    policyInfo = new PolicyInfo();
                    productId = item.getProductName();
                    BeanUtils.copyProperties(item,policyInfo);
                    policyInfo.setProductName(productNameMap.get(productId));
                    policyInfo.setPlatform(2);
                    policyInfoList.add(policyInfo);
                }
            }
        }
    }

    /**
     * 银盾保险在线--查询经纪人保单列表
     * @param policyInfoList 保单列表
     * @param practitionerId 经纪人id
     * @param time 时间段
     */
    private void getPolicyListForYD(List<PolicyInfo> policyInfoList, Long practitionerId, Integer time) {
        if(practitionerId != null ){
            AclPractitioner practitioner = aclPractitionerDALService.findById(practitionerId);
            Long customerId = practitioner.getCustomerId();
            if(customerId != null){
                List<CustomerPolicyInfo> policyInfos = poOrderDALService.findPolicyInfoByCustomerId(customerId,time);
                if(!policyInfos.isEmpty()){
                    PolicyInfo policyInfo ;
                    Map<Long,String> planNameMap = new HashMap<>();
                    Map<Long,String> productNameMap = new HashMap<>();
                    List<ProductPlan> plans = productPlanDALService.findAll();
                    List<Product> products = productDALService.findAll();
                    products.forEach(i->productNameMap.put(i.getId(),i.getName()));
                    plans.forEach(i->planNameMap.put(i.getId(),i.getName()));
                    Long planId ;
                    for(CustomerPolicyInfo item : policyInfos){
                        planId = item.getPlanId();
                        policyInfo = new PolicyInfo();
                        BeanUtils.copyProperties(item,policyInfo);
                        if(planId != null){
                            policyInfo.setPlanName(planNameMap.get(planId));
                            policyInfo.setNoPlanProduct(false);
                        }else{
                            policyInfo.setProductName(productNameMap.get(item.getProductId()));
                            policyInfo.setNoPlanProduct(true);
                        }
                        policyInfo.setPlatform(1);
                        policyInfoList.add(policyInfo);
                    }
                }
            }
        }
    }
}
