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

import com.google.common.base.Strings;
import com.yd.api.practitioner.service.PractitionerService;
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.practitioner.vo.sechedule.DeleteScheduleByIdResponseVO;
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.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.mapper.practitioner.AgAclLifePractitionerSalaryMapper;
import com.yd.dal.mapper.customer.AclPractitionerMapper;
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.SalaryDetailsSearchResponseVO;
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.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.math.BigDecimal;
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;
    @Autowired
    private PractitionerService practitionerService;
    @Autowired
    private AgAclLifePractitionerSalaryMapper practitionerSalaryMapper;
    @Autowired
    private N22PolicyService n22PolicyService;
    @Autowired
    private N22StaffService n22StaffService;
    @Autowired
    private N22SalaryService n22SalaryService;
    @Autowired
    private AclPractitionerMapper practitionerMapper;

    @Override
    public PolicyListQueryResponseVO policyListQuery(PolicyListQueryRequestVO requestVO) {
        PolicyListQueryResponseVO responseVO = new PolicyListQueryResponseVO();
        Long practitionerId = requestVO.getPractitionerId();
        Integer platform = requestVO.getPlatform();

        if (practitionerId != null) {
            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 practitionerIdEG = requestVO.getPractitionerIdEG();
        Long practitionerId = requestVO.getPractitionerId();
        Map<Long,PayScaleInfo> payScaleInfoMap = new HashMap<>();

        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()));

                PayScaleInfo payScaleInfo;
                Long 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());

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

        // 排序
        resultList.sort(Comparator.comparingLong(PayScaleInfo :: getMonDtlPeriod).reversed());
        responseVO.setPayScaleInfos(resultList);

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

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

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

            childList.add(SalaryDetails);
        }

        return result;
    }

    private void translateObj(List<AgAclLifePractitionerSalary> list, List<PayScaleInfo> resultList) {
        PayScaleInfo payScaleInfo;
        for (AgAclLifePractitionerSalary salary : list) {
            payScaleInfo = new PayScaleInfo();
            payScaleInfo.setMonShId(salary.getId());
            payScaleInfo.setPdfOssPath(salary.getPdfOssPath());
            payScaleInfo.setMonDtlPeriod(Long.valueOf(salary.getYearMonth()));
            payScaleInfo.setMonDtlAmount(salary.getPayableAmount().doubleValue());
            payScaleInfo.setMonDtlRAmount(salary.getNetAmount().doubleValue());

            resultList.add(payScaleInfo);
        }
    }

    @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();
        try {
            // 获取团队成员或被辅导人的practitionerId
            List<Long> practitionerIdList = practitionerService.getPractitionerIdList(practitionerId,1);

            List<TeamMemberDetail> dataList = aclPractitionerDALService.queryTeamMemberDetailList(practitionerIdList);

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

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

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