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

import com.google.common.base.Strings;
import com.yd.api.practitioner.service.PractitionerBasicInfoService;
import com.yd.api.practitioner.service.PractitionerService;
import com.yd.api.practitioner.vo.n22.QuerySalaryDetailRequestVO;
import com.yd.api.practitioner.vo.n22.QuerySalaryDetailResponseVO;
import com.yd.api.practitioner.vo.n22.SalaryDetail;
import com.yd.api.practitioner.vo.organization.*;
import com.yd.api.practitioner.vo.payscale.*;
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.practitioner.vo.subordinate.QueryTeamMemberDetailRequestVO;
import com.yd.api.practitioner.vo.subordinate.QueryTeamMemberDetailResponseVO;
import com.yd.api.practitioner.vo.subordinate.TeamMemberDetail;
import com.yd.api.result.CommonResult;
import com.yd.dal.entity.agms.fortune.WithdrawLabelInfo;
import com.yd.dal.entity.agms.fortune.WithdrawQueryInfo;
import com.yd.dal.entity.customer.AclCustomer;
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.AgAclLifePractitionerSalary;
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.entity.salary.AgAclSalary;
import com.yd.dal.mapper.practitioner.AgAclLifePractitionerSalaryMapper;
import com.yd.dal.mapper.salary.AgAclSalaryMapper;
import com.yd.dal.service.agms.AgmsFortuneDALService;
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.rmi.n22.common.utils.N22Utils;
import com.yd.rmi.n22.policy.pojo.policydetail.*;
import com.yd.rmi.n22.policy.pojo.policylist.PolicyInfoN22;
import com.yd.rmi.n22.policy.pojo.policylist.PolicyListQueryRequestBody;
import com.yd.rmi.n22.policy.service.N22PolicyService;
import com.yd.rmi.n22.salary.pojo.SalaryDetails;
import com.yd.rmi.n22.salary.pojo.SalaryDetailsSearchRequestBody;
import com.yd.rmi.n22.salary.pojo.SalaryDetailsSearchResponseBody;
import com.yd.rmi.n22.salary.pojo.SalaryDetailsSearchResponseVO;
import com.yd.rmi.n22.salary.pojo.searchstaffsalarydetails.Commission;
import com.yd.rmi.n22.salary.pojo.searchstaffsalarydetails.FirstYearPerformanceCommission;
import com.yd.rmi.n22.salary.pojo.searchstaffsalarydetails.OtherCommission;
import com.yd.rmi.n22.salary.pojo.searchstaffsalarydetails.RecommendSystemCommission;
import com.yd.rmi.n22.salary.pojo.searchstaffsalarydetails.RenewalYearPerformanceCommission;
import com.yd.rmi.n22.salary.pojo.searchstaffsalarydetails.SearchStaffSalaryDetailsRequestBody;
import com.yd.rmi.n22.salary.pojo.searchstaffsalarydetails.SearchStaffSalaryDetailsResponseBody;
import com.yd.rmi.n22.salary.pojo.searchstaffsalarydetails.SearchStaffSalaryDetailsResponseVO;
import com.yd.rmi.n22.salary.service.N22SalaryService;
import com.yd.rmi.n22.staff.pojo.GetStaffNewRequestBody;
import com.yd.rmi.n22.staff.pojo.GetStaffNewResponseVO;
import com.yd.rmi.n22.staff.pojo.Staff;
import com.yd.rmi.n22.staff.service.N22StaffService;
import com.yd.util.CommonUtil;
import com.yd.util.config.ZHBErrorConfig;
import org.apache.commons.beanutils.BeanPropertyValueEqualsPredicate;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

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

    private final static Logger logger = LoggerFactory.getLogger(PractitionerBasicInfoServiceImpl.class);

    @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;
    @Autowired
    private PractitionerService practitionerService;
    @Autowired
    private AgAclLifePractitionerSalaryMapper practitionerSalaryMapper;
    @Autowired
    private N22PolicyService n22PolicyService;
    @Autowired
    private N22StaffService n22StaffService;
    @Autowired
    private N22SalaryService n22SalaryService;
    @Autowired
    private AgmsFortuneDALService agmsFortuneDalService;
    @Autowired
    private AgAclSalaryMapper agAclSalaryMapper;
    @Override
    public PolicyListQueryResponseVO policyListQuery(PolicyListQueryRequestVO requestVO) {
        PolicyListQueryResponseVO responseVO = new PolicyListQueryResponseVO();
        Long practitionerId = requestVO.getPractitionerId();
        Integer platform = requestVO.getPlatform();

        if (practitionerId != null) {
            //等保调整
            List<AclCustomer> findByObjSortable = aclPractitionerDALService.getAclCustomers(practitionerId,null);
            if(null == findByObjSortable ){
                responseVO.setCommonResult(new CommonResult(false,ZHBErrorConfig.getErrorInfo("630028")));
                return responseVO;
            }

            String mobileNo = aclPractitionerDALService.findMobileNoByPractitionerId(practitionerId);
            if (!Strings.isNullOrEmpty(mobileNo) && mobileNo.length() == 11) {
                List<PolicyInfo> policyInfoList = new ArrayList<>();
                Integer time = requestVO.getTime();
                if (Integer.valueOf("1").equals(platform)) {
                    //1、线上
                    getPolicyListForYD(policyInfoList, practitionerId, time);
                } else {
                    //2、线下
//                    getPolicyListForEGolden(policyInfoList, mobileNo, time);
                    try {
                        getPolicyListFromN22(policyInfoList, mobileNo, time);
                    } catch (Exception e) {
                        e.printStackTrace();
                        responseVO.setCommonResult(new CommonResult(false, e.getMessage()));
                        return responseVO;
                    }
                }

                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;
    }

    private void getPolicyListFromN22(List<PolicyInfo> policyInfoList, String mobileNo, Integer time) throws Exception {

        // 1.根据手机号查询经纪人在N22系统的Agent_id
        GetStaffNewRequestBody getStaffNewRequestBody = new GetStaffNewRequestBody();
        getStaffNewRequestBody.setMobile(mobileNo);
        GetStaffNewResponseVO resp = n22StaffService.getStaffNew(getStaffNewRequestBody);
        if (!"查询成功".equals(resp.getResponseHead().getMessage())){
            throw new Exception("查询N22的Agent_id错误");
        }
        List<Staff> staffList = resp.getResponseBody().getStaff();
        if (staffList.size() == 0) {
            throw new Exception("查询N22的经纪人错误");
        }
        Staff staff = staffList.get(0);
        String agent_id = staff.getAgent_id();

        // 2.根据Agent_id查询N22中的保单列表
        PolicyListQueryRequestBody policyListQueryRequestBody = new PolicyListQueryRequestBody();
        policyListQueryRequestBody.setStaffInfo(agent_id);
        policyListQueryRequestBody.setMyPolicyType("2");
        policyListQueryRequestBody.setIsInsuredArray("1");
        // 根据查询时间范围获取查询开始时间和结束时间
        String startTime = null;
        String endTime = null;
        if (Integer.valueOf("1") == time) {
            startTime = CommonUtil.getBeginDayOfMonth();
            endTime = CommonUtil.getEndDayOfMonth();
        } else if (Integer.valueOf("3") == time) {
            startTime = CommonUtil.getStartOrEndDayOfQuarter(true);
            endTime = CommonUtil.getStartOrEndDayOfQuarter(false);
        } else if (Integer.valueOf("2") == time) {
            startTime = CommonUtil.getBeginDayOfYear();
            endTime = CommonUtil.getEndDayOfYear();
        } else if (Integer.valueOf("4") == time) {
            // 历史
            endTime = CommonUtil.getSpecifiedDayBefore(CommonUtil.getBeginDayOfYear());
        }

        policyListQueryRequestBody.setStarttime(startTime);
        policyListQueryRequestBody.setEndtime(endTime);

        com.yd.rmi.n22.policy.pojo.policylist.PolicyListQueryResponseVO policyListQueryResponseVO = n22PolicyService.policyList(policyListQueryRequestBody);

        if (!"查询成功".equals(policyListQueryResponseVO.getResponseHead().getMessage())){
            throw new Exception("查询N22经纪人保单列表错误");
        }
        List<PolicyInfoN22> policyList = policyListQueryResponseVO.getResponseBody().getPolicyList();

        this.translatePolicyInfoN22(policyList, policyInfoList);

    }

    private void translatePolicyInfoN22(List<PolicyInfoN22> policyList, List<PolicyInfo> policyInfoList) {
        for (PolicyInfoN22 item: policyList) {
            PolicyInfo policyInfo = new PolicyInfo();
            policyInfo.setPlatform(2);
            policyInfo.setOrderNo(item.getAppNum());
            policyInfo.setHolderName(item.getInsuranceName());
            policyInfo.setPlanName(item.getPolNameChn());
            policyInfo.setProductName(item.getProductName());
            policyInfo.setRelation_id(item.getRelationId());
            policyInfo.setPolicyNo(item.getPolicyNo());
            policyInfo.setOrderPrice(Double.valueOf(item.getPremium()));
            policyInfo.setOrderDate(item.getPolAppDate());

            policyInfoList.add(policyInfo);
        }
    }

    @Override
    public PolicyInfoQueryResponseVO policyInfoQuery(PolicyInfoQueryRequestVO requestVO) {
        PolicyInfoQueryResponseVO responseVO = new PolicyInfoQueryResponseVO();
        String orderNo = requestVO.getOrderNo();
        String policyNo = requestVO.getPolicyNo();
        String relation_id = requestVO.getRelation_id();

        if (!Strings.isNullOrEmpty(orderNo) || !Strings.isNullOrEmpty(policyNo)) {
            Integer platform = requestVO.getPlatform();
            platform = (platform == null) ? 1 : platform;
            if (platform == 2) {//N22
//                //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")));
//                }

                // 调用N22保单详情接口
                PolicyDetailQueryRequestBody policyInfoRequestBody = new PolicyDetailQueryRequestBody();
                policyInfoRequestBody.setPolicyNo(policyNo);
                policyInfoRequestBody.setRelation_id(relation_id);

                PolicyDetailQueryResponseVO policyDetailQueryResponseVO = n22PolicyService.policyInfo(policyInfoRequestBody);

                if (!"查询成功".equals(policyDetailQueryResponseVO.getResponseHead().getMessage())){
                    responseVO.setCommonResult(new CommonResult(true, "查询N22经纪人保单详情错误"));
                    return responseVO;
                }
                PolicyDetailQueryResponseBody policyDetail = policyDetailQueryResponseVO.getResponseBody();
                setResponseMessage(responseVO, policyDetail);
                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;
    }

    private void setResponseMessage(PolicyInfoQueryResponseVO responseVO, PolicyDetailQueryResponseBody policyDetail) {

        responseVO.setOrderNo(policyDetail.getQuotationNo());
        responseVO.setPolicyNo(policyDetail.getPolicyNo());
        responseVO.setOrderDate(policyDetail.getIssueDate());
        responseVO.setStartDate(policyDetail.getEffectiveDate());
        responseVO.setEndDate(policyDetail.getExpiryDate());
        responseVO.setTotalPrice(policyDetail.getPremium());
        responseVO.setStatus(N22Utils.getN22PolicyStatus(policyDetail.getPolicyStatus()));

        // 投保人信息
        HolderInfo holderInfo = new HolderInfo();
        PolicyHolderN22 holder = policyDetail.getPolicyHolder();
        holderInfo.setName(holder.getFirstName());
        holderInfo.setMobileNo(holder.getMobile().trim());
        holderInfo.setGender("1".equals(holder.getGender()) ? 1 : 2);
        holderInfo.setBirthDay(holder.getDateOfBirth());
        holderInfo.setAge(CommonUtil.getAge(CommonUtil.stringParseDate(holder.getDateOfBirth(),"yyyy-MM-dd")));

        IDInfo idInfo = new IDInfo();
        idInfo.setIdType(N22Utils.getN22IdType(holder.getIdType()));
        idInfo.setIdNo(holder.getIdNo());
        holderInfo.setIdInfo(idInfo);
        responseVO.setHolderInfo(holderInfo);
        // 被保人信息
        List<InsuredDetailN22> insureds = policyDetail.getInsureds();
        List<InsuredInfo> insuredInfos = new ArrayList<>();
        InsuredInfo insuredInfo;
        for (ParticipantN22 insured : insureds.get(0).getParticipants()) {
            // 2-被保人，3-受益人
            if ("2".equals(insured.getCustomerType())) {
                insuredInfo = new InsuredInfo();
                insuredInfo.setRelationType(N22Utils.getN22RelationType(insured.getIdType()));
                insuredInfo.setName(insured.getFirstName());
                insuredInfo.setMobileNo(insured.getMobile());
                insuredInfo.setGender("1".equals(insured.getGender()) ? 1 : 2);
                insuredInfo.setBirthDay(insured.getDateOfBirth());
                insuredInfo.setAge(CommonUtil.getAge(CommonUtil.stringParseDate(insured.getDateOfBirth(), "yyyy-MM-dd")));

                idInfo = new IDInfo();
                idInfo.setIdType(N22Utils.getN22IdType(insured.getIdType()));
                idInfo.setIdNo(insured.getIdNo());
                insuredInfo.setIdInfo(idInfo);

                insuredInfos.add(insuredInfo);
            }

        }

        responseVO.setInsuredInfos(insuredInfos);


//        responseVO.setPrice(CommonUtil.doubleFormat(orderPrice,2));
        ReferralInfo referralInfo = new ReferralInfo();
//        referralInfo.setReferralAmount(CommonUtil.doubleFormat(commission,2));
        responseVO.setReferralInfo(referralInfo);

        // 保障项目和总保费
        this.getPolicyFactorInfoAndPrice(insureds, responseVO);

    }

    private void getPolicyFactorInfoAndPrice(List<InsuredDetailN22> insureds, PolicyInfoQueryResponseVO responseVO) {

        List<PolicyFactorInfo> policyFactorInfoList= new ArrayList<>();

        BigDecimal price = BigDecimal.ZERO;
        ExtensionDataCoverage extensionData;

        if (CollectionUtils.isNotEmpty(insureds)) {
            List<CoverageN22> coverages = insureds.get(0).getCoverages();
            for (CoverageN22 coverage : coverages) {
                if (CollectionUtils.isNotEmpty(coverages)) {

                    extensionData = coverage.getExtensionData();
                    CoverageFee coverageFee = coverage.getCoverageFee();

                    // 赋值
                    PolicyFactorInfo policyFactorInfo = new PolicyFactorInfo();
                    policyFactorInfo.setPolicyType("寿险");
                    policyFactorInfo.setProductName(coverage.getCoverageName());

                    if (extensionData != null) {
                        policyFactorInfo.setInsuredAmount(extensionData.getSumInsured());
                        policyFactorInfo.setPayFrequency(extensionData.getInstallmentName());
                        String period = extensionData.getInstallment().substring(1);
                        policyFactorInfo.setPeriod(Integer.valueOf(period));
                    }

                    if (coverageFee != null) {
                        policyFactorInfo.setPremium(Double.valueOf(coverageFee.getApp()));
                        price = price.add(new BigDecimal(coverageFee.getApp()));
                    }
                    policyFactorInfoList.add(policyFactorInfo);
                }
            }
        }

        responseVO.setPolicyFactorInfos(policyFactorInfoList);
        responseVO.setPrice(price.doubleValue());
    }


    @Override
    public PayScaleQueryResponseVO payScaleListQuery(PayScaleQueryRequestVO requestVO) {
        PayScaleQueryResponseVO responseVO = new PayScaleQueryResponseVO();

        String isHistory = requestVO.getIsHistory();

        List<PayScaleInfo> resultList = new ArrayList<>();

        //如果是预览薪资单，则跳过权限校验
        if(!"AGMS".equals(requestVO.getPreFlag())){
            //等保调整
            List<AclCustomer> findByObjSortable = aclPractitionerDALService.getAclCustomers(requestVO.getPractitionerId(),null);
            if(null == findByObjSortable ){
                responseVO.setCommonResult(new CommonResult(false,ZHBErrorConfig.getErrorInfo("630028")));
                return responseVO;
            }
        }
        try {
            if ("0".equals(isHistory)) {
                // 查询本年
                resultList = this.queryNew(requestVO);
            } else if ("1".equals(isHistory)) {
                // 查询历史才需要执行
                resultList = this.historyEG(requestVO);
            } else {
                // 查询全部，把本年和历史集合合并到一起
                resultList = this.queryAll(requestVO);
            }
            responseVO.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));
            responseVO.setPayScaleInfos(resultList);

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

    private List<PayScaleInfo> queryNew(PayScaleQueryRequestVO requestVO) throws Exception {

        // 1.先查本地新基本法的薪资
        List<AgAclLifePractitionerSalary> list = practitionerSalaryMapper.queryListByPractitionerIdAndIsbasic(requestVO.getPractitionerId(), 1,requestVO.getIsActive());
        List<PayScaleInfo> salaryList = this.translateAgAclLifePractitionerSalaryToPayScaleInfo(list,requestVO.getPreFlag());

        // 2.再查N22
        List<PayScaleInfo> listN22 = this.queryPayScaleListFromN22(requestVO);

        // 3.合并结果集，先取new的，再取N22的
        Map<String, PayScaleInfo> map = new HashMap<>();
        String yearMonth = "";
        String year = "";
        String month = "";
        if (CollectionUtils.isNotEmpty(salaryList)) {
            for (PayScaleInfo newSalary : salaryList) {
                map.put(newSalary.getMonDtlPeriod(), newSalary);
            }
        }
        if (CollectionUtils.isNotEmpty(listN22)) {
            for (PayScaleInfo infoN22 : listN22) {
                year = infoN22.getYears() == null ? "" : infoN22.getYears();
                month = infoN22.getMonth() == null ? "" : infoN22.getMonth();
                yearMonth = this.getYearMonth(year, month);
                infoN22.setMonDtlPeriod(yearMonth);
                if (!map.containsKey(yearMonth)) {
                    map.put(yearMonth, infoN22);
                }
            }
        }
        ArrayList<PayScaleInfo> resultList = new ArrayList<>(map.values());
        // 排序
        resultList.sort(Comparator.comparing(PayScaleInfo::getMonDtlPeriod).reversed());

        return resultList;
    }

    private List<PayScaleInfo> translateAgAclLifePractitionerSalaryToPayScaleInfo(List<AgAclLifePractitionerSalary> newSalaryList,String preFlag) {
        List<PayScaleInfo> resultList = new ArrayList<>();
        PayScaleInfo payScaleInfo;
        String time;
        for (AgAclLifePractitionerSalary salary : newSalaryList) {
            payScaleInfo = new PayScaleInfo();
            payScaleInfo.setMonShId(salary.getId());
            payScaleInfo.setMonDtlPeriod(salary.getYearMonth());
            payScaleInfo.setMonDtlAmount(salary.getPayableAmount().doubleValue());
            payScaleInfo.setMonDtlRAmount(salary.getNetAmount().doubleValue());
            payScaleInfo.setIsBasic(salary.getIsBasic());
            payScaleInfo.setIsActive(salary.getIsActive());
            payScaleInfo.setPreFlag(preFlag);//AGMS预览标志
            time = payScaleInfo.getMonDtlPeriod();
            if (StringUtils.isNotBlank(time)) {
                payScaleInfo.setYears(time.substring(0, 4));
                payScaleInfo.setMonth(time.substring(4));
            }
            resultList.add(payScaleInfo);
        }

        return resultList;
    }

    private List<PayScaleInfo> queryAll(PayScaleQueryRequestVO requestVO) throws Exception {
        List<PayScaleInfo> listN22 = this.queryNew(requestVO);
        List<PayScaleInfo> historyEG = this.historyEG(requestVO);

        Map<String, PayScaleInfo> map = new HashMap<>();
        String yearMonth = "";
        String year = "";
        String month = "";
        for (PayScaleInfo infoEG : historyEG) {
            year = infoEG.getYears() == null ? "0" : infoEG.getYears();
            month = infoEG.getMonth() == null ? "0" : infoEG.getMonth();
            yearMonth = this.getYearMonth(year, month);
            infoEG.setMonDtlPeriod(yearMonth);
            map.put(yearMonth, infoEG);

        }
        for (PayScaleInfo infoN22 : listN22) {
            year = infoN22.getYears() == null ? "0" : infoN22.getYears();
            month = infoN22.getMonth() == null ? "0" : infoN22.getMonth();
            yearMonth = this.getYearMonth(year, month);
            infoN22.setMonDtlPeriod(yearMonth);
            if (!map.containsKey(yearMonth)) {
                map.put(yearMonth, infoN22);
            }
        }
        ArrayList<PayScaleInfo> resultList = new ArrayList<>(map.values());
        // 排序
        resultList.sort(Comparator.comparing(PayScaleInfo :: getMonDtlPeriod).reversed());

        return resultList;
    }

    private String getYearMonth(String year, String month) {
        String yearMonth = "";
        if (month.length() == 2) {
            yearMonth = year + "-" + month;

        } else if (month.length() == 1) {
            yearMonth = year + "-0" + month;
        }
        return yearMonth;
    }

    private List<PayScaleInfo> queryPayScaleListFromN22(PayScaleQueryRequestVO requestVO) {

        Long practitionerId = requestVO.getPractitionerId();
        String isHistory = requestVO.getIsHistory();

        String mobileNo = aclPractitionerDALService.findMobileNoByPractitionerId(practitionerId);
        Staff staff = n22StaffService.queryN22StaffByMobileNo(mobileNo);
        if (staff == null || StringUtils.isBlank(staff.getAgent_id())) {
            logger.error("未查询到N22LoginName");
            return null;
        }

        // 1.根据Agent_id当前经纪人的佣金明细
        SalaryDetailsSearchRequestBody salaryDetailsSearchRequestBody = new SalaryDetailsSearchRequestBody();
        salaryDetailsSearchRequestBody.setLoginName(staff.getAgent_id());
        salaryDetailsSearchRequestBody.setSearchType("1");
        salaryDetailsSearchRequestBody.setPaid_Status("3");
        if ("0".equals(isHistory)) {
            String beginDayOfYear = this.calculateDate(CommonUtil.getBeginDayOfYear());
            String endDayOfYear = this.calculateDate(CommonUtil.getEndDayOfYear());

            salaryDetailsSearchRequestBody.setStartDate(beginDayOfYear);
            salaryDetailsSearchRequestBody.setEndDate(endDayOfYear);
        }
        SalaryDetailsSearchResponseVO salaryDetailsSearchResponseVO = n22SalaryService.salaryDetailsSearch(salaryDetailsSearchRequestBody);

        if (!"查询成功".equals(salaryDetailsSearchResponseVO.getResponseHead().getMessage())){
            logger.error(salaryDetailsSearchResponseVO.getResponseHead().getMessage());
            return null;
        }
        List<SalaryDetails> salaryDetailsList = salaryDetailsSearchResponseVO.getResponseBody().getSalaryDetailsLIST();

        // list分组
        Map<String, List<SalaryDetails>> group = this.groupByCheckDate(salaryDetailsList);

        // 组装返回参数
        List<PayScaleInfo> resultList = new ArrayList<>();
        // 应发佣金
        Double monDtlAmount = 0D;
        // 实发佣金
        Double monDtlRAmount = 0D;
        // loginName等
        String loginName = null;
        String years = null;
        String month = null;
        String grade = "";
        for (String key : group.keySet()) {

            System.out.println("Key = " + key);

            List<SalaryDetails> list = group.get(key);
            if (CollectionUtils.isNotEmpty(list)) {
                monDtlAmount = list.get(0).getSumcommission();
                monDtlRAmount = list.get(0).getAfter_tax_comis();
                loginName = list.get(0).getLoginName();
                grade = list.get(0).getGrade();
                years = String.valueOf(list.get(0).getYear());
                month = String.valueOf(list.get(0).getMonth());

                PayScaleInfo payScaleInfo = new PayScaleInfo();
                payScaleInfo.setMonDtlAmount(monDtlAmount == null ? 0D : monDtlAmount);
                payScaleInfo.setMonDtlItem("实发薪水");
                payScaleInfo.setMonDtlRAmount(monDtlRAmount == null ? 0D : monDtlRAmount);
                payScaleInfo.setDrpTitleCode(grade == null ? "null" : grade);
                payScaleInfo.setMonDtlPeriod(key);
                payScaleInfo.setLoginName(loginName);
                payScaleInfo.setIsBasic("0");

                // 处理时间,作为接口/searchStaffSalaryDetails的查询入参
                if (StringUtils.isNotBlank(years) && StringUtils.isNotBlank(month)) {
                    this.handleYearsAndMonth(years, month, payScaleInfo);
                }

                resultList.add(payScaleInfo);
            }

        }

        resultList.sort(Comparator.comparing(PayScaleInfo :: getMonDtlPeriod).reversed());

        return resultList;
    }

    private void handleYearsAndMonth(String years, String month, PayScaleInfo payScaleInfo) {
        Integer mon = Integer.valueOf(month);
        Integer year = Integer.valueOf(years);
        if (mon == 11) {
            year = year + 1;
            mon = 1;
        } else if (mon == 12) {
            year = year + 1;
            mon = 2;
        } else {
            mon = mon + 2;
        }
        payScaleInfo.setYears(String.valueOf(year));
        payScaleInfo.setMonth(String.valueOf(mon));
    }

    private String calculateDate(String dateStr) {

        Date date = CommonUtil.stringParseDate(dateStr, "yyyy-MM-dd");
        Date result = CommonUtil.dateOperation(date, "SUB", "Mon", 2);
        String s = CommonUtil.dateParseString(result, "yyyy-MM-dd");

        System.out.println("看看业绩列表的查询时间");
        System.out.println(s);

        return s;
    }

    private List<PayScaleInfo> historyEG(PayScaleQueryRequestVO requestVO) {

        Long practitionerId = requestVO.getPractitionerId();

        List<PayScaleInfo> resultList =  aclPractitionerDALService.queryEGHistorySalaryPDFByPractitionerId(practitionerId);

        // 加入临时薪资表的数据
        List<AgAclLifePractitionerSalary> list = practitionerSalaryMapper.queryListByPractitionerId(practitionerId,requestVO.getIsActive());
        translateObj(list, resultList,requestVO.getPreFlag());

        // 排序
        resultList.sort(Comparator.comparing(PayScaleInfo :: getMonDtlPeriod).reversed());

        return resultList;
    }

    /**
     * 通过for循环逻辑，编程上会麻烦点，但是效率上高很多
     */
    private Map<String, List<SalaryDetails>> groupByCheckDate(List<SalaryDetails> salaryDetailsList) {
        Map<String, List<SalaryDetails>> result = new HashMap<String, List<SalaryDetails>>();
        String checkDate = "";
        for (SalaryDetails SalaryDetails : salaryDetailsList) {
            checkDate = SalaryDetails.getCheckDate();

            List<SalaryDetails> childList = result.get(checkDate);
            if (childList == null) {
                childList = new ArrayList<SalaryDetails>();
                result.put(checkDate, childList);
            }

            childList.add(SalaryDetails);
        }

        return result;
    }

    private void translateObj(List<AgAclLifePractitionerSalary> list, List<PayScaleInfo> resultList,String preFlag) {
        PayScaleInfo payScaleInfo;
        String time;
        for (AgAclLifePractitionerSalary salary : list) {
            payScaleInfo = new PayScaleInfo();
            payScaleInfo.setMonShId(salary.getId());
            payScaleInfo.setPdfOssPath(salary.getPdfOssPath());
            payScaleInfo.setMonDtlPeriod(salary.getYearMonth());
            payScaleInfo.setMonDtlAmount(salary.getPayableAmount().doubleValue());
            payScaleInfo.setMonDtlRAmount(salary.getNetAmount().doubleValue());
            payScaleInfo.setIsBasic(salary.getIsBasic());
            payScaleInfo.setIsActive(salary.getIsActive());
            payScaleInfo.setPreFlag(preFlag);
            resultList.add(payScaleInfo);
        }

        for (PayScaleInfo info : resultList) {
            if (StringUtils.isNotBlank(info.getMonDtlPeriod())) {
                time = info.getMonDtlPeriod();
                info.setYears(time.substring(0, 4));
                info.setMonth(time.substring(4));
            }
        }
    }

    @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;
    }

    @Override
    public QueryTeamMemberDetailResponseVO queryTeamMemberDetail(QueryTeamMemberDetailRequestVO requestVO) {
        QueryTeamMemberDetailResponseVO resp = new QueryTeamMemberDetailResponseVO();
        Long practitionerId = requestVO.getPractitionerId();
        String systemType = requestVO.getSystemType();
        try {

            // 获取团队成员或被辅导人的practitionerId
            List<Long> practitionerIdList =  new ArrayList<>();
            if(null != requestVO.getSId()){
                practitionerIdList = practitionerService.getPractitionerIdBySidList(requestVO.getSId(),systemType,1);
            }else{
                //等保调整
                List<AclCustomer> findByObjSortable = aclPractitionerDALService.getAclCustomers(practitionerId,1L);
                if(null == findByObjSortable ){
                    resp.setCommonResult(new CommonResult(false,ZHBErrorConfig.getErrorInfo("630028")));
                    return resp;
                }
                practitionerIdList = practitionerService.getPractitionerIdList(practitionerId,1);
            }
            List<TeamMemberDetail> dataList = aclPractitionerDALService.queryTeamMemberDetailList(practitionerIdList);

            List<TeamMemberDetail> s1DataList = new ArrayList<>();
            List<TeamMemberDetail> s2DataList = new ArrayList<>();
            List<TeamMemberDetail> s3DataList = new ArrayList<>();

            List<TeamMemberDetail> groupList  = new ArrayList<>();
            List<TeamMemberDetail> teamList =  new ArrayList<>();
            List<TeamMemberDetail> teamMemberList =  new ArrayList<>();


            BeanPropertyValueEqualsPredicate predicatePackage;

            //根据体系筛选出对应的经纪人信息,根据getSystemType分组
            if(null != dataList && dataList.size() > 0){
                for(TeamMemberDetail teamMemberDetail:dataList){
                    StringBuilder sb = new StringBuilder();
                    if(StringUtils.isNotBlank(teamMemberDetail.getBranch())){
                        sb.append(teamMemberDetail.getBranch());
                    }
                    if(StringUtils.isNotBlank(teamMemberDetail.getDeptName())){
                        sb.append("-");
                        sb.append(teamMemberDetail.getDeptName());
                    }
                    if(StringUtils.isNotBlank(teamMemberDetail.getS3system())){
                        sb.append("-");
                        sb.append(teamMemberDetail.getS3system());
                    }
                    if(StringUtils.isNotBlank(teamMemberDetail.getS2system())){
                        sb.append("-");
                        sb.append(teamMemberDetail.getS2system());
                    }
                    if(StringUtils.isNotBlank(teamMemberDetail.getS1system())){
                        sb.append("-");
                        sb.append(teamMemberDetail.getS1system());
                    }
                    teamMemberDetail.setAllSystemName(sb.toString());
                    if("S1".equals(teamMemberDetail.getSystemType())){
                        s1DataList.add(teamMemberDetail);
                    }
                    if("S2".equals(teamMemberDetail.getSystemType())){
                        s2DataList.add(teamMemberDetail);
                    }
                    if("S3".equals(teamMemberDetail.getSystemType())){
                        s3DataList.add(teamMemberDetail);
                    }
                }
                resp.setSystemName(dataList.get(0).getSystem());
            }
            //查询当前的经纪人信息
            //1，根据组织信息查询经纪人
            if(StringUtils.isNotBlank(systemType)){
                if("S2".equals(systemType)){
                    if(null != s1DataList){
                        commFor(s1DataList, teamMemberList);
                    }
                    //没有团队长
                    getTeamMemberDetails(s1DataList,teamMemberList,"1");
                    groupList.addAll(s2DataList);
                }
                //如果是s1 直接显示所有
                if("S1".equals(systemType)){
                    groupList.addAll(dataList);
                }
            }else {
                predicatePackage = new BeanPropertyValueEqualsPredicate("practitionerId", practitionerId);
                teamList = (List<TeamMemberDetail>) CollectionUtils.select(dataList, predicatePackage);

                //根据职级进行数据筛选
                if (null != teamList && teamList.size() > 0) {
                    if ("S2".equals(teamList.get(0).getPractitionerLevel())) {
                        //1获取当前经纪人所在的团队信息
                        commFor(s1DataList, teamMemberList);
                        //2当前团队没有团长，根据体系id去重，只显示一个组织
                        getTeamMemberDetails(s1DataList,teamMemberList,"1");
                        groupList.addAll(s2DataList);
                    } else if ("S3".equals(teamList.get(0).getPractitionerLevel())) {
                        // 如果S1不是直属S3，则不在S3下显示
                        for (TeamMemberDetail teamMemberDetail : s1DataList) {
                            if(StringUtils.isNotBlank(teamMemberDetail.getS2system())){
                                continue;
                            }
                            List<TeamMemberDetail> arrayList = new ArrayList<>();
                            arrayList.add(teamMemberDetail);
                            commFor(arrayList, teamMemberList);
                            getTeamMemberDetails(arrayList,teamMemberList,"1");
                        }

                        commFor(s2DataList, teamMemberList);
                        getTeamMemberDetails(s2DataList,teamMemberList,"2");
                        groupList.addAll(s3DataList);

                    } else if ("S1".equals(teamList.get(0).getPractitionerLevel())) {
                        groupList.addAll(dataList);
                    }
                    resp.setSystemName(teamList.get(0).getSystem());
                }
                if(groupList == null || groupList.size() == 0){
                    groupList.addAll(dataList);
                }
            }
            resp.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));
            //把被育成人也添加进来
            practitionerIdList =  new ArrayList<>();
            practitionerIdList.add(practitionerId);
            List<TeamMemberDetail> raiseList = aclPractitionerDALService.queryTeamMemberDetailRaiseList(practitionerIdList);
            teamMemberList.addAll(raiseList);
            List<TeamMemberDetail> lastList = new ArrayList<>();
            getTeamMemberDetails(teamMemberList,lastList,"2");

            //排序
            lastList.sort(Comparator.comparing(TeamMemberDetail::getSystemType).reversed());
            Collections.sort(groupList,new Comparator<TeamMemberDetail>() {
                @Override
                public int compare(TeamMemberDetail o1, TeamMemberDetail o2) {
                    if(o2.getPractitionerLevel() == null){
                       return  -1;
                    }
                    if(o1.getPractitionerLevel() == null){
                        return  -1;
                    }
                    return (o2.getPractitionerLevel()).toString().compareTo(o1.getPractitionerLevel().toString());
                }
            });
            resp.setTeamMemberDetail(groupList);
            resp.setTeamMemberList(lastList);

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

    //获取当前经纪人所在的团队信息
    private void commFor(List<TeamMemberDetail> s1DataList, List<TeamMemberDetail> teamMemberList) {
        for (TeamMemberDetail teamMemberDetail : s1DataList) {
            if (null != teamMemberDetail.getOwnerPractitionerId() && teamMemberDetail.getOwnerPractitionerId().longValue() == teamMemberDetail.getPractitionerId().longValue()) {
                teamMemberList.add(teamMemberDetail);
            }
        }
    }

    //没有团队长的组织 根据体系id去重，只显示一个组织
    private void getTeamMemberDetails(List<TeamMemberDetail> s1DataList,List<TeamMemberDetail> teamMemberList,String flag) {
        if(teamMemberList == null || teamMemberList.size() == 0 || "2".equals(flag)){
            List<TeamMemberDetail> list = s1DataList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
                    () -> new TreeSet<>(Comparator.comparing(TeamMemberDetail::getSId))), ArrayList::new));
            teamMemberList.addAll(list);
        }

    }

    @Override
    public QuerySalaryDetailResponseVO querySalaryDetail(QuerySalaryDetailRequestVO requestVO) {
        QuerySalaryDetailResponseVO responseVO = new QuerySalaryDetailResponseVO();
        //如果是预览薪资单，则跳过权限校验
        if(!"AGMS".equals(requestVO.getPreFlag())){
            //等保调整
            Long practitionerId = requestVO.getPractitionerId();
            if (null != practitionerId) {
                List<AclCustomer> findByObjSortable = aclPractitionerDALService.getAclCustomers(practitionerId,null);
                if(null == findByObjSortable ){
                    responseVO.setCommonResult(new CommonResult(false,ZHBErrorConfig.getErrorInfo("630028")));
                    return responseVO;
                }
            }
        }

        // isBasic为0时查询N22，为1时查询本地数据库
        if ("1".equals(requestVO.getIsBasic())) {
            this.querySalaryDetail(requestVO, responseVO);
        } else {
            this.querySalaryDetailFromN22(requestVO, responseVO);
        }

        return responseVO;
    }

    private void querySalaryDetail(QuerySalaryDetailRequestVO requestVO, QuerySalaryDetailResponseVO responseVO) {
        Long practitionerId = requestVO.getPractitionerId();
        if (null != practitionerId) {
            String years = requestVO.getYears();
            String month = requestVO.getMonth();
            String payoutYearmonth = "";
            if (month.length() == 2) {
                payoutYearmonth = years + month;

            } else if (month.length() == 1) {
                payoutYearmonth = years + "0" + month;
            }

            AgAclSalary agAclSalary = new AgAclSalary();
            agAclSalary.setPractitionerId(practitionerId);
            agAclSalary.setYearMonth(payoutYearmonth);
            List<AgAclSalary> newSalaryList = agAclSalaryMapper.queryByRecord(agAclSalary);

            BigDecimal abc = BigDecimal.ZERO;
            BigDecimal d = BigDecimal.ZERO;
            for (AgAclSalary item : newSalaryList) {
                if (null != item.getAmount()) {
                    abc = abc.add(item.getAmount());
                }
            }
            responseVO.setAbc(abc.toString());
            // 202109开始的手工录入薪资单的保单明细pdf
            String pdfOssPath = null;
            // 税额
            AgAclLifePractitionerSalary lifePractitionerSalary = new AgAclLifePractitionerSalary();
            lifePractitionerSalary.setPractitionerId(practitionerId);
            lifePractitionerSalary.setYearMonth(payoutYearmonth);
            lifePractitionerSalary.setIsActive(requestVO.getIsActive());
            List<AgAclLifePractitionerSalary> agAclLifePractitionerSalarylist = practitionerSalaryMapper.queryByRecord(lifePractitionerSalary);
            if (CollectionUtils.isNotEmpty(agAclLifePractitionerSalarylist)) {
                d = agAclLifePractitionerSalarylist.get(0).getTaxoutAmount();
                pdfOssPath = agAclLifePractitionerSalarylist.get(0).getPdfOssPath();
            }
            responseVO.setD(d.toString());
            // 本期实领
            BigDecimal abc_d = abc.subtract(d);
            // list
            List<SalaryDetail> list = new ArrayList<>();
            for (AgAclSalary item : newSalaryList) {
                SalaryDetail target = new SalaryDetail();
                target.setSalaryName(item.getSalaryName());
                target.setCommission(item.getAmount().doubleValue());
                target.setSalaryType(item.getSalaryType());
                target.setSalaryCode(item.getSalaryCode());
                target.setAfter_tax_comis(abc_d.doubleValue());
                target.setPdfOssPath(pdfOssPath);
                list.add(target);
            }
            responseVO.setList(list);

        } else {
            responseVO.setCommonResult(new CommonResult(false, ZHBErrorConfig.getErrorInfo("820001")));
        }
    }

    private void querySalaryDetailFromN22(QuerySalaryDetailRequestVO requestVO, QuerySalaryDetailResponseVO responseVO) {
        // 1.检查请求参数
        if (StringUtils.isBlank(requestVO.getYears())||StringUtils.isBlank(requestVO.getMonth())) {
            responseVO.setCommonResult(new CommonResult(false, "查询年月不能为空"));
        }
        // 2.查询佣金和税的接口
        SalaryDetailsSearchRequestBody salaryDetailsSearchRequestBody = new SalaryDetailsSearchRequestBody();
        this.handleDateParams(salaryDetailsSearchRequestBody, requestVO);
        salaryDetailsSearchRequestBody.setLoginName(requestVO.getAgent_id());
        salaryDetailsSearchRequestBody.setSearchType("1");
        salaryDetailsSearchRequestBody.setPaid_Status("3");
        salaryDetailsSearchRequestBody.setCheckStatus("1");

        SalaryDetailsSearchResponseVO salaryDetailsSearchResponseVO = n22SalaryService.salaryDetailsSearch(salaryDetailsSearchRequestBody);

        // 3.组装前端数据
        if ("查询成功".equals(salaryDetailsSearchResponseVO.getResponseHead().getMessage())) {

            SalaryDetailsSearchResponseBody salaryDetails = salaryDetailsSearchResponseVO.getResponseBody();
            this.createQuerySalaryDetailResponseVO(responseVO, salaryDetails);
            responseVO.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));

        } else {
            responseVO.setCommonResult(new CommonResult(false, ZHBErrorConfig.getErrorInfo("820001")));
        }
    }

    private void handleDateParams(SalaryDetailsSearchRequestBody salaryDetailsSearchRequestBody, QuerySalaryDetailRequestVO requestVO) {
        int year = Integer.valueOf(requestVO.getYears());
        int mon = Integer.valueOf(requestVO.getMonth());
        if (mon == 1) {
            year = year - 1;
            mon = 11;
        } else if (mon == 2) {
            year = year - 1;
            mon = 12;
        } else {
            mon = mon - 2;
        }

        String curDate = "";
        if (mon > 10) {
            curDate = year + "-" + mon + "-01";

        } else {
            curDate = year + "-0" + mon + "-01";
        }
        salaryDetailsSearchRequestBody.setStartDate(curDate);
        salaryDetailsSearchRequestBody.setEndDate(curDate);
    }

    @Override
    public SearchStaffSalaryDetailsResponseBody searchStaffSalaryDetails(SearchStaffSalaryDetailsRequestBody requestVO) {

        SearchStaffSalaryDetailsResponseBody responseBody = new SearchStaffSalaryDetailsResponseBody();
        responseBody.setCommonResult(new CommonResult(false, ZHBErrorConfig.getErrorInfo("820001")));

        // 检查请求参数
        if (StringUtils.isBlank(requestVO.getYears())||StringUtils.isBlank(requestVO.getMonth())) {
            responseBody.setCommonResult(new CommonResult(false, "查询年月不能为空"));
            return responseBody;
        }
        //如果是预览薪资单，则跳过权限校验
        if(!"AGMS".equals(requestVO.getPreFlag())){
            //等保调整
            List<AclCustomer> findByObjSortable = aclPractitionerDALService.getAclCustomers(requestVO.getPractitionerId(),null);
            if(null == findByObjSortable ){
                responseBody.setCommonResult(new CommonResult(false,ZHBErrorConfig.getErrorInfo("630028")));
                return responseBody;
            }
        }

        if ("1".equals(requestVO.getIsBasic())) {
            //所有的数据都从银盾获取
            this.queryYdSalaryDetails(requestVO, responseBody);
            // 查询银盾在线佣金的保单列表
            this.queryYdOnlineCommission(requestVO, responseBody);
            responseBody.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));
        } else if ("0".equals(requestVO.getIsBasic())){
            // 调N22接口
            SearchStaffSalaryDetailsResponseVO searchStaffSalaryDetailsResponseVO = n22SalaryService.searchStaffSalaryDetails(requestVO);
            if ("查询成功".equals(searchStaffSalaryDetailsResponseVO.getResponseHead().getMessage())) {
                responseBody = searchStaffSalaryDetailsResponseVO.getResponseBody();
                // 查询银盾在线佣金的保单列表
                this.queryYdOnlineCommission(requestVO, responseBody);
                responseBody.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));

            }
        }
        return responseBody;
    }

    //所有的数据都从银盾获取
    private void queryYdSalaryDetails(SearchStaffSalaryDetailsRequestBody requestVO, SearchStaffSalaryDetailsResponseBody responseBody) {
        List<Commission> c01List = new ArrayList<>();
        List<Commission> c02List = new ArrayList<>();
        List<Commission> c03List = new ArrayList<>();
        List<Commission> c04List = new ArrayList<>();
        List<Commission> c05List = new ArrayList<>();
        List<RenewalYearPerformanceCommission> c06List = new ArrayList<>();
        List<RenewalYearPerformanceCommission> c07List = new ArrayList<>();
        List<Commission> c08List = new ArrayList<>();
        List<RenewalYearPerformanceCommission> c09List = new ArrayList<>();
        List<RenewalYearPerformanceCommission> c10List = new ArrayList<>();
        List<OtherCommission> otherCommissionLis = new ArrayList<>();
        WithdrawQueryInfo info = new WithdrawQueryInfo();
        info.setPractitionerId(requestVO.getPractitionerId());
        info.setPayoutYearmonth(this.getPayoutYearmonth(requestVO));
        List<WithdrawLabelInfo> list = agmsFortuneDalService.salaryPolicyNoDetails(info);
        if(null != list && list.size() >0){
            for(WithdrawLabelInfo withdrawLabelInfo : list){
                if ("C01,C02,C03,C04,C05,C08,".indexOf(withdrawLabelInfo.getDropOptionCode()+",") != -1) {
                    Commission commission = new Commission();
                    commission.setCommission(withdrawLabelInfo.getReferralAmount().doubleValue());//佣金
                    commission.setCustomer(withdrawLabelInfo.getInsurerName());//保险公司
                    commission.setEffectiveDate(withdrawLabelInfo.getEffectiveStartDate());//生效时间
                    commission.setFYC_RYC(withdrawLabelInfo.getFycAmount().doubleValue());
                    commission.setInsurance_Cust(withdrawLabelInfo.getInsuredName());//投保人
                    commission.setPol_name_chn(withdrawLabelInfo.getProductName());//产品名称
                    commission.setPolicyno(withdrawLabelInfo.getPolicyNo());//保单号
                    commission.setRate(withdrawLabelInfo.getFycRate().intValue());//职佣率
                    commission.setSalesCommissionRate(withdrawLabelInfo.getCommissionRate().doubleValue());
                    commission.setSaleSystem(withdrawLabelInfo.getSubordinateSystemName());//体系
                    commission.setYearPREMIUM(withdrawLabelInfo.getOrderPrice().intValue());//保费
                    commission.setCalculationFormula(withdrawLabelInfo.getCalculationFormula());//佣金计算公式
                    commission.setSalestaff(withdrawLabelInfo.getPractitionerName());//经纪人名称
                    commission.setSalaryCode(transformationType(withdrawLabelInfo.getDropOptionCode()));
                    //C02:续年度直接销售佣金;C03:续年度销售加码奖金;C04:月度销售加码奖金; 没有orderid
                    if ("C02".equals(withdrawLabelInfo.getDropOptionCode())) {
                        c02List.add(commission);
                    }
                    if ("C03".equals(withdrawLabelInfo.getDropOptionCode())) {
                        c03List.add(commission);
                    }
                    if ("C04".equals(withdrawLabelInfo.getDropOptionCode())) {
                        c04List.add(commission);
                    }
                    //C01:直接销售拥金;
                    if ("C01".equals(withdrawLabelInfo.getDropOptionCode())) {
                        c01List.add(commission);
                    }
                    //C05:推荐奖金; 个人的有orderid  团体的无
                    if ("C05".equals(withdrawLabelInfo.getDropOptionCode())) {
                        c05List.add(commission);
                    }
                    //C08:团队管理绩效达标奖金; 当前经纪人体系的所有保单
                    if ("C08".equals(withdrawLabelInfo.getDropOptionCode())) {
                        c08List.add(commission);
                    }
                }

                //C07:间接辅导岗位津贴;C06:直接辅导岗位津贴;C09:育成奖金; 被育成体系的所有保单;C10:团队长辅导津贴
                if ("C06,C07,C09,C10,".indexOf(withdrawLabelInfo.getDropOptionCode()+",") != -1) {
                    RenewalYearPerformanceCommission renewalYearPerformanceCommission = new RenewalYearPerformanceCommission();
                    renewalYearPerformanceCommission.setComments(withdrawLabelInfo.getRemark());
                    renewalYearPerformanceCommission.setCommission(String.valueOf(withdrawLabelInfo.getReferralAmount()));
                    renewalYearPerformanceCommission.setRate(String.valueOf(withdrawLabelInfo.getFycRate()));
                    renewalYearPerformanceCommission.setFYC_RYC(String.valueOf(withdrawLabelInfo.getFycAmount()));
                    renewalYearPerformanceCommission.setSaleSystem(withdrawLabelInfo.getSubordinateSystemName());
                    renewalYearPerformanceCommission.setCalculationFormula(withdrawLabelInfo.getCalculationFormula());//佣金计算公式
                    renewalYearPerformanceCommission.setSalaryCode(transformationType(withdrawLabelInfo.getDropOptionCode()));

                    if ("C06".equals(withdrawLabelInfo.getDropOptionCode())) {
                        c06List.add(renewalYearPerformanceCommission);
                    }
                    if ("C07".equals(withdrawLabelInfo.getDropOptionCode())) {
                        c07List.add(renewalYearPerformanceCommission);
                    }
                    if ("C09".equals(withdrawLabelInfo.getDropOptionCode())) {
                        c09List.add(renewalYearPerformanceCommission);
                    }
                    if ("C10".equals(withdrawLabelInfo.getDropOptionCode())) {
                        c10List.add(renewalYearPerformanceCommission);
                    }
                }

                //C99:其他,C98:公司激励奖金,C97:其它税前加扣款,C96:加码奖金,C95:季度奖金,C94,银盾在线佣金
                if ("C99,C94,C95,C96,C97,C98,".indexOf(withdrawLabelInfo.getDropOptionCode()+",") != -1) {
                    OtherCommission otherCommission = new OtherCommission();
                    otherCommission.setComments(withdrawLabelInfo.getRemark());
                    otherCommission.setCommission(String.valueOf(withdrawLabelInfo.getReferralAmount().doubleValue()));
                    otherCommission.setCommissionName(withdrawLabelInfo.getCommissionType());
                    otherCommission.setWithdrawedId(withdrawLabelInfo.getWithdrawId());
                    otherCommission.setCalculationFormula(withdrawLabelInfo.getCalculationFormula());//佣金计算公式
                    otherCommission.setSalaryCode(transformationType(withdrawLabelInfo.getDropOptionCode()));
                    otherCommissionLis.add(otherCommission);
                }
            }

        }

        //1,首年度销售佣金 C01
        responseBody.setFristYearCommissionList(c01List);
        //2,续年度销售佣金 C02
        responseBody.setRenewalYearCommissionList(c02List);//续年度直接销售佣金
        responseBody.setContinuedAnnualSalesBonusList(c03List);//续年度销售加码奖金
        responseBody.setMonthlySalesAddWeightList(c04List);//月度销售加码奖金
        //3,首年度辅导奖金 暂时没有
        responseBody.setFristYearCoachCommissionList(null);
        //4,续年度辅导奖金 暂时没有
        responseBody.setRenewalYearCoachCommissionList(null);
        //5,首年度绩效奖金 暂时没有
        responseBody.setFirstYearPerformanceCommissionList(null);
        //6,续年度绩效奖金 暂时没有
        responseBody.setRenewalYearPerformanceCommissionList(null);
        responseBody.setDirectCounselingList(c06List);//直接辅导岗位津贴
        responseBody.setIndirectCounselingList(c07List);//间接辅导岗位津贴
        responseBody.setBreedingBonusList(c09List);//育成奖金
        responseBody.setTLCoachingAllowanceList(c10List);//团队长辅导津贴

        //7,推介奖金 C05 个人的有orderid
        responseBody.setRecommendCommissionList(c05List);
        //8,体系推介奖金  C05 体系的的有orderid
        responseBody.setRecommendSystemCommissionList(null);
        //9,特别管理奖金
        responseBody.setSpecialManagementCommissionList(null);
        responseBody.setFycMeritsInfoList(c08List);//C08 团队管理绩效达标奖金
        //10, 其他
        //    * 10.其它税前加扣款-》备注
        //   * 11.公司激励奖金-》备注
        //   * 12.加码奖金-》备注
        //   * 13.季度奖金-》备注
        //   * 14.银盾在线佣金-》H5
        responseBody.setOtherCommissionList(otherCommissionLis);

    }

    /**
     * 码值处理
     *
     */
    private String transformationType(String commissionType) {
        //C01:直接销售拥金;
        if ("C01".equals(commissionType)) {
            return "A-001";
        }
        //C02:续年度直接销售佣金;
        if ("C02".equals(commissionType)) {
            return "A-002";
        }
        //C03:续年度销售加码奖金;
        if ("C03".equals(commissionType)) {
            return "A-005";
        }
        //C04:月度销售加码奖金; 没有orderid
        if ("C04".equals(commissionType)) {
            return "A-003";
        }
        //C05:推荐奖金; 个人的有orderid  团体的无
        if ("C05".equals(commissionType)) {
            return "B-004";
        }
        //C06:直接辅导岗位津贴;
        if ("C06".equals(commissionType)) {
            return "B-008";
        }
        //C07:间接辅导岗位津贴;
        if ("C07".equals(commissionType)) {
            return "B-009";
        }
        //C08:团队管理绩效达标奖金; 当前经纪人体系的所有保单
        if ("C08".equals(commissionType)) {
            return "B-006";
        }
        //C09:育成奖金; 被育成体系的所有保单
        if ("C09".equals(commissionType)) {
            return "B-010";
        }
        //C10:团队长辅导津贴
        if ("C10".equals(commissionType)) {
            return "B-011";
        }

        //C99:其他
        if ("C99".equals(commissionType)) {
            return "C-006";
        }

        //公司激励奖金
        if ("C98".equals(commissionType)) {
            return "C-001";
        }
        //其它税前加扣款
        if ("C97".equals(commissionType)) {
            return "C-002";
        }
        //加码奖金
        if ("C96".equals(commissionType)) {
            return "C-003";
        }
        //季度奖金
        if ("C95".equals(commissionType)) {
            return "C-004";
        }
        //银盾在线佣金
        if ("C94".equals(commissionType)) {
            return "C-005";
        }
        return null;
    }

    private void queryYdOnlineCommission(SearchStaffSalaryDetailsRequestBody requestVO, SearchStaffSalaryDetailsResponseBody responseBody) {
        WithdrawQueryInfo info = new WithdrawQueryInfo();
        info.setPractitionerId(requestVO.getPractitionerId());
        info.setPayoutYearmonth(this.getPayoutYearmonth(requestVO));
        info.setCommissionPayoutStatus(Long.valueOf("4"));
        List<WithdrawLabelInfo> withdraws = agmsFortuneDalService.transformForWithdrawLabel(info);

        // 有银盾在线佣金
        if (CollectionUtils.isNotEmpty(withdraws)) {
            Long  withdrawId = withdraws.get(0).getWithdrawId();

            List<OtherCommission> otherCommissionList = responseBody.getOtherCommissionList();
            if (CollectionUtils.isNotEmpty(otherCommissionList)) {
                for (OtherCommission otherCommission : otherCommissionList) {
                    // 此项为银盾在线佣金
                    if ("12C24EDF-83D7-081C-AE2C-085031C4DCAF".equals(otherCommission.getProject_Id())) {
                        //获取withdrewId
                        otherCommission.setWithdrawedId(withdrawId);
                    }
                }
            } else {
                // 手工录入薪资单，List为空
                otherCommissionList = new ArrayList<>();
                OtherCommission otherCommission = new OtherCommission();
                otherCommission.setWithdrawedId(withdrawId);
                otherCommission.setProject_Id("12C24EDF-83D7-081C-AE2C-085031C4DCAF");

                otherCommissionList.add(otherCommission);
                responseBody.setOtherCommissionList(otherCommissionList);
            }
        }

    }

    private String getPayoutYearmonth(SearchStaffSalaryDetailsRequestBody requestVO) {
        String years = requestVO.getYears();
        String month = requestVO.getMonth();
        String payoutYearmonth = "";
        if (month.length() == 2) {
            payoutYearmonth = years + "-" + month;

        } else if (month.length() == 1) {
            payoutYearmonth = years + "-0" + month;
        }
        return payoutYearmonth;
    }

    private QuerySalaryDetailResponseVO createQuerySalaryDetailResponseVO(
            QuerySalaryDetailResponseVO responseVO, SalaryDetailsSearchResponseBody staffSalaryDetails) {

        List<SalaryDetail> list = new ArrayList<>();

        BigDecimal abc = BigDecimal.ZERO;
        String d = "";

        List<SalaryDetails> salaryDetailsList = staffSalaryDetails.getSalaryDetailsLIST();
        // 过滤掉销售业绩是0的元素
        salaryDetailsList = salaryDetailsList.stream()
                .filter((SalaryDetails i) -> !Double.valueOf("0").equals(i.getCommission())
                )
                .collect(Collectors.toList());

        // 1.只取SalaryType=业绩佣金和加扣款项的元素
        salaryDetailsList = salaryDetailsList.stream()
                .filter((SalaryDetails i) ->
                        ("业绩佣金".equals(i.getSalaryType())
                                || "加扣款项".equals(i.getSalaryType())
                        )
                )
                .collect(Collectors.toList());

        if (CollectionUtils.isNotEmpty(salaryDetailsList)) {
            // 代扣个人所得税
            Double total_tax = 0D;
            for (SalaryDetails item : salaryDetailsList) {
                if (!Double.valueOf(0D).equals(item.getTotal_tax())) {
                    total_tax = item.getTotal_tax();
                    break;
                }
            }
            responseVO.setD(String.valueOf(total_tax));
            // 税后佣金
            Double after_tax_comis = salaryDetailsList.get(0).getAfter_tax_comis();

            // 预扣率
            String rate = this.getRate(salaryDetailsList.get(0).getTotal_commission());
            responseVO.setRate(rate);
            // 佣金合计
            for (SalaryDetails item : salaryDetailsList) {
                abc = abc.add(BigDecimal.valueOf(item.getCommission()));
            }
            responseVO.setAbc(abc.toString());
            // list
            for (SalaryDetails item : salaryDetailsList) {
                SalaryDetail target = new SalaryDetail();
                BeanUtils.copyProperties(item, target);
                target.setAfter_tax_comis(after_tax_comis);
                list.add(target);
            }
            responseVO.setList(list);
        }

        return responseVO;
    }

    private String getRate(Double total_commission) {
        String rate = "0";
        if (total_commission == null) {
            return rate;
        }

        long l = (long) (total_commission * 100);
        if (0 < l && l <= 3600000) {
            rate = "3";
        } else if (3600000 < l && l <= 14400000) {
            rate = "10";
        } else if (14400000 < l && l <= 30000000) {
            rate = "20";
        } else if (30000000 < l && l <= 42000000) {
            rate = "25";
        } else if (42000000 < l && l <= 66000000) {
            rate = "30";
        } else if (66000000 < l && l <= 96000000) {
            rate = "35";
        } else {
            rate = "45";
        }
        return rate;
    }

    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){
            Long shIdMain = payScaleInfoMain.getMonShId();
            Long 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);
                    }
                }
            }
        }
    }
}
