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.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.Comparator;
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)) {//寿险
                // 查询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当前经纪人的佣金明细
        List<Achieve> achieveList = this.queryN22(category, type, time);

        // 2.组装返回报文
        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(achieve.getFYC());
            info.setTypeName(achieve.getDescription());

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

        // 4.排序
        infoList.sort(Comparator.comparingDouble(StatisticsSalesInfo::getFyc).reversed());

        return infoList;
    }

    private List<Achieve> queryN22(String category, String type, String time) throws Exception {
        // 0.声明变量
        SearchStaffAchievementResponseVO searchStaffAchievementResponseVO = null;
        List<Achieve> resultList = new ArrayList<>();

        // 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)) {

                List<Achieve> achieveList = new ArrayList<>();

                searchStaffAchievementRequestBody.setIsdown("1");
                // 循环查分公司
                List<String> organizationIdList = this.getGroupIdByThisInterface("二级机构");
                for (String organizationId : organizationIdList) {
                    searchStaffAchievementRequestBody.setSearchtype("3");
                    searchStaffAchievementRequestBody.setOrganization_id(organizationId);

                    searchStaffAchievementResponseVO = n22SalaryService.searchStaffAchievement(searchStaffAchievementRequestBody);
                    List<Achieve> achieves = n22SalaryService.searchStaffAchievementGetAchieveList(searchStaffAchievementResponseVO);
                    achieveList.addAll(achieves);
                }
                // 循环查渠道机构
                List<String> frIdList = this.getGroupIdByThisInterface("渠道机构");
                for (String FRId : frIdList) {
                    searchStaffAchievementRequestBody.setSearchtype("2");
                    searchStaffAchievementRequestBody.setRolegroup_id(FRId);

                    searchStaffAchievementResponseVO = n22SalaryService.searchStaffAchievement(searchStaffAchievementRequestBody);
                    List<Achieve> achieves = n22SalaryService.searchStaffAchievementGetAchieveList(searchStaffAchievementResponseVO);
                    achieveList.addAll(achieves);
                }

                resultList = achieveList;

            } else {
                List<Achieve> achieveList = new ArrayList<>();

                // 查团队
                searchStaffAchievementRequestBody.setSearchtype("2");
                searchStaffAchievementRequestBody.setIsdown("1");
                // 循环查
                List<String> groupIdList = this.getGroupIdByThisInterface("寿险团队");
                for (String groupId : groupIdList) {
                    searchStaffAchievementRequestBody.setRolegroup_id(groupId);

                    searchStaffAchievementResponseVO = n22SalaryService.searchStaffAchievement(searchStaffAchievementRequestBody);
                    List<Achieve> achieves = n22SalaryService.searchStaffAchievementGetAchieveList(searchStaffAchievementResponseVO);
                    achieveList.addAll(achieves);
                }
                resultList = achieveList;
            }
        } else if ("all".equals(category)) {
            searchStaffAchievementRequestBody.setOrganization_id("HX6ZCQ");
            searchStaffAchievementRequestBody.setSearchtype("3");
            searchStaffAchievementRequestBody.setIsdown("1");

            searchStaffAchievementResponseVO = n22SalaryService.searchStaffAchievement(searchStaffAchievementRequestBody);
            resultList = n22SalaryService.searchStaffAchievementGetAchieveList(searchStaffAchievementResponseVO);

        }

        return resultList;
    }

    /**
     * 用业绩接口的返回报文筛选出所有团队组id
     * @param groupType 可填二级机构，渠道机构，寿险团队
     * @return
     * @throws Exception
     */
    private List<String> getGroupIdByThisInterface(String groupType) throws Exception {
        List<String> list = new ArrayList<>();

        String curDay = CommonUtil.dateParseString(new Date(),"yyyy-MM-dd");
        // 组装参数
        SearchStaffAchievementRequestBody searchStaffAchievementRequestBody = new SearchStaffAchievementRequestBody();
        searchStaffAchievementRequestBody.setIssuedatestart(curDay);
        searchStaffAchievementRequestBody.setIssuedateend(curDay);
        searchStaffAchievementRequestBody.setPolicystatus("201");
        searchStaffAchievementRequestBody.setSearchtype("2");
        searchStaffAchievementRequestBody.setIsdown("0");
        // 调接口
        SearchStaffAchievementResponseVO searchStaffAchievementResponseVO = n22SalaryService.searchStaffAchievement(searchStaffAchievementRequestBody);
        List<Achieve> achieveList = n22SalaryService.searchStaffAchievementGetAchieveList(searchStaffAchievementResponseVO);

        for (Achieve item : achieveList) {
            if (groupType.equals(item.getRolegrouptype())) {
                list.add(item.getID());
            }
        }
        return list;
    }

    /**
     * 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 += item.getFyc();
                pieces += item.getPieces();
            }
            if(pieces != 0){
                unitPremium = BigDecimal.valueOf(fyp / pieces).setScale(2,BigDecimal.ROUND_HALF_UP).toString();
            }
        }
        statisticsSalesInfo.setFyc(Double.parseDouble(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;
    }

}
