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

import com.google.common.base.Strings;
import com.yd.api.agms.service.AgmsDashboardService;
import com.yd.api.agms.vo.dashboard.*;
import com.yd.api.result.CommonResult;
import com.yd.dal.entity.agms.dashboard.StatisticsOpportunityInfo;
import com.yd.dal.entity.agms.dashboard.StatisticsPEPInfo;
import com.yd.dal.entity.customer.practitioner.PractitionerRankInfo;
import com.yd.dal.entity.meta.MdDropOptions;
import com.yd.dal.service.agms.AgmsDashboardDALService;
import com.yd.dal.service.meta.MdDropOptionsDALService;
import com.yd.rmi.n22.salary.pojo.Achieve;
import com.yd.rmi.n22.salary.pojo.SearchStaffAchievementRequestBody;
import com.yd.rmi.n22.salary.pojo.SearchStaffAchievementResponseVO;
import com.yd.rmi.n22.salary.service.N22SalaryService;
import com.yd.util.CommonUtil;
import com.yd.util.config.ZHBErrorConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service("agmsDashboardService")
public class AgmsDashboardServiceImpl implements AgmsDashboardService {

    @Autowired
    private AgmsDashboardDALService agmsDashboardDALService;
    @Autowired
    private MdDropOptionsDALService mdDropOptionsDALService;
    @Autowired
    private N22SalaryService n22SalaryService;

    @Override
    public StatisticsPEPResponseVO statisticsPEP(StatisticsPEPRequestVO requestVO) {
        //AGMS -- Dashboard查询  PEP活动管理
        StatisticsPEPResponseVO responseVO = new StatisticsPEPResponseVO();
        MdDropOptions mdDropOptions = mdDropOptionsDALService.selectByMasterCodeAndOptionsCode("bizchance_promotion_action","refused");
        List<StatisticsPEPInfo> statisticsPEPInfos = agmsDashboardDALService.statisticsPEP(requestVO.getType(),mdDropOptions.getId());
        responseVO.setStatisticsPEPInfos(statisticsPEPInfos);
        responseVO.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));
        return responseVO;
    }

    @Override
    public StatisticsOpportunityResponseVO statisticsOpportunity(StatisticsOpportunityRequestVO requestVO) {
        //AGMS -- Dashboard查询  商机预测
        StatisticsOpportunityResponseVO responseVO = new StatisticsOpportunityResponseVO();
        MdDropOptions mdDropOptions = mdDropOptionsDALService.selectByMasterCodeAndOptionsCode("bizchance_promotion_action","refused");
        List<StatisticsOpportunityInfo> statisticsOpportunityInfos = agmsDashboardDALService.statisticsOpportunity(requestVO.getType(),requestVO.getTime(),mdDropOptions.getId());
        responseVO.setStatisticsOpportunityInfos(statisticsOpportunityInfos);
        responseVO.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));
        return responseVO;
    }

    @Override
    public StatisticsForecastTotalResponseVO statisticsForecastTotal(StatisticsForecastTotalRequestVO requestVO) {
        //AGMS -- Dashboard查询  预测统计查询
        StatisticsForecastTotalResponseVO responseVO = new StatisticsForecastTotalResponseVO();
        MdDropOptions mdDropOptions = mdDropOptionsDALService.selectByMasterCodeAndOptionsCode("bizchance_promotion_action","refused");
        List<StatisticsOpportunityInfo> statisticsOpportunityInfos = agmsDashboardDALService.statisticsOpportunity("total",requestVO.getTime(),mdDropOptions.getId());
        List<StatisticsPEPInfo> statisticsPEPInfos = agmsDashboardDALService.statisticsPEP("total",mdDropOptions.getId());
        if (!statisticsOpportunityInfos.isEmpty()){
            StatisticsOpportunityInfo statisticsOpportunityInfo = statisticsOpportunityInfos.get(0);
            responseVO.setOpportunityNum(statisticsOpportunityInfo.getOpportunityNum());
            responseVO.setPredictFYC(statisticsOpportunityInfo.getPredictFYC());
            responseVO.setPredictFYP(statisticsOpportunityInfo.getPredictFYP());
            responseVO.setPieces(statisticsOpportunityInfo.getOpportunityNum());
        }

        if (!statisticsPEPInfos.isEmpty()){
            StatisticsPEPInfo statisticsPEPInfo = statisticsPEPInfos.get(0);
            String time = requestVO.getTime();
            switch (time.toLowerCase()){
                case ("d"):
                    responseVO.setScore(statisticsPEPInfo.getScoreDay());
                    break;
                case ("w"):
                    responseVO.setScore(statisticsPEPInfo.getScoreWeek());
                    break;
                case ("m"):
                    responseVO.setScore(statisticsPEPInfo.getScoreMonth());
                    break;
                case ("q"):
                    responseVO.setScore(statisticsPEPInfo.getScoreQuarter());
                    break;
                case ("y"):
                    responseVO.setScore(statisticsPEPInfo.getScoreYear());
                    break;
            }
        }

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

    @Override
    public StatisticsSalesResponseVO statisticsSales(StatisticsSalesRequestVO requestVO) {
        StatisticsSalesResponseVO responseVO = new StatisticsSalesResponseVO();
        responseVO.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));

        String category = requestVO.getCategory();
        String time = requestVO.getTime();
        String type = requestVO.getType();
        category = Strings.isNullOrEmpty(category) ? "all" : category;
        time = Strings.isNullOrEmpty(time) ? "m" : time;
        type = Strings.isNullOrEmpty(type) ? "b" : type;
        List<StatisticsSalesInfo> statisticsSalesInfos = null;
        try {
            if ("life".equals(category)) {//寿险
//                statisticsSalesInfos = agmsDashboardDALService.statisticsSalesEG(type, time);

                // 查询N22接口获取寿险数据
                statisticsSalesInfos = this.statisticsSalesN22(category, type, time);

            } else if ("pc".equals(category)) {//产险
                statisticsSalesInfos = agmsDashboardDALService.statisticsSalesYD(type, time);
            } else {
                statisticsSalesInfos = getAll(category, type, time);
            }
        } catch (Exception e) {
            e.printStackTrace();
            responseVO.setCommonResult(new CommonResult(false, e.getMessage()));
        }
        responseVO.setStatisticsSalesInfos(statisticsSalesInfos);
        return responseVO;
    }

    private List<StatisticsSalesInfo> statisticsSalesN22(String category, String type, String time) throws Exception {

        // 1.根据Agent_id当前经纪人的佣金明细
        SearchStaffAchievementResponseVO searchStaffAchievementResponseVO = this.queryN22(category, type, time);

        if (!"查询成功".equals(searchStaffAchievementResponseVO.getResponseHead().getMessage())){
            throw new Exception( "N22寿险业绩统计查询错误");
        }
        List<Achieve> achieveList = searchStaffAchievementResponseVO.getResponseBody().getAchieveList();

        // 2.筛选结果集
        if ("life".equals(category)) {
            if ("t".equals(type)) {
                achieveList = achieveList.stream()
                        .filter((Achieve i)  ->  "寿险团队".equals(i.getRolegrouptype()))
                        .collect(Collectors.toList());
            } else if ("b".equals(type)) {
                achieveList = achieveList.stream()
                        .filter((Achieve i)  ->  ("二级机构".equals(i.getRolegrouptype()) || "渠道机构".equals(i.getRolegrouptype())))
                        .collect(Collectors.toList());
            }
        }

        // 3.组装返回报文
        List<StatisticsSalesInfo> infoList = new ArrayList<>();
        StatisticsSalesInfo info = null;
        for (Achieve achieve : achieveList) {

            info = new StatisticsSalesInfo();
            info.setPieces(achieve.getSucNumber());
            info.setFyp(Double.toString(achieve.getFYP()));
            info.setFyc(Double.toString(achieve.getFYC()));
            info.setTypeName(achieve.getDescription());

            infoList.add(info);
        }
        // 3.计算件均保费
        agmsDashboardDALService.getUnitPremium(infoList);

        return infoList;
    }

    private SearchStaffAchievementResponseVO queryN22(String category, String type, String time) {
        // 1.根据查询时间范围获取查询开始时间和结束时间
        String startTime;
        String endTime;
        if ("d".equals(time)) {
            endTime = startTime = CommonUtil.dateParseString(new Date(),"yyyy-MM-dd");

        } else if ("w".equals(time)) {
            startTime = CommonUtil.getWeekStart();
            endTime = CommonUtil.getWeekEnd();
        } else if ("m".equals(time)) {
            startTime = CommonUtil.getBeginDayOfMonth();
            endTime = CommonUtil.getEndDayOfMonth();
        } else if ("q".equals(time)) {
            startTime = CommonUtil.getStartOrEndDayOfQuarter(true);
            endTime = CommonUtil.getStartOrEndDayOfQuarter(false);
        } else {
            startTime = CommonUtil.getBeginDayOfYear();
            endTime = CommonUtil.getEndDayOfYear();
        }

        SearchStaffAchievementRequestBody searchStaffAchievementRequestBody = new SearchStaffAchievementRequestBody();

        searchStaffAchievementRequestBody.setIssuedatestart(startTime);
        searchStaffAchievementRequestBody.setIssuedateend(endTime);
        searchStaffAchievementRequestBody.setPolicystatus("201");

        if ("life".equals(category)) {
            if ("b".equals(type)) {
                searchStaffAchievementRequestBody.setSearchtype("3");
                searchStaffAchievementRequestBody.setIsdown("0");
            } else {
                searchStaffAchievementRequestBody.setSearchtype("2");
                searchStaffAchievementRequestBody.setIsdown("0");
            }
        } else if ("all".equals(category)) {
            searchStaffAchievementRequestBody.setOrganization_id("HX6ZCQ");
            searchStaffAchievementRequestBody.setSearchtype("3");
            searchStaffAchievementRequestBody.setIsdown("1");
        }

        return n22SalaryService.searchStaffAchievement(searchStaffAchievementRequestBody);
    }

    /**
     * dashBoard -- 寿险+产险销售统计
     * @param type 类型
     * @param time 时间
     * @return 数据
     */
    private List<StatisticsSalesInfo> getAll(String category, String type, String time) throws Exception {
        StatisticsSalesInfo statisticsSalesInfo = new StatisticsSalesInfo();
        List<StatisticsSalesInfo> statisticsSalesInfos = new ArrayList<>();
        String unitPremium = "0";
        double fyp = 0D,fyc = 0D;
        Integer pieces = 0;
//        List<StatisticsSalesInfo> statisticsSalesInfosLife = agmsDashboardDALService.statisticsSalesEG(type,time);

        // 查询N22接口获取寿险数据
        List<StatisticsSalesInfo> statisticsSalesInfosLife = this.statisticsSalesN22(category, type, time);
        List<StatisticsSalesInfo> statisticsSalesInfosPC = agmsDashboardDALService.statisticsSalesYD(type,time);

        statisticsSalesInfosLife.addAll(statisticsSalesInfosPC);
        if(statisticsSalesInfosLife.size() > 0){
            for(StatisticsSalesInfo item : statisticsSalesInfosLife){
                fyp += Double.parseDouble(item.getFyp());
                fyc += Double.parseDouble(item.getFyc());
                pieces += item.getPieces();
            }
            if(pieces != 0){
                unitPremium = BigDecimal.valueOf(fyp / pieces).setScale(2,BigDecimal.ROUND_HALF_UP).toString();
            }
        }
        statisticsSalesInfo.setFyc(new DecimalFormat("0.00").format(fyc));
        statisticsSalesInfo.setFyp(new DecimalFormat("0.00").format(fyp));
        statisticsSalesInfo.setPieces(pieces);
        statisticsSalesInfo.setUnitPremium(unitPremium);
        statisticsSalesInfo.setTypeName("寿险+财险");
        statisticsSalesInfos.add(statisticsSalesInfo);
        return statisticsSalesInfos;
    }

    @Override
    public StatisticsPractitionerResponseVO statisticsPractitioner(StatisticsPractitionerRequestVO requestVO) {
        StatisticsPractitionerResponseVO responseVO = new StatisticsPractitionerResponseVO();
        String type = requestVO.getType();
        type = Strings.isNullOrEmpty(type) ? "b" : type;
        List<StatisticsPractitionerInfo> statisticsPractitionerInfos = agmsDashboardDALService.statisticsPractitioner(type);

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

}
