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

import com.yd.api.agms.vo.dashboard.StatisticsPractitionerInfo;
import com.yd.api.agms.vo.dashboard.StatisticsSalesInfo;
import com.yd.dal.entity.agms.dashboard.StatisticsOpportunityInfo;
import com.yd.dal.entity.agms.dashboard.StatisticsPEPInfo;
import com.yd.dal.entity.practitioner.PersonalOffLineFYC;
import com.yd.dal.mapper.agms.AgmsDashboardMapper;
import com.yd.dal.service.agms.AgmsDashboardDALService;
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.intercept.annotation.TargetDataSource;
import com.yd.util.intercept.commons.DataSourceKey;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;

@Service("agmsDashboardDALService")
public class AgmsDashboardDALServiceImpl implements AgmsDashboardDALService {

    @Resource
    private AgmsDashboardMapper agmsDashboardMapper;
    @Autowired
    private N22SalaryService n22SalaryService;
    @Autowired
    private AgmsDashboardDALService agmsDashboardDALService;

    @Override
    public List<StatisticsPEPInfo> statisticsPEP(String type,Long dropOptionId) {
        //查询寿险经纪人人数统计,按type分类
        List<Map<String,Long>> practitionerNums = agmsDashboardMapper.getPractitionerNums(type);
        ConcurrentMap<Long,Long> practitionerNumMap = new ConcurrentHashMap<>();
        practitionerNums.forEach(u->practitionerNumMap.put(u.get("id"),u.get("practitionerNum")));

        //查询总分数
        List<StatisticsPEPInfo> statisticsPEPInfos = new ArrayList<>();
        if ("b".equalsIgnoreCase(type)) {
            statisticsPEPInfos = agmsDashboardMapper.statisticsPEP(type, dropOptionId);
        } else {
            // 新体系
            List<Map<String, Object>> teamMapList = agmsDashboardDALService.queryTeamAllMap();
            teamMapList= teamMapList.stream().filter((Map<String, Object> i) -> i.size()==2).collect(Collectors.toList());
            statisticsPEPInfos = agmsDashboardMapper.statisticsPEPTeam(type, dropOptionId, teamMapList);

            for (Map<String, Object> teamMap :teamMapList) {
                Object teamMember = teamMap.get("teamMember");
                if (null != teamMember) {
                    List<Long> list = (List<Long>) teamMember;
                    practitionerNumMap.put((Long) teamMap.get("id"), (long) list.size());
                }
            }
        }

        for (StatisticsPEPInfo statisticsPEPInfo:statisticsPEPInfos) {
            Long practitionerNum = 0L;
            if (type.equalsIgnoreCase("B")){
                practitionerNum = practitionerNumMap.get(statisticsPEPInfo.getBranchId());
                statisticsPEPInfo.setPractitionerNum(practitionerNum);
            }else if (type.equalsIgnoreCase("T")){
                practitionerNum = practitionerNumMap.get(statisticsPEPInfo.getSubordinateId());
                statisticsPEPInfo.setPractitionerNum(practitionerNum);
            }else {
                practitionerNum = practitionerNumMap.get(0L);
                statisticsPEPInfo.setPractitionerNum(practitionerNum);
            }
            if ("暂无公司".equals(statisticsPEPInfo.getBranchName())) {
                continue;
            }
            Double scoreDay = BigDecimal.valueOf(statisticsPEPInfo.getScoreDay())
                    .divide(BigDecimal.valueOf(practitionerNum),2,BigDecimal.ROUND_HALF_UP)
                    .doubleValue();
            statisticsPEPInfo.setScoreDay(scoreDay);

            Double scoreWeek = BigDecimal.valueOf(statisticsPEPInfo.getScoreWeek())
                    .divide(BigDecimal.valueOf(practitionerNum),2,BigDecimal.ROUND_HALF_UP)
                    .doubleValue();
            statisticsPEPInfo.setScoreWeek(scoreWeek);

            Double scoreMonth = BigDecimal.valueOf(statisticsPEPInfo.getScoreMonth())
                    .divide(BigDecimal.valueOf(practitionerNum),2,BigDecimal.ROUND_HALF_UP)
                    .doubleValue();
            statisticsPEPInfo.setScoreMonth(scoreMonth);

            Double scoreQuarter = BigDecimal.valueOf(statisticsPEPInfo.getScoreQuarter())
                    .divide(BigDecimal.valueOf(practitionerNum),2,BigDecimal.ROUND_HALF_UP)
                    .doubleValue();
            statisticsPEPInfo.setScoreQuarter(scoreQuarter);

            Double scoreYear = BigDecimal.valueOf(statisticsPEPInfo.getScoreYear())
                    .divide(BigDecimal.valueOf(practitionerNum),2,BigDecimal.ROUND_HALF_UP)
                    .doubleValue();
            statisticsPEPInfo.setScoreYear(scoreYear);

            Double scoreTotal = BigDecimal.valueOf(statisticsPEPInfo.getScoreTotal())
                    .divide(BigDecimal.valueOf(practitionerNum),2,BigDecimal.ROUND_HALF_UP)
                    .doubleValue();
            statisticsPEPInfo.setScoreTotal(scoreTotal);
        }
        Comparator<StatisticsPEPInfo> byDay = Comparator.comparing(StatisticsPEPInfo::getScoreDay, Comparator.nullsLast(Double::compareTo)).reversed();
        Comparator<StatisticsPEPInfo> byWeek = Comparator.comparing(StatisticsPEPInfo::getScoreWeek, Comparator.nullsLast(Double::compareTo)).reversed();
        Comparator<StatisticsPEPInfo> byMonth = Comparator.comparing(StatisticsPEPInfo::getScoreMonth, Comparator.nullsLast(Double::compareTo)).reversed();
        Comparator<StatisticsPEPInfo> byQuarter = Comparator.comparing(StatisticsPEPInfo::getScoreQuarter, Comparator.nullsLast(Double::compareTo)).reversed();
        Comparator<StatisticsPEPInfo> statisticsPEPInfoComparator = byDay.thenComparing(byWeek).thenComparing(byMonth).thenComparing(byQuarter);
        statisticsPEPInfos = statisticsPEPInfos.stream().sorted(statisticsPEPInfoComparator).collect(Collectors.toList());
        return statisticsPEPInfos;
    }

    @Override
    public List<StatisticsOpportunityInfo> statisticsOpportunity(String type, String time, Long dropOptionId) {
        if ("b".equalsIgnoreCase(type)) {
            return agmsDashboardMapper.statisticsOpportunity(type, time, dropOptionId);
        } else {
            // 新体系
            List<Map<String, Object>> teamMapList = agmsDashboardDALService.queryTeamAllMap();
            teamMapList= teamMapList.stream().filter((Map<String, Object> i) -> i.size()==2).collect(Collectors.toList());
            return agmsDashboardMapper.statisticsOpportunityTeam(type, time, dropOptionId, teamMapList);
        }
    }

    @Override
    public List<StatisticsSalesInfo> statisticsSalesYD(String category, String type, String time) {
        List<StatisticsSalesInfo> statisticsSalesInfos = null;
        if ("b".equalsIgnoreCase(type)) {
            statisticsSalesInfos = agmsDashboardMapper.statisticsSalesYD(category, type,time);
        } else {
            List<Map<String, Object>> teamMapList = this.queryTeamAllMap();
            teamMapList= teamMapList.stream().filter((Map<String, Object> i) -> i.size()==2).collect(Collectors.toList());
            statisticsSalesInfos = agmsDashboardMapper.statisticsSalesTeam(category, time, teamMapList);
        }
        getUnitPremium(statisticsSalesInfos);
        return statisticsSalesInfos;
    }

    /**
     * 获取均件保费
     * @param statisticsSalesInfos
     */
    @Override
    public void getUnitPremium(List<StatisticsSalesInfo> statisticsSalesInfos) {
        if(statisticsSalesInfos != null && statisticsSalesInfos.size() > 0){
            String fyp;
            Integer pieces;
            for(StatisticsSalesInfo item : statisticsSalesInfos){
                fyp = item.getFyp();
                pieces = item.getPieces();
                if(pieces != null && pieces != 0){
                    item.setUnitPremium(BigDecimal.valueOf(Double.parseDouble(fyp) / pieces).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
                }
            }
        }
    }

    @Override
    public List<Achieve> queryN22FYC(Integer time, Integer isPersonal, String loginName) {
        // 1.根据查询时间范围获取查询开始时间和结束时间
        String startTime;
        String endTime;
        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 {
            startTime = CommonUtil.getBeginDayOfYear();
            endTime = CommonUtil.getEndDayOfYear();
        }
        // 2.根据Agent_id当前经纪人的佣金明细
        SearchStaffAchievementRequestBody searchStaffAchievementRequestBody = new SearchStaffAchievementRequestBody();
        if (Integer.valueOf("0").equals(isPersonal)) {
            searchStaffAchievementRequestBody.setAgent_id(loginName);
        }
        searchStaffAchievementRequestBody.setSearchtype("1");
        searchStaffAchievementRequestBody.setIsdown("0");
        searchStaffAchievementRequestBody.setPolicystatus("201");
        searchStaffAchievementRequestBody.setIssuedatestart(startTime);
        searchStaffAchievementRequestBody.setIssuedateend(endTime);
        SearchStaffAchievementResponseVO searchStaffAchievementResponseVO = n22SalaryService.searchStaffAchievement(searchStaffAchievementRequestBody);

        if ("查询成功".equals(searchStaffAchievementResponseVO.getResponseHead().getMessage())){
            List<Achieve> achieveList = searchStaffAchievementResponseVO.getResponseBody().getAchieveList();
            return achieveList;
        }
        return null;
    }

    @Override
    public List<Map<String, Object>> queryTeamAllMap() {
        List<Map<String, Object>> memberList = agmsDashboardMapper.queryTeamAllMap();

        Object teamMember = null;
        String[] arr = null;
        for (Map<String, Object> map : memberList) {
            teamMember = map.get("teamMember");
            if (teamMember != null && StringUtils.isNotBlank((String) teamMember)) {
                arr = ((String) teamMember).split(",");
                map.put("teamMember", Arrays.asList(arr));
            }
        }
        return memberList;
    }

    @Override
    public List<StatisticsPractitionerInfo> statisticsPractitioner(String type, String time) {
        List<StatisticsPractitionerInfo> statisticsPractitionerInfos = null;
        if ("b".equalsIgnoreCase(type)) {
            statisticsPractitionerInfos = agmsDashboardMapper.statisticsPractitioner(type, time);
        } else {
            List<Map<String, Object>> teamMapList = this.queryTeamAllMap();
            statisticsPractitionerInfos = agmsDashboardMapper.statisticsPractitionerTeam(time, teamMapList);
        }
        //计算实动率
        if(statisticsPractitionerInfos != null && statisticsPractitionerInfos.size() > 0){
            Integer realAmount,amount;
            for(StatisticsPractitionerInfo item : statisticsPractitionerInfos){
                realAmount = item.getRealAmount();
                amount = item.getAmount();
                if(amount > 0){
                    item.setRealRate(BigDecimal.valueOf((realAmount.doubleValue() / amount.doubleValue()) * 100).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
                }
                // 前端取amount作为报聘人数
                item.setAmount(item.getHiringAmount());
            }
        }
        return statisticsPractitionerInfos;
    }

    @Override
    @TargetDataSource(dataSourceKey = DataSourceKey.DB_EGOLDEN)
    public List<StatisticsSalesInfo> statisticsSalesEG(String type, String time) {
        List<StatisticsSalesInfo> statisticsSalesInfos = agmsDashboardMapper.statisticsSalesEG(type,time);
        getUnitPremium(statisticsSalesInfos);
        return statisticsSalesInfos;
    }

    @Override
    @TargetDataSource(dataSourceKey = DataSourceKey.DB_EGOLDEN)
    public List<PersonalOffLineFYC> offLineFYC(List<String> mobileNoList) {
        List<PersonalOffLineFYC> personalOffLineFYCList = agmsDashboardMapper.personalOffLineFYC(mobileNoList);
        return personalOffLineFYCList;
    }
}
