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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
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;

    @Override
    public List<StatisticsPEPInfo> statisticsPEP(String type,Long dropOptionId) {
        //查询总分数
        List<StatisticsPEPInfo> statisticsPEPInfos = agmsDashboardMapper.statisticsPEP(type, 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")));
        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);
            }
            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).reversed();
        Comparator<StatisticsPEPInfo> byWeek = Comparator.comparing(StatisticsPEPInfo::getScoreWeek).reversed();
        Comparator<StatisticsPEPInfo> byMonth = Comparator.comparing(StatisticsPEPInfo::getScoreMonth).reversed();
        Comparator<StatisticsPEPInfo> byQuarter = Comparator.comparing(StatisticsPEPInfo::getScoreQuarter).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) {
        return agmsDashboardMapper.statisticsOpportunity(type , time, dropOptionId);
    }

    @Override
    public List<StatisticsSalesInfo> statisticsSalesYD(String category, String type, String time) {
        List<StatisticsSalesInfo> statisticsSalesInfos = agmsDashboardMapper.statisticsSalesYD(category, type,time);
        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<StatisticsPractitionerInfo> statisticsPractitioner(String type, String time) {
        List<StatisticsPractitionerInfo> statisticsPractitionerInfos = agmsDashboardMapper.statisticsPractitioner(type, time);
        //计算实动率
        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;
    }
}
