package com.artfess.yhxt.statistics.manager.impl;

import cn.hutool.core.bean.BeanUtil;
import com.artfess.base.query.QueryFilter;
import com.artfess.sysConfig.persistence.manager.SysDictionaryManager;
import com.artfess.sysConfig.persistence.model.SysDictionaryDetail;
import com.artfess.yhxt.basedata.dao.RoadDao;
import com.artfess.yhxt.basedata.manager.BizCourseDetailsManager;
import com.artfess.yhxt.basedata.manager.RoadManager;
import com.artfess.yhxt.basedata.model.Road;
import com.artfess.yhxt.budget.manager.YearBudgetDetailedManager;
import com.artfess.yhxt.budget.manager.YearBudgetManager;
import com.artfess.yhxt.budget.model.YearBudget;
import com.artfess.yhxt.budget.model.YearBudgetDetailed;
import com.artfess.yhxt.contract.dao.WorkOrderInformationDao;
import com.artfess.yhxt.contract.manager.WorkOrderInformationManager;
import com.artfess.yhxt.contract.model.WorkOrderInformation;
import com.artfess.yhxt.disease.model.Disease;
import com.artfess.yhxt.schedule.StatisticsSchedule;
import com.artfess.yhxt.specialproject.manager.BizEngineeringProjectManager;
import com.artfess.yhxt.specialproject.manager.BizProjectContractDetailsManager;
import com.artfess.yhxt.specialproject.manager.BizProjectContractManager;
import com.artfess.yhxt.specialproject.manager.ProjectAcceptanceManager;
import com.artfess.yhxt.specialproject.model.BizEngineeringProject;
import com.artfess.yhxt.specialproject.model.ProjectAcceptance;
import com.artfess.yhxt.statistics.dao.SiteStatisticDao;
import com.artfess.yhxt.statistics.model.SiteStatistic;
import com.artfess.yhxt.statistics.model.WorkStatistic;
import com.artfess.yhxt.statistics.dao.WorkStatisticDao;
import com.artfess.yhxt.statistics.manager.WorkStatisticManager;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.yhxt.statistics.model.YearBudgetSum;
import com.artfess.yhxt.statistics.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author xzh
 * @company 阿特菲斯信息技术有限公司
 * @since 2021-10-26
 */
@Service
public class WorkStatisticManagerImpl extends BaseManagerImpl<WorkStatisticDao, WorkStatistic> implements WorkStatisticManager {

    @Resource
    private RoadDao roadDao;
    @Resource
    private BizCourseDetailsManager bizCourseDetailsManager;
    @Resource
    private WorkOrderInformationManager workOrderInformationManager;

    @Resource
    private RoadManager roadManager;
    @Resource
    private BizEngineeringProjectManager bizEngineeringProjectManager;
    @Resource
    private StatisticsSchedule statisticsSchedule;

    @Resource
    private SiteStatisticDao siteStatisticDao;

    @Resource
    private SysDictionaryManager sysDictionaryManager;
    @Resource
    private YearBudgetManager yearBudgetManager;
    @Resource
    private YearBudgetDetailedManager yearBudgetDetailedManager;
    @Resource
    private ProjectAcceptanceManager projectAcceptanceManager;
    @Resource
    private BizProjectContractManager bizProjectContractManager;
    @Resource
    private BizProjectContractDetailsManager bizProjectContractDetailsManager;
    @Resource
    private WorkOrderInformationDao workOrderInformationDao;

    @Override
    public List<WorkStatistic> getWorkJson(QueryFilter<WorkStatistic> queryFilter) {
        try {
            statisticsSchedule.scheduleWorkeCount();
            Map params = queryFilter.getParams();
            List<WorkStatistic> workStatisticArrayList = new ArrayList<>();
            QueryWrapper<Road> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(ObjectUtils.isNotEmpty(params.get("companyId")), "COMPANY_ID", params.get("companyId"));
            queryWrapper.eq(ObjectUtils.isNotEmpty(params.get("roadSegmentId")), "ID_", params.get("roadSegmentId"));
            queryWrapper.eq("IS_DELE_", "0");
            List<Road> list = roadManager.list(queryWrapper);
            if (list.size() > 0) {
                for (Road road : list) {
                    if (ObjectUtils.isEmpty(params.get("accDateYear")) && ObjectUtils.isEmpty(params.get("accDateMonth"))) {
                        String mouth = new SimpleDateFormat("yyyy-MM").format(new Date());
                        params.put("accDateMonth", mouth);
                    }
                    WorkStatistic workStatistic = this.baseMapper.countWorkStatistic(params, road.getId());
                    if (workStatistic == null) {
                        workStatistic = new WorkStatistic();
                    }
                    workStatistic.setRoadSegmentId(road.getId());
                    workStatistic.setRoadSegmentName(road.getName());
                    workStatisticArrayList.add(workStatistic);


                }
            }
            return workStatisticArrayList;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    public List<SiteStatistic> getSiteJson(QueryFilter<WorkStatistic> queryFilter) {
        Map params = queryFilter.getParams();
        List<SiteStatistic> siteStatistics = new ArrayList<>();
        QueryWrapper<Road> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjectUtils.isNotEmpty(params.get("companyId")), "COMPANY_ID", params.get("companyId"));
        queryWrapper.eq(ObjectUtils.isNotEmpty(params.get("roadSegmentId")), "ID_", params.get("roadSegmentId"));
        queryWrapper.eq("IS_DELE_", "0");
        List<Road> list = roadManager.list(queryWrapper);
        if (list.size() > 0) {
            for (Road road : list) {
                if (ObjectUtils.isEmpty(params.get("accDateYear")) && ObjectUtils.isEmpty(params.get("accDateMonth"))) {
                    String mouth = new SimpleDateFormat("yyyy-MM").format(new Date());
                    params.put("accDateMonth", mouth);
                }
                SiteStatistic siteStatistic = this.baseMapper.countSiteStatistic(params, road.getId());
                siteStatistic.setRoadSegmentId(road.getId());
                siteStatistic.setRoadSegmentName(road.getName());
                siteStatistic.setAccDateMonth(params.get("accDateMonth").toString());
                siteStatistics.add(siteStatistic);
            }
        }

        return siteStatistics;

/*        Map<String, Object> map = queryFilter.getParams();
        Object companyId = map.get("companyId");
        Object roadSegmentId = map.get("roadSegmentId");
        if ((companyId != null && StringUtils.isNotBlank(String.valueOf(companyId))) ||
                (null != roadSegmentId && StringUtils.isNotBlank(String.valueOf(roadSegmentId)))) {

            return this.baseMapper.getCompanySiteJson(map);
        } else {
            return this.baseMapper.getSiteJson(map);
        }*/
    }

    @Override
    public List<CheckVo> getCheckJson(QueryFilter<WorkStatistic> queryFilter) {
        Map<String, Object> params = queryFilter.getParams();
        if (ObjectUtils.isEmpty(params.get("accDateYear")) && ObjectUtils.isEmpty(params.get("accDateMonth"))) {
            String mouth = new SimpleDateFormat("yyyy-MM").format(new Date());
            params.put("accDateMonth", mouth);
        }
        return this.baseMapper.getCheckJson(params);
    }

    @Override
    public List<CheckRoadVo> getCheckRodeJson(QueryFilter<WorkStatistic> queryFilter) {
        Map params = queryFilter.getParams();
        List<CheckRoadVo> checkRoadVos = new ArrayList<>();
        QueryWrapper<Road> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjectUtils.isNotEmpty(params.get("companyId")), "COMPANY_ID", params.get("companyId"));
        queryWrapper.eq(ObjectUtils.isNotEmpty(params.get("roadSegmentId")), "ID_", params.get("roadSegmentId"));
        queryWrapper.eq("IS_DELE_", "0");
        List<Road> list = roadManager.list(queryWrapper);
        if (ObjectUtils.isEmpty(params.get("accDateYear")) && ObjectUtils.isEmpty(params.get("accDateMonth"))) {
            String year = new SimpleDateFormat("yyyy").format(new Date());
            params.put("accDateYear", year);
        }
        if (list.size() > 0) {
            for (Road road : list) {
                List<CheckVo> checkVo = this.baseMapper.countcheckVo(params, road.getId());
                CheckRoadVo checkRoadVo = new CheckRoadVo();
                checkRoadVo.setRoadSegmentId(road.getId());
                checkRoadVo.setRoadSegmentName(road.getName());
                checkRoadVo.setCheckVos(checkVo);
                checkRoadVos.add(checkRoadVo);
            }
        }
        return checkRoadVos;
    }

    @Override
    public List<CountSpecialProject> countSpecialProject(QueryFilter<WorkStatistic> queryFilter) {
        ArrayList<CountSpecialProject> countSpecialProjects = new ArrayList<>();

        Map<String, Object> params = queryFilter.getParams();

        if (ObjectUtils.isNotEmpty(params.get("accDateMonth"))) {
            String[] split = params.get("accDateMonth").toString().split("-");
            params.put("accDateYear", split[0]);
        }
        if (ObjectUtils.isEmpty(params.get("accDateYear")) && ObjectUtils.isEmpty(params.get("accDateMonth"))) {
            String year = new SimpleDateFormat("yyyy").format(new Date());
            params.put("accDateYear", year);
        }
        QueryWrapper<Road> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("IS_DELE_", "0");
        queryWrapper.eq(ObjectUtils.isNotEmpty(params.get("roadSegmentId")), "id_", params.get("roadSegmentId"));
        List<Road> roadList = roadDao.selectList(queryWrapper);
        for (Road road : roadList) {
            CountSpecialProject countSpecialProject = new CountSpecialProject();
            countSpecialProject.setRoadSegmentId(road.getId());
            countSpecialProject.setRoadSegmentName(road.getName());
            //专项个数计划项目
            QueryWrapper<YearBudget> queryWrapperYearBudget = new QueryWrapper<>();
            queryWrapperYearBudget.eq("IS_DELE_", "0");
            queryWrapperYearBudget.eq("ROAD_SEGMENT_ID_", road.getId());
            queryWrapperYearBudget.eq(ObjectUtils.isNotEmpty(params.get("accDateYear")), "ASCRIPTION_YEAR_", params.get("accDateYear"));

            YearBudget yearBudget = yearBudgetManager.getOne(queryWrapperYearBudget);

            if (yearBudget != null) {
                //专项
                QueryWrapper<YearBudgetDetailed> yearBudgetDetailedQueryWrapperFRCZX = new QueryWrapper<>();
                yearBudgetDetailedQueryWrapperFRCZX.eq("YEAR_BUDGET_ID_", yearBudget.getId());
                yearBudgetDetailedQueryWrapperFRCZX.eq("BUDGET_TYPE_", "FRCZX");
                List<YearBudgetDetailed> yearBudgetDetailedListFRCZX = yearBudgetDetailedManager.list(yearBudgetDetailedQueryWrapperFRCZX);
                countSpecialProject.setPlannedProject(String.valueOf(yearBudgetDetailedListFRCZX.size()));
                BigDecimal projectProgram = yearBudgetDetailedListFRCZX.stream().filter(s -> s != null && s.getTotalPrice() != null).map(YearBudgetDetailed::getTotalPrice)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
//                countSpecialProject.setProjectProgram(projectProgram.toString());


            }

            //专项进行中数量
            QueryWrapper<BizEngineeringProject> runWrapper = new QueryWrapper<>();
            runWrapper.eq("ROAD_SEGMENT_ID_", road.getId());
            runWrapper.eq("PROJECT_TYPE_", "2");
            runWrapper.eq("IS_DELE_","0");
            runWrapper.eq("STARTUP_FLAG_","1");
            countSpecialProject.setRunningProject(String.valueOf(bizEngineeringProjectManager.list(runWrapper).size()));

            //专项实际完成个数
            QueryWrapper<BizEngineeringProject> unQueryWrapperProject = new QueryWrapper<>();
            unQueryWrapperProject.eq("ROAD_SEGMENT_ID_", road.getId());
            unQueryWrapperProject.eq("PROJECT_TYPE_", "2");
            unQueryWrapperProject.eq("IS_DELE_","0");
            unQueryWrapperProject.eq(ObjectUtils.isNotEmpty(params.get("accDateYear")), "PROJECT_YEAR_", params.get("accDateYear"));
            List<BizEngineeringProject> list = bizEngineeringProjectManager.list(unQueryWrapperProject);
            if (list.size() > 0) {
                String projectIds = list.stream().map(BizEngineeringProject::getId).collect(Collectors.joining(","));
                List<String> ids = Arrays.asList(projectIds.split(","));
                QueryWrapper<ProjectAcceptance> acceptanceQueryWrapper = new QueryWrapper<>();
                acceptanceQueryWrapper.in("PROJECT_ID_", ids);
                int count = projectAcceptanceManager.count(acceptanceQueryWrapper);
                countSpecialProject.setFinishProject(String.valueOf(count));
            }

            countSpecialProjects.add(countSpecialProject);
        }

        //

        return countSpecialProjects;
    }

    @Override
    public List<YearBudgetSum> countYearBudgetData(QueryFilter<WorkStatistic> queryFilter) {

        Map<String, Object> params = queryFilter.getParams();
        Object accDateMonth = params.get("accDateMonth");
        if (ObjectUtils.isNotEmpty(accDateMonth)) {
            String[] split = accDateMonth.toString().split("-");
            params.put("accDateMonth", split[0]);
        }
        if (ObjectUtils.isEmpty(params.get("accDateYear")) && ObjectUtils.isEmpty(params.get("accDateMonth"))) {
            String year = new SimpleDateFormat("yyyy").format(new Date());
            params.put("accDateYear", year);
        }
        return this.baseMapper.countYearBudgetData(params);
    }

    @Override
    public List<SiteStatistic> countCheckJsonDetail() {
        QueryWrapper<SiteStatistic> queryWrapper = new QueryWrapper<>();
        return siteStatisticDao.selectList(queryWrapper);
    }

    @Override
    public List<MoneyVo> getMoneyJson(QueryFilter<WorkStatistic> queryFilter) {
        Map params = queryFilter.getParams();
        List<MoneyVo> moneyVos = new ArrayList<>();
        QueryWrapper<Road> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjectUtils.isNotEmpty(params.get("companyId")), "COMPANY_ID", params.get("companyId"));
        queryWrapper.eq(ObjectUtils.isNotEmpty(params.get("roadSegmentId")), "ID_", params.get("roadSegmentId"));
        queryWrapper.eq("IS_DELE_", "0");
        List<Road> list = roadManager.list(queryWrapper);
        if (ObjectUtils.isEmpty(params.get("accDateYear")) && ObjectUtils.isEmpty(params.get("accDateMonth"))) {
            String year = new SimpleDateFormat("yyyy").format(new Date());
            params.put("accDateYear", year);
        }
        if (list.size() > 0) {
            for (Road road : list) {
                MoneyVo moneyVo = this.baseMapper.countMoneyRoadSegment(params, road.getId());
                if (moneyVo == null) moneyVo = new MoneyVo();
                moneyVo.setRoadSegmentId(road.getId());
                moneyVo.setRoadSegmentName(road.getName());
                moneyVos.add(moneyVo);
            }
        }

        return moneyVos;

/*        Map<String, Object> map = queryFilter.getParams();

        return this.baseMapper.getMoneyRoadSegmentIdJson(map);*/
    }

    @Override
    public List<YearBudgetSum> getYearBudgetJson(QueryFilter<WorkStatistic> queryFilter) {
        Map<String, Object> params = queryFilter.getParams();
        Object accDateMonth = params.get("accDateMonth");
        if (ObjectUtils.isNotEmpty(accDateMonth)) {
            String[] split = accDateMonth.toString().split("-");
            params.put("accDateMonth", split[0]);
        }
        if (ObjectUtils.isEmpty(params.get("accDateYear")) && ObjectUtils.isEmpty(params.get("accDateMonth"))) {
            String year = new SimpleDateFormat("yyyy").format(new Date());
            params.put("accDateYear", year);
        }
        return this.baseMapper.getYearBudgetJson(params);
    }

    @Override
    public List<CountDisease> countAmountDisease(QueryFilter queryFilter) {
        Map params = queryFilter.getParams();
        Object roadId = params.get("roadSegmentId");
        List<CountDisease> countDiseaseList = new ArrayList<>();
        if (ObjectUtils.isEmpty(params.get("accDateYear")) && ObjectUtils.isEmpty(params.get("accDateMonth"))) {
            String mouth = new SimpleDateFormat("yyyy-MM").format(new Date());
            params.put("accDateMonth", mouth);
        }
        if (ObjectUtils.isEmpty(roadId)) {
            QueryWrapper<Road> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("IS_DELE_", "0");
            List<Road> roadList = roadDao.selectList(queryWrapper);
            for (Road road : roadList) {
                CountDisease countDisease = new CountDisease();
                String id = road.getId();
                params.put("roadSegmentId", id);
                Integer finished = this.baseMapper.countAmountDiseaseFinished(params);
                Integer unFinished = this.baseMapper.countAmountDiseaseUnFinished(params);
                countDisease.setRoadId(road.getId());
                countDisease.setRoadName(road.getName());
                countDisease.setCountDisFinished(finished.toString());
                countDisease.setCountDisUnFinished(unFinished.toString());
                countDiseaseList.add(countDisease);
            }
        } else {
            CountDisease countDisease = new CountDisease();
            String id = roadId.toString();
            Integer finished = this.baseMapper.countAmountDiseaseFinished(params);
            Integer unFinished = this.baseMapper.countAmountDiseaseUnFinished(params);
            Road road = roadDao.selectById(id);
            countDisease.setRoadId(id);
            countDisease.setRoadName(road.getName());
            QueryWrapper<Road> queryWrapper = new QueryWrapper<>();
            countDisease.setRoadName(roadDao.selectOne(queryWrapper.eq("ID_", id)).getName());
            countDisease.setCountDisFinished(finished.toString());
            countDisease.setCountDisUnFinished(unFinished.toString());
            countDiseaseList.add(countDisease);
        }
        return countDiseaseList;
    }

    @Override
    public List<CountTypeDisease> countTypeDisease(QueryFilter queryFilter) {
        try {
            Map<String, List<SysDictionaryDetail>> bhlx = sysDictionaryManager.queryDictItemsByCode("bhlx");
            Map params = queryFilter.getParams();
            Object roadId = params.get("roadSegmentId");
            List<CountTypeDisease> countTypeDiseases = new ArrayList<>();
            if (ObjectUtils.isEmpty(params.get("accDateYear")) && ObjectUtils.isEmpty(params.get("accDateMonth"))) {
                String mouth = new SimpleDateFormat("yyyy-MM").format(new Date());
                params.put("accDateMonth", mouth);
            }
            if (ObjectUtils.isEmpty(roadId)){
                QueryWrapper<Road> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("IS_DELE_", "0");
                List<Road> roadList = roadDao.selectList(queryWrapper);
                for (Road road : roadList) {

                    List<SysDictionaryDetail> list = bhlx.get("bhlx");
                    ArrayList<SysDictionaryDetail> sysDictionaryDetails = new ArrayList<>();
                    for (int i = 0; i < list.size(); i++) {
                        SysDictionaryDetail detail = null;
                        try {
                            Map map = (Map) list.get(i);
                            detail = BeanUtil.toBean(map, SysDictionaryDetail.class);
                        } catch (Exception e) {
                            e.printStackTrace();
                            detail=list.get(i);
                        }
                        sysDictionaryDetails.add(detail);
                    }

                    for (SysDictionaryDetail sysDictionaryDetail : sysDictionaryDetails) {
                        params.put("roadSegmentId",road.getId());
                        params.put("type",sysDictionaryDetail.getValue());
                        List<Disease> countType = this.baseMapper.countTypeDisease(params);
                        CountTypeDisease countTypeDisease = new CountTypeDisease();
                        countTypeDisease.setSubjectName(sysDictionaryDetail.getName());
                        countTypeDisease.setSubjectCode(sysDictionaryDetail.getValue());
                        countTypeDisease.setRoadSegmentId(road.getId());
                        countTypeDisease.setRoadSegmentName(road.getName());
                        countTypeDisease.setCountTypeDis(String.valueOf(countType.size()));
                        countTypeDiseases.add(countTypeDisease);
                    }


                }
                return countTypeDiseases;
            }else {

                List<SysDictionaryDetail> list = bhlx.get("bhlx");
                ArrayList<SysDictionaryDetail> sysDictionaryDetails = new ArrayList<>();
                Road road = roadDao.selectById(roadId.toString());
                for (int i = 0; i < list.size(); i++) {
                    Map map = (Map) list.get(i);
                    SysDictionaryDetail detail = BeanUtil.toBean(map, SysDictionaryDetail.class);
                    sysDictionaryDetails.add(detail);
                }

                for (SysDictionaryDetail sysDictionaryDetail : sysDictionaryDetails) {
                    params.put("type",sysDictionaryDetail.getValue());
                    List<Disease> countType = this.baseMapper.countTypeDisease(params);
                    CountTypeDisease countTypeDisease = new CountTypeDisease();
                    countTypeDisease.setSubjectName(sysDictionaryDetail.getName());
                    countTypeDisease.setSubjectCode(sysDictionaryDetail.getValue());
                    countTypeDisease.setRoadSegmentId(road.getId());
                    countTypeDisease.setRoadSegmentName(road.getName());
                    countTypeDisease.setCountTypeDis(String.valueOf(countType.size()));
                    countTypeDiseases.add(countTypeDisease);
                }


                return countTypeDiseases;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<CountDayDisease> countDayDisease(QueryFilter queryFilter) {
        List<CountDayDisease> countDayDiseases = new ArrayList<>();
        Map params = queryFilter.getParams();
        Object roadId = params.get("roadSegmentId");
        if (ObjectUtils.isEmpty(params.get("accDateYear")) && ObjectUtils.isEmpty(params.get("accDateMonth"))) {
            String mouth = new SimpleDateFormat("yyyy-MM").format(new Date());
            params.put("accDateMonth", mouth);
        }
        if (ObjectUtils.isEmpty(roadId)) {
            QueryWrapper<Road> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("IS_DELE_", "0");
            List<Road> roadList = roadDao.selectList(queryWrapper);
            for (Road road : roadList) {
                CountDayDisease countDayDisease = new CountDayDisease();
                String id = road.getId();
                //查询路段解决病害的总天数
                params.put("roadSegmentId", id);
                Integer daySum = this.baseMapper.countDayDiseaseSum(params);
                //查询病害的总数
                Integer diseaseSum = this.baseMapper.countDiseaseSum(params);
                Integer avg;
                if (diseaseSum != 0) {
                    avg = daySum / diseaseSum;
                } else {
                    avg = 0;
                }
                countDayDisease.setRoadId(road.getId());
                countDayDisease.setRoadName(road.getName());
                countDayDisease.setCountDayAvg(avg.toString());
                countDayDiseases.add(countDayDisease);
            }
        } else {
            CountDayDisease countDayDisease = new CountDayDisease();
            String id = roadId.toString();
            //查询路段解决病害的总天数
            Integer daySum = this.baseMapper.countDayDiseaseSum(params);
            //查询病害的总数
            Integer diseaseSum = this.baseMapper.countDiseaseSum(params);
            Integer avg;
            if (diseaseSum != 0) {
                avg = daySum / diseaseSum;
            } else {
                avg = 0;
            }
            countDayDisease.setRoadId(id);
            QueryWrapper<Road> queryWrapper = new QueryWrapper<>();
            countDayDisease.setRoadName(roadDao.selectOne(queryWrapper.eq("ID_", id)).getName());
            countDayDisease.setCountDayAvg(avg.toString());

            countDayDiseases.add(countDayDisease);
        }

        return countDayDiseases;
    }

    @Override
    public List<NewCountWorkOrderVo> newCountWorkOrder(QueryFilter<WorkStatistic> queryFilter) {
        QueryWrapper<WorkOrderInformation> orderQueryWrapper = new QueryWrapper<>();
        Map<String, Object> params = queryFilter.getParams();
        if (ObjectUtils.isEmpty(params.get("accDateYear")) && ObjectUtils.isEmpty(params.get("accDateMonth"))) {
            String mouth = new SimpleDateFormat("yyyy-MM").format(new Date());
            params.put("accDateMonth", mouth);
        }
        if (ObjectUtils.isNotEmpty(params.get("roadSegmentId"))){
            List<String> ids = Arrays.asList(params.get("roadSegmentId").toString().split(","));
            params.put("ids",ids);
            orderQueryWrapper.in("ROAD_SEGMENT_ID_", ids);
        }
        List<Map<String, Object>> mapList = this.baseMapper.countWorkOrder(params);

        //返回集合
        List<NewCountWorkOrderVo> returnList = new ArrayList<>();

        //通过路段名分组
        Map<String, List<Map<String, Object>>> groupMap = mapList.stream().collect(Collectors.groupingBy(e -> e.get("roadName").toString()));
        //返回子集合
        List<NewWorkCountVo> task1Children = new ArrayList<>();
        List<NewWorkCountVo>  task2Children = new ArrayList<>();
        List<NewWorkCountVo>  task4Children = new ArrayList<>();
        List<NewWorkCountVo>  task5Children = new ArrayList<>();
        List<NewWorkCountVo>  endChildren = new ArrayList<>();
        List<NewWorkCountVo>  overChildren = new ArrayList<>();


        //养护站下单[业主]
        long userTask1 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask1")).count();

        for(String key:groupMap.keySet()){


            long task1Count = groupMap.get(key).stream().filter(s -> s.get("taskKey").equals("UserTask1")).count();
            long task7Count = groupMap.get(key).stream().filter(s -> s.get("taskKey").equals("UserTask7")).count();

            long task2Count = groupMap.get(key).stream().filter(s -> s.get("taskKey").equals("UserTask2")).count();
            long task3Count = groupMap.get(key).stream().filter(s -> s.get("taskKey").equals("UserTask3")).count();

            long task4Count = groupMap.get(key).stream().filter(s -> s.get("taskKey").equals("UserTask4")).count();

            long task5Count = groupMap.get(key).stream().filter(s -> s.get("taskKey").equals("UserTask5")).count();
            long task6Count = groupMap.get(key).stream().filter(s -> s.get("taskKey").equals("UserTask6")).count();

            long endCount = groupMap.get(key).stream().filter(s -> s.get("taskKey").equals("EndEvent1")).count();
            if (!"0".equals(String.valueOf(task1Count + task7Count))){
                NewWorkCountVo task1 = new NewWorkCountVo();
                task1.setNumber(task1Count + task7Count);
                task1.setRoadName(key);
                QueryWrapper<Road> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("IS_DELE_", "0");
                queryWrapper.eq("NAME_", key);
                List<Road> roadList = roadDao.selectList(queryWrapper);
                if (roadList.size()>0){
                    task1.setRoadId(roadList.get(0).getId());
                }
                task1Children.add(task1);
            }
            if (!"0".equals(String.valueOf(task2Count + task3Count))){
                NewWorkCountVo task2 = new NewWorkCountVo();
                task2.setNumber(task2Count + task3Count);
                task2.setRoadName(key);
                QueryWrapper<Road> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("IS_DELE_", "0");
                queryWrapper.eq("NAME_", key);
                List<Road> roadList = roadDao.selectList(queryWrapper);
                if (roadList.size()>0){
                    task2.setRoadId(roadList.get(0).getId());
                }
                task2Children.add(task2);
            }
            if (!"0".equals(String.valueOf(task4Count))){
                NewWorkCountVo task4 = new NewWorkCountVo();
                task4.setNumber(task4Count);
                task4.setRoadName(key);
                QueryWrapper<Road> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("IS_DELE_", "0");
                queryWrapper.eq("NAME_", key);
                List<Road> roadList = roadDao.selectList(queryWrapper);
                if (roadList.size()>0){
                    task4.setRoadId(roadList.get(0).getId());
                }
                task4Children.add(task4);
            }
            if (!"0".equals(String.valueOf(task5Count + task6Count))){
                NewWorkCountVo task5 = new NewWorkCountVo();
                task5.setNumber(task5Count+task6Count);
                task5.setRoadName(key);
                QueryWrapper<Road> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("IS_DELE_", "0");
                queryWrapper.eq("NAME_", key);
                List<Road> roadList = roadDao.selectList(queryWrapper);
                if (roadList.size()>0){
                    task5.setRoadId(roadList.get(0).getId());
                }
                task5Children.add(task5);
            }
            if (!"0".equals(String.valueOf(endCount))){
                NewWorkCountVo taskEnd = new NewWorkCountVo();
                taskEnd.setNumber(endCount);
                taskEnd.setRoadName(key);
                QueryWrapper<Road> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("IS_DELE_", "0");
                queryWrapper.eq("NAME_", key);
                List<Road> roadList = roadDao.selectList(queryWrapper);
                if (roadList.size()>0){
                    taskEnd.setRoadId(roadList.get(0).getId());
                }
                endChildren.add(taskEnd);
            }


        }
        //管理中心确认[业主]
        long userTask7 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask7")).count();
        //派单中
        NewCountWorkOrderVo pdVo = new NewCountWorkOrderVo();
        pdVo.setName("派单中");
        pdVo.setNumber(String.valueOf(userTask1 + userTask7));
        pdVo.setChildren(task1Children);
        returnList.add(pdVo);
        //养护单位派单[施工]
        long userTask2 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask2")).count();
        //养护单位填报[施工]
        long userTask3 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask3")).count();

        //施工中数
        NewCountWorkOrderVo sgVo = new NewCountWorkOrderVo();
        sgVo.setName("施工中");
        sgVo.setNumber(String.valueOf(userTask2 + userTask3));
        sgVo.setChildren(task2Children);
        returnList.add(sgVo);
        //收方计量[业主]
        long userTask4 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask4")).count();

        //施工单位验收
        NewCountWorkOrderVo ysVo = new NewCountWorkOrderVo();
        ysVo.setName("施工单位验收");
        ysVo.setNumber(String.valueOf(userTask4 + userTask7));
        ysVo.setChildren(task4Children);
        returnList.add(ysVo);
        //养护站审核[业主]
        long userTask5 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask5")).count();
        long userTask6 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask6")).count();

        //审核中数
        NewCountWorkOrderVo shVo = new NewCountWorkOrderVo();
        shVo.setName("审核中");
        shVo.setNumber(String.valueOf(userTask5 + userTask6));
        shVo.setChildren(task5Children);
        returnList.add(shVo);

        //完成工单
        long endEvent1 = mapList.stream().filter(s -> s.get("taskKey").equals("EndEvent1")).count();

        //完成
        NewCountWorkOrderVo endVo = new NewCountWorkOrderVo();
        endVo.setName("已完成");
        endVo.setNumber(String.valueOf(endEvent1));
        endVo.setChildren(endChildren);
        returnList.add(endVo);

        //逾期工单  DEMAND_FINISH_TIME_  END_TIME_

        orderQueryWrapper.eq("OVERDUE_", "1");
        orderQueryWrapper.eq("IS_DELE_", "0");
        if (ObjectUtils.isNotEmpty(params.get("accDateMonth"))){
            Object month = params.get("accDateMonth");
            orderQueryWrapper.apply("date_format(ISSUE_DATE_,'%Y-%m') = {0}",month);
        }

        List<WorkOrderInformation> overList = workOrderInformationDao.selectList(orderQueryWrapper);


        //逾期分组
        Map<String, List<WorkOrderInformation>> overMap = overList.stream().collect(Collectors.groupingBy(WorkOrderInformation::getRoadSegmentId));

        for(String key:overMap.keySet()){
            Map<String,Object> overdueMap = new HashMap<>();
            Road road = roadManager.getById(key);
            if (overMap.get(key).size()>0){
                NewWorkCountVo taskOver = new NewWorkCountVo();
                taskOver.setNumber(overMap.get(key).size());
                taskOver.setRoadName(road.getName());
                taskOver.setRoadId(key);
                overChildren.add(taskOver);
            }
        }
        //逾期
        NewCountWorkOrderVo overVo = new NewCountWorkOrderVo();
        overVo.setName("已逾期");
        overVo.setNumber(String.valueOf(overList.size()));
        overVo.setChildren(overChildren);
        returnList.add(overVo);

        return returnList;
    }

    @Override
    public CountWorkOrder countWorkOrder(QueryFilter<WorkStatistic> queryFilter) {
        QueryWrapper<WorkOrderInformation> orderQueryWrapper = new QueryWrapper<>();
        Map<String, Object> params = queryFilter.getParams();
        if (ObjectUtils.isEmpty(params.get("accDateYear")) && ObjectUtils.isEmpty(params.get("accDateMonth"))) {
            String mouth = new SimpleDateFormat("yyyy-MM").format(new Date());
            params.put("accDateMonth", mouth);
        }
        if (ObjectUtils.isNotEmpty(params.get("roadSegmentId"))){
            List<String> ids = Arrays.asList(params.get("roadSegmentId").toString().split(","));
            params.put("ids",ids);
            orderQueryWrapper.in("ROAD_SEGMENT_ID_", ids);
        }
        List<Map<String, Object>> mapList = this.baseMapper.countWorkOrder(params);

        //养护站下单[业主]
        long userTask1 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask1")).count();

        //养护单位派单[施工]
        long userTask2 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask2")).count();
        //养护单位填报[施工]
        long userTask3 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask3")).count();
        //收方计量[业主]
        long userTask4 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask4")).count();
        //养护站审核[业主]
        long userTask5 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask5")).count();
        long userTask6 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask6")).count();
        //管理中心确认[业主]
        long userTask7 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask7")).count();
        //完成工单
        long endEvent1 = mapList.stream().filter(s -> s.get("taskKey").equals("EndEvent1")).count();

        //逾期工单  DEMAND_FINISH_TIME_  END_TIME_

        orderQueryWrapper.eq("OVERDUE_", "1");
        orderQueryWrapper.eq("IS_DELE_", "0");
        if (ObjectUtils.isNotEmpty(params.get("accDateMonth"))){
            Object month = params.get("accDateMonth");
            orderQueryWrapper.apply("date_format(ISSUE_DATE_,'%Y-%m') = {0}",month);
        }

        List<WorkOrderInformation> overList = workOrderInformationDao.selectList(orderQueryWrapper);

        //未完成工单逾期
        long overdueWorkOrderCountUnFinish = overList.size();

        CountWorkOrder countWorkOrder = new CountWorkOrder();
        countWorkOrder.setBacklogWorkOrder(String.valueOf(userTask1 + userTask7));
        countWorkOrder.setConstructionWorkOrder(String.valueOf(userTask2 + userTask3));
        countWorkOrder.setDebitWorkOrder(String.valueOf(userTask4));
        countWorkOrder.setAuditWorkOrder(String.valueOf(userTask5+userTask6));
        countWorkOrder.setFinishWorkOrder(String.valueOf(endEvent1));
        countWorkOrder.setOverdueWorkOrder(String.valueOf( overdueWorkOrderCountUnFinish));
        return countWorkOrder;
    }


    @Override
    public List<CountWorkOrder> countWorkOrders(QueryFilter<WorkStatistic> queryFilter) {
        List<CountWorkOrder> list = new ArrayList<CountWorkOrder>();
        Map<String, Object> params = queryFilter.getParams();
        Object roadSegmentId = params.get("roadSegmentId");
        if (ObjectUtils.isEmpty(params.get("accDateYear")) && ObjectUtils.isEmpty(params.get("accDateMonth"))) {
            String mouth = new SimpleDateFormat("yyyy-MM").format(new Date());
            params.put("accDateMonth", mouth);
        }
        if (ObjectUtils.isEmpty(roadSegmentId)) {
            QueryWrapper<Road> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("IS_DELE_", "0");
            List<Road> roadList = roadDao.selectList(queryWrapper);
            for (Road road : roadList) {
                String id = road.getId();
                params.put("roadSegmentId", id);
//                List<String> ids = new ArrayList<>();
//                ids.add(id);
//                params.put("ids",ids);
                List<Map<String, Object>> mapList = this.baseMapper.countWorkOrder4Open(params);
                //养护站下单[业主]
                long userTask1 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask1")).count();
                //养护单位派单[施工]
                long userTask2 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask2")).count();
                //养护单位填报[施工]
                long userTask3 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask3")).count();
                //养护单位验收[施工]
                long userTask4 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask4")).count();
                //养护站审核[业主]
                long userTask5 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask5")).count();
                long userTask6 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask6")).count();
                //管理中心确认[业主]
                long userTask7 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask7")).count();
                //完成工单
                long endEvent1 = mapList.stream().filter(s -> s.get("taskKey").equals("EndEvent1")).count();
                //逾期工单  DEMAND_FINISH_TIME_  END_TIME_
                QueryWrapper<WorkOrderInformation> orderQueryWrapper = new QueryWrapper<>();
                orderQueryWrapper.eq("OVERDUE_", "1");
                orderQueryWrapper.eq("IS_DELE_", "0");
                orderQueryWrapper.eq("ROAD_SEGMENT_ID_", id);
                if (ObjectUtils.isNotEmpty(params.get("accDateMonth"))){
                    Object month = params.get("accDateMonth");
                    orderQueryWrapper.apply("date_format(ISSUE_DATE_,'%Y-%m') = {0}",month);
                }

                List<WorkOrderInformation> overList = workOrderInformationDao.selectList(orderQueryWrapper);

                //未完成工单逾期
                long overdueWorkOrderCountUnFinish = overList.size();


                CountWorkOrder countWorkOrder = new CountWorkOrder();
                countWorkOrder.setRoadSegmentId(id);
                countWorkOrder.setRoadSegmentName(road.getName());
                countWorkOrder.setBacklogWorkOrder(String.valueOf(userTask1 + userTask7));
                countWorkOrder.setConstructionWorkOrder(String.valueOf(userTask2 + userTask3));
                countWorkOrder.setDebitWorkOrder(String.valueOf(userTask4));
                countWorkOrder.setAuditWorkOrder(String.valueOf(userTask5 + userTask6));
                countWorkOrder.setFinishWorkOrder(String.valueOf(endEvent1));
                countWorkOrder.setOverdueWorkOrder(String.valueOf(overdueWorkOrderCountUnFinish));
                list.add(countWorkOrder);
            }
        } else {
            List<String> ids = Arrays.asList(params.get("roadSegmentId").toString().split(","));
            params.put("ids",ids);
            List<Map<String, Object>> mapList = this.baseMapper.countWorkOrder4Open(params);
            //养护站下单[业主]
            long userTask1 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask1")).count();
            //养护单位派单[施工]
            long userTask2 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask2")).count();
            //养护单位填报[施工]
            long userTask3 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask3")).count();
            //收方计量[业主]
            long userTask4 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask4")).count();
            //养护站审核[业主]
            long userTask5 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask5")).count();
            long userTask6 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask6")).count();
            //管理中心确认[业主]
            long userTask7 = mapList.stream().filter(s -> s.get("taskKey").equals("UserTask7")).count();
            //完成工单
            long endEvent1 = mapList.stream().filter(s -> s.get("taskKey").equals("EndEvent1")).count();
            //逾期工单  DEMAND_FINISH_TIME_  END_TIME_
            QueryWrapper<WorkOrderInformation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("OVERDUE_", "1");
            queryWrapper.eq("IS_DELE_", "0");
            queryWrapper.in("ROAD_SEGMENT_ID_",ids);
            List<WorkOrderInformation> overList = workOrderInformationDao.selectList(queryWrapper);

            //未完成工单逾期
            long overdueWorkOrderCountUnFinish = overList.size();


            CountWorkOrder countWorkOrder = new CountWorkOrder();
            countWorkOrder.setRoadSegmentId(roadSegmentId.toString());
            countWorkOrder.setRoadSegmentName(roadDao.selectById(roadSegmentId.toString()).getName());
            countWorkOrder.setBacklogWorkOrder(String.valueOf(userTask1 + userTask7));
            countWorkOrder.setConstructionWorkOrder(String.valueOf(userTask2 + userTask3));
            countWorkOrder.setDebitWorkOrder(String.valueOf(userTask4));
            countWorkOrder.setAuditWorkOrder(String.valueOf(userTask5 + userTask6));
            countWorkOrder.setFinishWorkOrder(String.valueOf(endEvent1));
            countWorkOrder.setOverdueWorkOrder(String.valueOf(overdueWorkOrderCountUnFinish));
            list.add(countWorkOrder);
        }
        return list;
    }
}
