/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.xrtygis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.xrtygis.em.AssessContentEnum;
import com.tofly.xrtygis.em.QuarterEnum;
import com.tofly.xrtygis.entity.TfKpiManage;
import com.tofly.xrtygis.entity.TfKpiPersonManage;
import com.tofly.xrtygis.entity.dto.TfKpiManageDto;
import com.tofly.xrtygis.mapper.TfKpiManageMapper;
import com.tofly.xrtygis.service.TfKpiManageService;
import com.tofly.xrtygis.service.TfKpiPersonManageService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 绩效考核管理
 *
 * @author JF
 * @date Fri Mar 25 00:00:00 CST 2022
 */
@Service("tfKpiManageService")
public class TfKpiManageServiceImpl extends ServiceImpl<TfKpiManageMapper, TfKpiManage> implements TfKpiManageService {

    @Autowired
    private TfKpiPersonManageService tfKpiPersonManageService;

    @Override
    //获取绩效汇总分页列表
    public Page<TfKpiManage> getTfKpiCensusPage(Page page, TfKpiManageDto tfKpiManageDto) {

        String assessDate;
        if(StringUtils.isNotBlank(tfKpiManageDto.getStartAssessDate())
                && StringUtils.isNotBlank(tfKpiManageDto.getEndAssessDate())){
            assessDate = getAssessDate("2",tfKpiManageDto);
        }else if(StringUtils.isNotBlank(tfKpiManageDto.getQuarterAssessDate())
                && StringUtils.isNotBlank(tfKpiManageDto.getThisYearAssessDate())){
            assessDate = getAssessDate("1",tfKpiManageDto);
        }else {
            return page;
        }

        TfKpiManageDto tfKpiManageAreaQuery = new TfKpiManageDto();
        tfKpiManageAreaQuery.setAssessPerson(tfKpiManageDto.getAssessPerson());
        tfKpiManageAreaQuery.setThisYearAssessDate(assessDate);
        tfKpiManageAreaQuery.setAreaLevel(tfKpiManageDto.getAreaLevel());
        return this.baseMapper.getTfKpiManageList(page, tfKpiManageAreaQuery);
    }

    @Override
    //获取绩效明细分页列表
    public Page<TfKpiManage> getTfKpiDetailedPage(Page page, TfKpiManageDto tfKpiManageDto) {

        String startYear = tfKpiManageDto.getStartAssessDate();
        String endYear = tfKpiManageDto.getEndAssessDate();
        if(StringUtils.isNotBlank(startYear)&& StringUtils.isNotBlank(endYear)){
            tfKpiManageDto.setAssessType("2");
        }else if(StringUtils.isNotBlank(tfKpiManageDto.getQuarterAssessDate())
                && StringUtils.isNotBlank(tfKpiManageDto.getThisYearAssessDate())){
            tfKpiManageDto.setAssessType("1");
        }else {
            return page;
        }

        //查询明细列表是否包含此年此人，不包含则添加
        saveHasYearOrQuarter(tfKpiManageDto.getAssessType(), page, tfKpiManageDto);

        //获取考核明细
        return getDetailedCensus(tfKpiManageDto.getAssessType(), page, tfKpiManageDto);
    }

    @Override
    //获取绩效汇总统计图数据
    public List<Map<String,Object>> getTfKpiCensusPhoto(TfKpiManageDto tfKpiManageDto) {

        if(StringUtils.isNotBlank(tfKpiManageDto.getStartAssessDate())
                && StringUtils.isNotBlank(tfKpiManageDto.getEndAssessDate())){
            tfKpiManageDto.setAssessType("2");
        }else if(StringUtils.isNotBlank(tfKpiManageDto.getQuarterAssessDate())
                && StringUtils.isNotBlank(tfKpiManageDto.getThisYearAssessDate())){
            tfKpiManageDto.setAssessType("1");
        }else {
            return new ArrayList<>();
        }
        return getAvgScoreContent(tfKpiManageDto.getAssessType(),tfKpiManageDto);
    }

    //获取考核日期
    private static String getAssessDate(String assessType, TfKpiManageDto tfKpiManageDto) {
        String startYear = tfKpiManageDto.getStartAssessDate();
        String endYear = tfKpiManageDto.getEndAssessDate();
        String[] quarterList = tfKpiManageDto.getQuarterAssessDate().split(",");
        StringBuilder assessDate = new StringBuilder();
        if(assessType.equals("1")){
            for(String quarter:quarterList) {
                assessDate.append(tfKpiManageDto.getThisYearAssessDate()).append("年第")
                        .append(QuarterEnum.getCodeForValue(String.valueOf(quarter))).append("季度,");
            }
            assessDate = new StringBuilder(assessDate.substring(0, assessDate.length() - 1));
        }else if(assessType.equals("2")){
            for(int i = Integer.parseInt(startYear);i < Integer.parseInt(endYear) + 1;i++) {
                assessDate.append(i).append("年");
                if (i != Integer.parseInt(endYear)) {
                    assessDate.append(",");
                }
            }
        }

        return assessDate.toString();
    }

    //获取明细汇总列表
    private Page<TfKpiManage> getDetailedCensus(String assessType, Page page, TfKpiManageDto tfKpiManageDto) {

        List<TfKpiManage> tfKpiManages = new ArrayList<>();

        String assessDate = getAssessDate(assessType,tfKpiManageDto);
        if(StringUtils.isBlank(assessDate)||tfKpiManageDto.getItemizedSummary()==null){
            return page.setRecords(tfKpiManages);
        }

        if(tfKpiManageDto.getItemizedSummary().equals("1")){
            TfKpiManageDto tfKpiManageAreaQuery = new TfKpiManageDto();
            tfKpiManageAreaQuery.setAssessPerson(tfKpiManageDto.getAssessPerson());
            tfKpiManageAreaQuery.setThisYearAssessDate(assessDate);
            tfKpiManageAreaQuery.setAreaLevel(tfKpiManageDto.getAreaLevel());
            tfKpiManages.addAll(this.baseMapper.getTfKpiManageList(page, tfKpiManageAreaQuery).getRecords());
        }else if(tfKpiManageDto.getItemizedSummary().equals("2")){
            TfKpiManageDto tfKpiManageDtoQuery = new TfKpiManageDto();
            tfKpiManageDtoQuery.setAssessPerson(tfKpiManageDto.getAssessPerson());
            tfKpiManageDtoQuery.setAreaLevel(tfKpiManageDto.getAreaLevel());
            for(int i=1;i<5;i++){
                tfKpiManageDtoQuery.setAssessDate(tfKpiManageDto.getThisYearAssessDate() + "年第"
                        + QuarterEnum.getCodeForValue(String.valueOf(i)) + "季度");
                List<TfKpiManage> tfKpiAreaList = this.baseMapper.getTfKpiManageList(page, tfKpiManageDtoQuery).getRecords();
                for(TfKpiManage tfKpiArea:tfKpiAreaList){
                    String assessArea = tfKpiArea.getAssessArea();
                    tfKpiManageDtoQuery.setAssessArea(assessArea);
                    List<TfKpiManage> tfKpiList = this.baseMapper.getTfKpiManageList(page, tfKpiManageDtoQuery).getRecords();
                    StringBuilder assessSituation = new StringBuilder();
                    int assessAllScore = 0;
                    for(int j = 0;j<tfKpiList.size();j++){
                        assessSituation.append(AssessContentEnum.getCodeForValue(tfKpiList.get(j).getAssessContent()))
                                .append("(").append(tfKpiList.get(j).getAssessStandard()).append("%)");
                        assessAllScore += Integer.parseInt(tfKpiList.get(j).getAssessScore());
                        if(j<tfKpiList.size()-1){
                            assessSituation.append(",");
                        }
                    }
                    int assessAvgScore = 0;
                    if(assessAllScore != 0 && tfKpiList.size() != 0){
                        assessAvgScore = assessAllScore / tfKpiList.size();
                    }
                    tfKpiArea.setAssessAvgScore(String.valueOf(assessAvgScore));
                    tfKpiArea.setAssessSituation(assessSituation.toString());
                    tfKpiManages.add(tfKpiArea);
                }
            }
            page.setTotal(tfKpiManages.size());
        }

        return page.setRecords(tfKpiManages);
    }

    //若不存在查询需要的年度季度，则添加明细列表
    private void saveHasYearOrQuarter(String assessType, Page page, TfKpiManageDto tfKpiManageDto) {
        boolean hasAssessPerson = tfKpiManageDto.getAssessPerson() != null;

        String assessDate;
        if(assessType.equals("2")){
            assessDate = tfKpiManageDto.getThisYearAssessDate() + "年";
        }else if(assessType.equals("1")){
            assessDate = tfKpiManageDto.getThisYearAssessDate() + "年第一季度";
        }else {
            return;
        }
        TfKpiManageDto tfKpiManageAreaQuery = new TfKpiManageDto();
        tfKpiManageAreaQuery.setAssessPerson(tfKpiManageDto.getAssessPerson());
        tfKpiManageAreaQuery.setThisYearAssessDate(assessDate);
        List<TfKpiManage> tfHasKpiList = this.baseMapper.getTfKpiManageList(page, tfKpiManageAreaQuery).getRecords();
        if(tfHasKpiList.size()!=0){
            return;
        }
        List<TfKpiPersonManage> tfKpiPersonList = tfKpiPersonManageService.list(new QueryWrapper<TfKpiPersonManage>()
                .eq("ASSESS_TYPE",assessType)
                .eq(hasAssessPerson,"ASSESS_PERSON",tfKpiManageDto.getAssessPerson()));
        if(tfKpiPersonList.size()==0){
            return;
        }

        for(TfKpiPersonManage tfKpiPersonManage:tfKpiPersonList){
            //添加考核明细
            TfKpiManage tfKpiManageInsert = new TfKpiManage();
            tfKpiManageInsert.setAssessPerson(tfKpiPersonManage.getAssessPerson());
            tfKpiManageInsert.setAssessArea(tfKpiPersonManage.getAssessArea());
            tfKpiManageInsert.setAssessType(tfKpiPersonManage.getAssessType());
            tfKpiManageInsert.setAssessContent(tfKpiPersonManage.getAssessContent());
            tfKpiManageInsert.setAssessStandard(tfKpiPersonManage.getAssessStandard());
            tfKpiManageInsert.setAreaLevel(tfKpiPersonManage.getAreaLevel());
            if(assessType.equals("1")){
                for(int i = 1;i < 5;i++){
                    tfKpiManageInsert.setAssessDate(tfKpiManageDto.getThisYearAssessDate()
                            + "年第" + QuarterEnum.getCodeForValue(String.valueOf(i)) + "季度");
                    this.save(tfKpiManageInsert);
                }
            }else if(assessType.equals("2")){
                tfKpiManageInsert.setAssessDate(tfKpiManageDto.getThisYearAssessDate() + "年");
                this.save(tfKpiManageInsert);
            }else {
                return;
            }
        }
    }

    private List<Map<String,Object>> getAvgScoreContent(String assessType, TfKpiManageDto tfKpiManageDto) {
        List<Map<String,Object>> tfKpiManages = new ArrayList<>();

        String assessDate = getAssessDate(assessType,tfKpiManageDto);
        if(StringUtils.isBlank(assessDate)){
            return tfKpiManages;
        }

        TfKpiManageDto tfKpiManageAreaQuery = new TfKpiManageDto();
        tfKpiManageAreaQuery.setAssessPerson(tfKpiManageDto.getAssessPerson());
        tfKpiManageAreaQuery.setAssessDate(assessDate);
        tfKpiManageAreaQuery.setAreaLevel(tfKpiManageDto.getAreaLevel());
        List<String> areaList = this.baseMapper.getKpiManageAreaList(tfKpiManageAreaQuery);
        List<String> areaListCollect = areaList.stream().distinct().collect(Collectors.toList());

        for(String area:areaListCollect){
            tfKpiManageAreaQuery.setAssessArea(area);
            Map<String,Object> census = new HashMap<>();
            census.put("assessArea",area);
            for(int j = 1;j < 5;j++){
                tfKpiManageAreaQuery.setAssessContent(String.valueOf(j));
                Integer scoreAll = this.baseMapper.getTfKpiManageScoreAll(tfKpiManageAreaQuery);
                Integer scoreCount = this.baseMapper.getTfKpiManageScoreCount(tfKpiManageAreaQuery);
                int scoreAvg;
                if(scoreAll!=null&&scoreCount!=0){
                    scoreAvg = scoreAll/scoreCount;
                }else{
                    scoreAvg = 0;
                }
                census.put("assessContent"+j, AssessContentEnum.getCodeForValue(String.valueOf(j)));
                census.put("assessContent"+j+"_assessAvgScore",scoreAvg);
            }
            tfKpiManages.add(census);
        }
        return tfKpiManages;
    }
}
