package org.jeecg.modules.stm.rectify.charts.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.time.DateUtils;
import org.jeecg.modules.stm.act.main.entity.StCaMain;
import org.jeecg.modules.stm.act.main.service.IStCaMainService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.jeecg.modules.stm.base.domain.entity.StDomain;
import org.jeecg.modules.stm.base.domain.service.IStDomainService;
import org.jeecg.modules.stm.rectify.assin.entity.StProblemTaskAssin;
import org.jeecg.modules.stm.rectify.assin.service.IStProblemTaskAssinService;
import org.jeecg.modules.stm.rectify.charts.service.RectifyChartService;
import org.jeecg.modules.stm.rectify.charts.vo.ChartVo;
import org.jeecg.modules.stm.rectify.plan.entity.StRectifyPlan;
import org.jeecg.modules.stm.rectify.plan.service.IStRectifyPlanService;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: yzh
 * @Date 2023/8/1 19:51
 * @Description:
 */
@Service
public class RectifyChartServiceImpl implements RectifyChartService {

    @Autowired
    private IStProblemTaskAssinService iStProblemTaskAssinService;

    @Autowired
    private IStRectifyPlanService iStRectifyPlanService;

    @Autowired
    private ISysDepartService iSysDepartService;

    @Autowired
    private IStDomainService iStDomainService;

    @Autowired
    private IStCaMainService iStCaMainService;

    @Override
    public ChartVo projectStatisticChart() {
        // 查询问题和项目数量
        QueryWrapper<StProblemTaskAssin> queryWrapper = new QueryWrapper<>();
        // 1、当年的
        Date now = new Date();
        Date startDate = DateUtil.beginOfYear(now);
        Date endDate = DateUtil.endOfYear(now);
        queryWrapper.between("CREATED_TIME",startDate,endDate);
        // 2、项目标志
        queryWrapper.eq("PROBLEM_SOURCE_FLAG","0");
        //3、统计问题数量 子项不包含父项 和 只有父项
        queryWrapper.and(wrapper -> wrapper.ne("PID","0").
                or(wrapper1 -> wrapper1.eq("PID","0").eq("HAS_CHILD","0")));
        List<StProblemTaskAssin> stProblemTaskAssinList = iStProblemTaskAssinService.list();
        if(CollectionUtils.isEmpty(stProblemTaskAssinList)){
            return null;
        }
        Map<String,List<StProblemTaskAssin>> dataMap = stProblemTaskAssinList.stream().filter(stProblemTaskAssin -> stProblemTaskAssin.getProjectNo()!=null).collect(Collectors.groupingBy(StProblemTaskAssin::getProjectNo));
        List<String> names = new ArrayList<>();
        List<Double> values = new ArrayList<>();
        for(String key: dataMap.keySet()){
            List<StProblemTaskAssin> item = dataMap.get(key);
            names.add(item.get(0).getProblemSource());
            // 问题数量
            int count = item.size();
            // 计算问题完成数量
            List<Integer> problemIds = item.stream().map(StProblemTaskAssin::getId).collect(Collectors.toList());
            QueryWrapper<StRectifyPlan> rectifyPlanQueryWrapper = new QueryWrapper<>();
            rectifyPlanQueryWrapper.in("PROBLEM_TASK_ID",problemIds);
            rectifyPlanQueryWrapper.eq("APPROVE_FLAG","3");
//            Date endDateNow = DateUtil.endOfDay(now);
//            rectifyPlanQueryWrapper.lt("END_DATE",endDateNow);
            long okCount = iStRectifyPlanService.count(rectifyPlanQueryWrapper);
            double var = new BigDecimal(okCount).
                    divide(new BigDecimal(count),2, RoundingMode.HALF_UP).
                    multiply(new BigDecimal("100")).
                    doubleValue();
            values.add(var);
        }
        ChartVo chartVo = new ChartVo();
        chartVo.setNames(names);
        chartVo.setValues(values);
        return chartVo;
    }

    @Override
    public List<SysDepart> problemDepList() {
        QueryWrapper<StProblemTaskAssin> queryWrapper = new QueryWrapper<>();
        // 1、当年的所有部门
        queryWrapper.select("HEAD_DEP_CODE");
        Date now = new Date();
        Date startDate = DateUtil.beginOfYear(now);
        Date endDate = DateUtil.endOfYear(now);
        queryWrapper.between("CREATED_TIME",startDate,endDate);
        queryWrapper.isNotNull("HEAD_DEP_CODE");
        List<StProblemTaskAssin> stProblemTaskAssinList = iStProblemTaskAssinService.list(queryWrapper);
        if(CollectionUtils.isEmpty(stProblemTaskAssinList)){
            return null;
        }
        List<String> data = stProblemTaskAssinList.stream().
                map(StProblemTaskAssin::getHeadDepCode).
                distinct().
                collect(Collectors.toList());
        QueryWrapper<SysDepart> sysDepartQueryWrapper = new QueryWrapper<>();
        sysDepartQueryWrapper.in("id",data);
        sysDepartQueryWrapper.orderByAsc("depart_order");
        List<SysDepart> list = iSysDepartService.list(sysDepartQueryWrapper);
        return list;
    }

    @Override
    public ChartVo problemDepStatisticChart(String depCode) {
        // 查询问题和项目数量
        QueryWrapper<StProblemTaskAssin> queryWrapper = new QueryWrapper<>();
//        // 1、当年的
        Date now = new Date();
//        Date startDate = DateUtil.beginOfYear(now);
//        Date endDate = DateUtil.endOfYear(now);
//        queryWrapper.between("CREATED_TIME",startDate,endDate);
        queryWrapper.eq("HEAD_DEP_CODE",depCode);
        //3、统计问题数量 子项不包含父项 和 只有父项
        queryWrapper.and(wrapper -> wrapper.ne("PID","0").
                or(wrapper1 -> wrapper1.eq("PID","0").eq("HAS_CHILD","0")));
        List<StProblemTaskAssin> stProblemTaskAssinList = iStProblemTaskAssinService.list(queryWrapper);
        if(CollectionUtils.isEmpty(stProblemTaskAssinList)){
            return null;
        }
        // 问题数量
        int count = stProblemTaskAssinList.size();
        List<String> names = new ArrayList<>();
        List<Double> values = new ArrayList<>();
        names.add("完成");
        // 计算问题完成数量
        List<Integer> problemIds = stProblemTaskAssinList.stream().map(StProblemTaskAssin::getId).collect(Collectors.toList());
        QueryWrapper<StRectifyPlan> rectifyPlanQueryWrapper = new QueryWrapper<>();
        rectifyPlanQueryWrapper.in("PROBLEM_TASK_ID",problemIds);
        // 3 标识已完成
        rectifyPlanQueryWrapper.eq("APPROVE_FLAG","3");
        //Date endDateNow = DateUtil.endOfDay(now);
        //rectifyPlanQueryWrapper.lt("END_DATE",endDateNow);
        long okCount = iStRectifyPlanService.count(rectifyPlanQueryWrapper);
        BigDecimal varBig = new BigDecimal(okCount).
                divide(new BigDecimal(count),2, RoundingMode.HALF_UP).
                multiply(new BigDecimal("100"));
        Double var = varBig.doubleValue();
        values.add(var);
        names.add("未完成");
        values.add((new BigDecimal("100").subtract(varBig)).doubleValue());
        ChartVo chartVo = new ChartVo();
        chartVo.setNames(names);
        chartVo.setValues(values);
        return chartVo;
    }

    @Override
    public ChartVo yearStatisticChart() {
        int startYear = 2023;
        Date now = new Date();
        int year = DateUtil.year(now);
        int len = year - startYear +1;
        List<String> names = new ArrayList<>();
        List<Double> values = new ArrayList<>();
        for(int i=0;i<len;i++){
            // 查询问题和项目数量
            QueryWrapper<StProblemTaskAssin> queryWrapper = new QueryWrapper<>();
            // 23年开始的任务
            Date newDate = DateUtils.setYears(now,(startYear+i));
            Date startDate = DateUtil.beginOfYear(newDate);
            Date endDate = DateUtil.endOfYear(newDate);
            queryWrapper.between("CREATED_TIME",startDate,endDate);
            //3、统计问题数量 子项不包含父项 和 只有父项
            queryWrapper.and(wrapper -> wrapper.ne("PID","0").
                    or(wrapper1 -> wrapper1.eq("PID","0").eq("HAS_CHILD","0")));
            List<StProblemTaskAssin> stProblemTaskAssinList = iStProblemTaskAssinService.list(queryWrapper);
            if(CollectionUtils.isEmpty(stProblemTaskAssinList)){
                return null;
            }
            // 问题数量
            int count = stProblemTaskAssinList.size();
            names.add(String.format("%s", (startYear+i)));
            // 计算问题完成数量
            List<Integer> problemIds = stProblemTaskAssinList.stream().map(StProblemTaskAssin::getId).collect(Collectors.toList());
            QueryWrapper<StRectifyPlan> rectifyPlanQueryWrapper = new QueryWrapper<>();
            rectifyPlanQueryWrapper.in("PROBLEM_TASK_ID",problemIds);
            rectifyPlanQueryWrapper.eq("APPROVE_FLAG","3");
//            if(i==(len-1)){
//                Date endDateNow = DateUtil.endOfDay(now);
//                rectifyPlanQueryWrapper.lt("END_DATE", endDateNow);
//            }else {
//                rectifyPlanQueryWrapper.lt("END_DATE", endDate);
//            }
            long okCount = iStRectifyPlanService.count(rectifyPlanQueryWrapper);
            double var = new BigDecimal(okCount).
                    divide(new BigDecimal(count),2, RoundingMode.HALF_UP).
                    multiply(new BigDecimal("100")).
                    doubleValue();
            values.add(var);
        }
        ChartVo chartVo = new ChartVo();
        chartVo.setNames(names);
        chartVo.setValues(values);
        return chartVo;
    }

    @Override
    public ChartVo domainStatisticChart() {
        // 统计所有领域的父级领域
        QueryWrapper<StDomain> domainQueryWrapper = new QueryWrapper<>();
        domainQueryWrapper.eq("LEVEL","1");
        List<StDomain> stDomainList = iStDomainService.list(domainQueryWrapper);
        Map<String,List<String>> domCodeActNosMap = new HashMap<>();
        Map<String,String> domCodeNamesMap = new HashMap<>();
        for(StDomain stDomain:stDomainList) {
            List<String> childCodes = new ArrayList<>();
            childCodes.add(stDomain.getDomainCode());
            getChildDominCodes(stDomain, childCodes);
            QueryWrapper<StCaMain> caMainQueryWrapper = new QueryWrapper<>();
            caMainQueryWrapper.select("CA_NO");
            caMainQueryWrapper.in("DOMAIN_CODE",childCodes);
            List<StCaMain> caMainList = iStCaMainService.list(caMainQueryWrapper);
            if(CollectionUtils.isEmpty(caMainList)){
                continue;
            }
            List<String> caNos = caMainList.stream().map(StCaMain::getCaNo).collect(Collectors.toList());
            domCodeActNosMap.put(stDomain.getDomainCode(),caNos);
            domCodeNamesMap.put(stDomain.getDomainCode(),stDomain.getDomainName());
        }
        List<String> names = new ArrayList<>();
        List<Double> values = new ArrayList<>();
        for(String key:domCodeNamesMap.keySet()){
            List<String> caNos = domCodeActNosMap.get(key);
            // 查询问题和项目数量
            QueryWrapper<StProblemTaskAssin> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("ACT_NO",caNos);
            //统计问题数量 子项不包含父项 和 只有父项
            queryWrapper.and(wrapper -> wrapper.ne("PID","0").
                    or(wrapper1 -> wrapper1.eq("PID","0").eq("HAS_CHILD","0")));
            List<StProblemTaskAssin> stProblemTaskAssinList = iStProblemTaskAssinService.list(queryWrapper);
            if(CollectionUtils.isEmpty(stProblemTaskAssinList)){
                continue;
            }
            names.add(domCodeNamesMap.get(key));
            // 问题数量
            int count = stProblemTaskAssinList.size();
            // 计算问题完成数量
            List<Integer> problemIds = stProblemTaskAssinList.stream().map(StProblemTaskAssin::getId).collect(Collectors.toList());
            QueryWrapper<StRectifyPlan> rectifyPlanQueryWrapper = new QueryWrapper<>();
            rectifyPlanQueryWrapper.in("PROBLEM_TASK_ID",problemIds);
            rectifyPlanQueryWrapper.eq("APPROVE_FLAG","3");
//            Date endDateNow = DateUtil.endOfDay(new Date());
//            rectifyPlanQueryWrapper.lt("END_DATE",endDateNow);
            long okCount = iStRectifyPlanService.count(rectifyPlanQueryWrapper);
            double var = new BigDecimal(okCount).
                    divide(new BigDecimal(count),2, RoundingMode.HALF_UP).
                    multiply(new BigDecimal("100")).
                    doubleValue();
            values.add(var);
        }
        ChartVo chartVo = new ChartVo();
        chartVo.setNames(names);
        chartVo.setValues(values);
        return chartVo;
    }

    private void getChildDominCodes(StDomain stDomain, List<String> childCodes) {
        QueryWrapper<StDomain> domainQueryWrapper = new QueryWrapper<>();
        domainQueryWrapper.eq("UPPER_DOMAIN_CODE",stDomain.getDomainCode());
        List<StDomain> stDomainList = iStDomainService.list(domainQueryWrapper);
        if(CollectionUtils.isEmpty(stDomainList)){
            return;
        }
        for(StDomain stDomain1:stDomainList){
            childCodes.add(stDomain1.getDomainCode());
            getChildDominCodes(stDomain1,childCodes);
        }
    }


}
