package cn.com.countrygarden.bi.main.service.performance.impl;

import cn.com.countrygarden.bi.main.dao.hmWygl.TbHSPRRegionAvatarInfoMapper;
import cn.com.countrygarden.bi.main.dao.performance.*;
import cn.com.countrygarden.bi.main.dao.sys.UserRolesMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.TbHsprCommunityMapper;
import cn.com.countrygarden.bi.main.model.hmWygl.TbHSPRRegionAvatarInfo;
import cn.com.countrygarden.bi.main.model.performance.PerformanceElement;
import cn.com.countrygarden.bi.main.model.performance.PerformanceMonthly;
import cn.com.countrygarden.bi.main.model.performance.PerformanceStatistics;
import cn.com.countrygarden.bi.main.model.performance.monthly.*;
import cn.com.countrygarden.bi.main.model.sys.UserRoles;
import cn.com.countrygarden.bi.main.model.twerp.ErpCommunity;
import cn.com.countrygarden.bi.main.service.performance.AssessmentMonthlyTargetService;
import cn.com.countrygarden.bi.main.service.performance.PerformanceMonthService;
import cn.com.countrygarden.bi.main.service.performance.PerformanceMonthlyService;
import cn.com.countrygarden.bi.main.service.performance.PerformanceMonthlyStatisticsService;
import cn.com.countrygarden.bi.main.util.erp.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Condition;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TreeSet;

/**
 * 月度-绩效分析
 *
 * @author Max Date:2018/09/21
 * @version 1.0
 * @since 1.8
 */
@Service
public class PerformanceMonthServiceImpl implements PerformanceMonthService {

    @Autowired
    private PerformanceMonthlyStatisticsService performanceMonthlyStatisticsService;

    @Autowired
    private PerformanceCompanyMapper performanceCompanyMapper;

    @Autowired
    private PerformanceMonthlyService performanceMonthlyService;

    @Autowired
    private TbHsprCommunityMapper tbHsprCommunityMapper;

    @Autowired
    private TbHSPRRegionAvatarInfoMapper tbHSPRRegionAvatarInfoMapper;

    @Autowired
    private PerformanceEnvMapper performanceEnvMapper;

    @Autowired
    private PerformanceAreaMapper performanceAreaMapper;

    @Autowired
    private PerformanceElementMapper performanceElementMapper;

    @Autowired
    private PerformanceMonthlyStatisticsMapper performanceMonthlyStatisticsMapper;

    @Autowired
    private UserRolesMapper userRolesMapper;

    @Autowired
    private AssessmentMonthlyTargetService assessmentMonthlyTargetService;

    @Autowired
    private PerformanceMonthlyMapper performanceMonthlyMapper;

    /**
     * 月度-绩效分析-区域
     *
     * @param elementId 指标id
     * @param userCode  用户userCode
     * @return Object
     */
    @Override
    public Object scoreListRegion(long elementId, String userCode) {
        List<ErpCommunity> organList = tbHsprCommunityMapper.findOrganBaseByUserCode(userCode, null);//获取区域id
        if (organList.isEmpty()) {
            return "该账号无可访问区域数据！";
        }
        List<String> hierarchyIdList = new ArrayList<>();
        for (ErpCommunity organ : organList) {
            hierarchyIdList.add(organ.getOrganCode());
        }

        //过滤多余城市公司和无效区域
        hierarchyIdList = performanceAreaMapper.areaFilter(hierarchyIdList,"1");

        //取年
        Calendar date = Calendar.getInstance();
        Integer year = date.get(Calendar.YEAR);

        //得到当前年的导入数据的最大月份
        Integer m = performanceMonthlyStatisticsService.selectMaxMonth(elementId, year);
        int month = 1;//至少返回一个月的数据给前台
        if (m != null) {
            month = m;
        }
        int copyMonth = month;

        //用于返回给前端的数据
        MonthScoreListDto result = new MonthScoreListDto();
        List<PerformanceMonthlyStatistics> statistics = new ArrayList<>();
        List<MonthCompleteInfo> monthCompleteInfos = new ArrayList<>();

        for (; month > 0; month--) {
            //柱状图
            PerformanceMonthlyStatistics result_statistics = performanceMonthlyStatisticsService.getAverage(elementId, year, month);
            if (result_statistics != null) {
                statistics.add(result_statistics);
            } else {//无数据情况下，充填数据，为了前端好遍历展示
                PerformanceMonthlyStatistics temp_statistics = new PerformanceMonthlyStatistics();
                temp_statistics.setElementId(elementId);
                temp_statistics.setYear(year);
                temp_statistics.setMonth(month);
                temp_statistics.setAverageRate("0");
                statistics.add(temp_statistics);
            }
        }
        //加入返回结果中
        result.setHistogram(statistics);//柱状图

        //区域，当前，最大及其以前数据
        for (String hierarchyId : hierarchyIdList) {
            MonthCompleteInfo tempMonthCompleteInfo = new MonthCompleteInfo();

            //查询图片/名字
            List<String> temp_list = new ArrayList<>();
            temp_list.add(hierarchyId);
            List<TbHSPRRegionAvatarInfo> imageList = this.tbHSPRRegionAvatarInfoMapper.selectOrganList(temp_list);
            if (imageList.size() != 0) {
                tempMonthCompleteInfo.setImageUrl(imageList.get(0).getImageOnePath());
                tempMonthCompleteInfo.setName(imageList.get(0).getNames());
            }

            //查询区域名称
            String hierachyName = performanceAreaMapper.selectHierachyName(hierarchyId);
            if (!StringUtil.isBlankOrEmpty(hierachyName)) {
                tempMonthCompleteInfo.setHierarchyName(hierachyName);//设置区域名称
            }

            int temp_month = copyMonth;
            List<PerformanceMonthly> performanceMonthlies = new ArrayList<>();
            //区域根据年/月返回
            for (; temp_month > 0; temp_month--) {
                PerformanceMonthly pm = new PerformanceMonthly();
                pm.setElementId(elementId);
                pm.setYear(year);
                pm.setMonth(temp_month);
                pm.setHierarchyId(hierarchyId);
                PerformanceMonthly result_performanceMonthly = performanceMonthlyService.getSelect(pm);
                if (result_performanceMonthly != null) {
                    performanceMonthlies.add(result_performanceMonthly);
                } else {//为了前端能方便取数，个数需要和柱状图个数保持一致
                    pm.setComplete("0");
                    pm.setAnnualTarget("0");
                    pm.setCompleteRate("0");
                    performanceMonthlies.add(pm);
                }
            }

            //加入临时缓存，方便加入结果中
            tempMonthCompleteInfo.setCompleteInfo(performanceMonthlies);
            monthCompleteInfos.add(tempMonthCompleteInfo);
        }

        //加入结果中
        result.setMonthCompleteInfo(monthCompleteInfos);

        return result;
    }

    /**
     * 月度-绩效分析-区域
     *
     * @param elementId 指标id
     * @param userCode  用户UserCode
     * @return Object
     */
    @Override
    public Object scoreListCompany(long elementId, String userCode) {
        List<ErpCommunity> organList = tbHsprCommunityMapper.findOrganBaseByUserCode(userCode, null);//获取区域id
        if (organList.isEmpty()) {
            return "该账号无可访问区域数据！";
        }
        List<String> hierarchyIdList = new ArrayList<>();
        for (ErpCommunity organ : organList) {
            hierarchyIdList.add(organ.getOrganCode());
        }

        hierarchyIdList = performanceAreaMapper.areaFilter(hierarchyIdList,"2");//过滤区域和无效的城市公司

        //取年
        Calendar date = Calendar.getInstance();
        Integer year = date.get(Calendar.YEAR);

        //得到当前年的导入数据的最大月份
        Integer m = performanceMonthlyStatisticsService.selectMaxMonth(elementId, year);
        int month = 1;//至少返回一个月的数据给前台
        if (m != null) {
            month = m;
        }
        int copyMonth = month;

        //用于返回给前端的数据
        MonthScoreListDto result = new MonthScoreListDto();
        List<PerformanceMonthlyStatistics> statistics = new ArrayList<>();
        List<MonthCompleteInfo> monthCompleteInfos = new ArrayList<>();

        for (; month > 0; month--) {
            //柱状图
            PerformanceMonthlyStatistics result_statistics = performanceMonthlyStatisticsService.getAverage(elementId, year, month);
            if (result_statistics != null) {
                statistics.add(result_statistics);
            } else {//无数据情况下，充填数据，为了前端好遍历展示
                PerformanceMonthlyStatistics temp_statistics = new PerformanceMonthlyStatistics();
                temp_statistics.setYear(year);
                temp_statistics.setMonth(month);
                temp_statistics.setElementId(elementId);
                temp_statistics.setAverageRate("0");
                statistics.add(temp_statistics);
            }
        }
        //加入返回结果中
        result.setHistogram(statistics);//柱状图

        //区域，当前，最大及其以前数据
        for (String hierarchyId : hierarchyIdList) {
            MonthCompleteInfo tempMonthCompleteInfo = new MonthCompleteInfo();

            //查询图片/名字
            List<String> temp_list = new ArrayList<>();
            temp_list.add(hierarchyId);
            List<TbHSPRRegionAvatarInfo> imageList = this.tbHSPRRegionAvatarInfoMapper.selectOrganList(temp_list);
            if (imageList.size() != 0) {
                tempMonthCompleteInfo.setImageUrl(imageList.get(0).getImageOnePath());
                tempMonthCompleteInfo.setName(imageList.get(0).getNames());
            }

            //查询城市公司名称
            String hierachyName  = performanceAreaMapper.selectHierachyName(hierarchyId);
            if (!StringUtil.isBlankOrEmpty(hierachyName)) {
                tempMonthCompleteInfo.setHierarchyName(hierachyName);//设置城市公司名称
            }

            int temp_month = copyMonth;
            List<PerformanceMonthly> performanceMonthlies = new ArrayList<>();
            //区域根据年/月返回
            for (; temp_month > 0; temp_month--) {
                PerformanceMonthly pm = new PerformanceMonthly();
                pm.setYear(year);
                pm.setMonth(temp_month);
                pm.setElementId(elementId);
                pm.setHierarchyId(hierarchyId);
                PerformanceMonthly result_performanceMonthly = performanceMonthlyService.getSelect(pm);
                if (result_performanceMonthly != null) {
                    performanceMonthlies.add(result_performanceMonthly);
                } else {//为了前端能方便取数，个数需要和柱状图个数保持一致
                    pm.setCompleteRate("0");
                    pm.setComplete("0");
                    pm.setAnnualTarget("0");
                    performanceMonthlies.add(pm);
                }
            }

            //加入临时缓存，方便加入结果中
            tempMonthCompleteInfo.setCompleteInfo(performanceMonthlies);
            monthCompleteInfos.add(tempMonthCompleteInfo);
        }

        //加入结果中
        result.setMonthCompleteInfo(monthCompleteInfos);

        return result;
    }

    @Override
    public Object performanceAnalysis(long elementId, String typeNo, String userCode, int month) {

        List<ErpCommunity> organList = tbHsprCommunityMapper.findOrganBaseByUserCode(userCode, null);//获取区域id
        if (organList.isEmpty()) {
            return "该账号无可访问区域数据！";
        }
        List<String> hierarchyIdList = new ArrayList<>();
        for (ErpCommunity organ : organList) {
            hierarchyIdList.add(organ.getOrganCode());
        }

        //过滤
        hierarchyIdList = performanceAreaMapper.areaFilter(hierarchyIdList,typeNo);

        List<MonthCompleteInfo> monthCompleteInfos = new ArrayList<>();

        //取年(暂时设置为2018，后续修改为2019)
        Calendar date = Calendar.getInstance();
        Integer year =  2018;//date.get(Calendar.YEAR);

        //区域，当前，最大及其以前数据
        for (String hierarchyId : hierarchyIdList) {
            MonthCompleteInfo tempMonthCompleteInfo = new MonthCompleteInfo();

            //查询图片/名字
            List<String> temp_list = new ArrayList<>();
            temp_list.add(hierarchyId);
            List<TbHSPRRegionAvatarInfo> imageList = this.tbHSPRRegionAvatarInfoMapper.selectOrganList(temp_list);
            if (imageList.size() != 0) {
                tempMonthCompleteInfo.setImageUrl(imageList.get(0).getImageOnePath());
                tempMonthCompleteInfo.setName(imageList.get(0).getNames());
            }

            //查询区域名称
            String hierachyName = performanceAreaMapper.selectHierachyName(hierarchyId);
            if (!StringUtil.isBlankOrEmpty(hierachyName)) {
                tempMonthCompleteInfo.setHierarchyName(hierachyName);//设置区域名称
            }

            List<PerformanceMonthly> performanceMonthlies = new ArrayList<>();
            //区域根据年/月返回
                PerformanceMonthly pm = new PerformanceMonthly();
                pm.setElementId(elementId);
                pm.setYear(year);
                pm.setMonth(month);
                pm.setHierarchyId(hierarchyId);
                PerformanceMonthly result_performanceMonthly = performanceMonthlyService.getSelect(pm);
                if (result_performanceMonthly != null) {
                    performanceMonthlies.add(result_performanceMonthly);
                } else {//为了前端能方便取数，个数需要和柱状图个数保持一致
                    pm.setComplete("0");
                    pm.setAnnualTarget("0");
                    pm.setCompleteRate("0");
                    performanceMonthlies.add(pm);
                }

            //加入临时缓存，方便加入结果中
            tempMonthCompleteInfo.setCompleteInfo(performanceMonthlies);
            monthCompleteInfos.add(tempMonthCompleteInfo);
        }
        return monthCompleteInfos;
    }

    @Override
    public Object myPerformance(String[] selectAreaList,String typeNo, String userCode, int month) {

        //查询所有三级以上的指标，切不包含总指标
        Condition condition = new Condition(PerformanceElement.class);
        condition.createCriteria().andNotEqualTo("level", 4).andNotEqualTo("elementId",0).andNotEqualTo("elementId",999L)
                .andNotEqualTo("type","城市公司").andNotEqualTo("type","加/减分项");
        List<PerformanceElement> performanceElementList = performanceElementMapper.selectByCondition(condition);

        //查询本年度可以统计数据的月份数
        //保持数据一致性，月份从月度统计表中取
        long elementid = performanceElementList.get(0).getElementId();//取任意一个指标
        //取年(暂时设置为2018，后续修改为2019)
        Calendar date = Calendar.getInstance();
        Integer year = 2018; //date.get(Calendar.YEAR);

        int maxMonth = performanceMonthlyStatisticsMapper.selectMaxMonth(elementid,year);

        //int month = performanceMonthlyMapper.selectCountMonthByYear(year);//从月度表取

        //查询账号是否是区域总的，如果是还需要判断最新一个月是否发布，若无发布则只返回之前月份的数据
        Condition conditionField=new Condition(UserRoles.class);
        conditionField.createCriteria().andEqualTo("userCode",userCode).andEqualTo("roleCode","performanceArea");
        List<UserRoles> userRolesList=userRolesMapper.selectByCondition(conditionField);
        if(userRolesList.size()>0){//表示为区域总的账号
            //查询最新季度是否发布了
            List<AssessmentMonthlyTarget> lastPublic = assessmentMonthlyTargetService.getOgranLastMonthPublic(year,maxMonth);
            if(lastPublic.size() > 0){
                maxMonth--;
            }
        }
        //验证月度的正确性
        month = month <= maxMonth ? month : maxMonth;
        //默认返回最新季度的数据
        if(month == 0)
            month = maxMonth;

        //组装我的考核返回实体
        List<MyPerformMonthDto> returnList = new ArrayList<>();
        for(String hierachyId : selectAreaList){
            MyPerformMonthDto myPerformMonthDto = new MyPerformMonthDto();
            myPerformMonthDto.setHierachyId(hierachyId);
            myPerformMonthDto.setMaxMonth(maxMonth);

            PerformanceMonthAveDto monthAveDto = new PerformanceMonthAveDto();
            monthAveDto.setMonth(month);//设置月份信息

            List<PerformanceMonthDto> monthDtos = new ArrayList<>();//每个月所有的DTO
            for(int j = 0; j < performanceElementList.size(); j++){
                long elementId = performanceElementList.get(j).getElementId();//获取id
                String elementName = performanceElementList.get(j).getName();//获取指标名称
                //通过年、月、指标id、地区id获得唯一一个实体
                PerformanceMonthly performanceMonthly = new PerformanceMonthDto(year,month,elementId,hierachyId);//父类引用指向子类实例
                PerformanceMonthly pm = performanceMonthlyMapper.getSelect(performanceMonthly);
                if(pm != null){
                    performanceMonthly = new PerformanceMonthDto(pm);
                }
                PerformanceMonthDto monthDto = (PerformanceMonthDto)performanceMonthly;
                //设置指标名称i
                monthDto.setElementName(elementName);
                //加到集合中
                monthDtos.add(monthDto);
            }
            monthAveDto.setMonthDtoList(monthDtos);

            //获取区域月度平均值 0 代表区域
            PerformanceMonthly pm = new PerformanceMonthly(year,month,0,hierachyId);
            pm = performanceMonthlyMapper.getSelect(pm);
            if(pm != null){
                //设置平均分
                String averageScore = pm.getCompleteRate();
                if(!StringUtil.isBlankOrEmpty(averageScore)) {
                    monthAveDto.setElementsAverage(averageScore);
                }
                //设置排名
                int ranges = pm.getRanges();
                monthAveDto.setRanges(ranges);
            }
            myPerformMonthDto.setPerformanceMonthAveDto(monthAveDto);
            returnList.add(myPerformMonthDto);
        }

        return returnList;
    }

    @Override
    public Object getElementAveScore(long elementId) {
        TreeSet<PerformanceMonthlyStatistics> set = new TreeSet<>();
        //获取当前年份    (暂时设置为2018，后续修改为2019)
        int year = 2018;
        for(int i = 1; i < 13; i++){
            PerformanceMonthlyStatistics ps = performanceMonthlyStatisticsService.getAverage(elementId,year,i);
            if(ps != null)
                set.add(ps);
            else{//为空则填充
                PerformanceMonthlyStatistics temp_statistics = new PerformanceMonthlyStatistics();
                temp_statistics.setElementId(elementId);
                temp_statistics.setYear(year);
                temp_statistics.setMonth(i);
                temp_statistics.setAverageRate("0");
                set.add(temp_statistics);
            }
        }
        return set;
    }


}
