package com.tofly.xrtygis.custom.service.zsdata.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.core.util.DateUtil;
import com.tofly.common.core.util.StringUtil;
import com.tofly.xrtygis.custom.entity.dataquery.*;
import com.tofly.xrtygis.custom.service.zsdata.DataContrastService;
import com.tofly.xrtygis.custom.service.zsdata.DataQueryService;
import com.tofly.xrtygis.custom.util.Date7Utils;
import com.tofly.xrtygis.entity.Costbgwater;
import com.tofly.xrtygis.mapper.CostbgpriceMapper;
import com.tofly.xrtygis.mapper.CostbgwaterMapper;
import com.tofly.xrtygis.mapper.CostrlwaterMapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author FlashWJL
 * @date 2021/4/27 15:44
 */
@Service
@AllArgsConstructor
public class DataContrastServiceImpl implements DataContrastService {

    private final CostbgpriceMapper baseMapper;
    private final CostbgwaterMapper costbgwaterMapper;
    private final CostrlwaterMapper costrlwaterMapper;
    private final DataQueryService queryService;

    @Override
    public List<Map> getProduceCostPrice(HttpServletResponse response, Page page, WaterPlanSearch search) {
        //判断是根据什么进行查询的；如：年度查询、年份查询、月度查询
        List<Map> resultMap = new ArrayList<>();
        search.setTemplateFlag("");
        //调用单价查询业务
        List<Map> planPage = queryService.getTargetPricePlan(response, search);
        List<Map> realityPage = queryService.getTargetPriceReality(response, search);

        List<QueryPrice> plan = JSONObject.parseArray(JSONObject.toJSONString(planPage), QueryPrice.class);
        List<QueryPrice> reality = JSONObject.parseArray(JSONObject.toJSONString(realityPage), QueryPrice.class);

        //保存年度和对应实体类
        Map<String, QueryPrice> planMap = plan.stream().collect(Collectors.toMap(QueryPrice::getCreateTime, m -> m));
        reality.forEach(k -> {
            //将相同时间的存放在map里
            Map map = new HashMap();
            String time = k.getCreateTime();
            map.put("reality", k);
            QueryPrice queryPrice = planMap.get(time);
            //如果查询来是null；则没有当前实际填报单价的月份中没有计划单价；则需要使用前一月的；以此类推直到找到为止
            if (StringUtil.isNull(queryPrice)) {
                //默认某月1号
                Date date = DateUtil.formatDate(time, "yyyy-MM");
                //找的次数 一年12次，需要找到之前
                for (int i = 0; i < 12; i++) {
                    Date nextDate = Date7Utils.addNextPeriod(-i, date);
                    String nextDateStr = DateUtil.parseDateToStr("yyyy-MM", nextDate);
                    //如果循环完都没有找到，那就没有填报
                    queryPrice = planMap.get(nextDateStr);
                    if (StringUtil.isNotNull(queryPrice)) {
                        break;
                    }
                }
            }
            QueryPrice query = new QueryPrice();
            if (StringUtil.isNull(queryPrice)) {
                query.setYear(k.getYear());
            } else {
                query = queryPrice;
            }
            map.put("plan", query);
            resultMap.add(map);
        });


        //如果传的是 1，则代表导出Excel数据
//        if ("1".equals(search.getTemplateFlag())) {
//            // 根据templateServiceType,templateFlag获取对应模板数据
//            ExcelExportFileTypeEnum excelExportFileTypeEnum = ExcelExportFileTypeEnum.getExcelExportFileTypeEnum("waterPlanServiceImpl", search.getTemplateFlag());
//            if (null == excelExportFileTypeEnum) {
//                return null;
//            }
//            //将查询的结果转json字符串的格式，因为导出的时候只能传一个字符串
//            String resultListToString = JSONArray.toJSONString(result.getRecords());
//            // 从模型类型枚举根据templateServiceType获取策略对应模板数据
//            List<Map<String, Object>> dataList = excelStrategyContext.getExportData("waterPlanServiceImpl", search.getTemplateFlag(), resultListToString);
//            ExcelUtil.export(dataList.get(0), excelExportFileTypeEnum, Constant.FILE_PATH_TEST_EXPORT_EXCEL, response);
//        }
        return resultMap;
    }


    @Override
    public Map<String,List<Map>> getProduceCostPrice(WaterPlanSearch search) {
        String year = search.getStartYear();

        Map<String,List<Map>> result = new HashMap();

        result.put("real",baseMapper.getPriceRealDataYear(year));
        result.put("plan",baseMapper.getPricePlanDataYear(year));

        return result;
    }

    @Override
    public List<Map> getProduceDataQuery(HttpServletResponse response, Page page, WaterPlanSearch search) {
        //判断是根据什么进行查询的；如：年度查询、年份查询、月度查询
        String startYear = search.getStartYear();
        String year = search.getYear();
        List<Map> resultMap = new ArrayList<>();
        String month = search.getMonth();
        String yearDay = search.getYearDay();
        List<WaterReality> reality;
        List<Costbgwater> plan;

        //首先按年度查询；以年为单位展示数据
        if (StringUtil.isNotEmpty(startYear)) {
            plan = costbgwaterMapper.getProduceDataYearPlan(startYear);
            reality = costrlwaterMapper.getProduceDataYearReality(startYear);
        }
        //按年份查询；以该年中每月数据展示
        else if (StringUtil.isNotEmpty(year)) {
            plan = costbgwaterMapper.egtProduceDataMonthByYaerPlan(year);
            reality = costrlwaterMapper.getProduceDataMonthByYearReality(year);
        }
        //月份查询；如2016-01 ---2021-01，则是2016-01，2017-01，2018-01，2019-01，2020-01的数据
        else if (StringUtil.isNotEmpty(month) && StringUtil.isNotEmpty(yearDay)) {
            plan = costbgwaterMapper.getProduceDataMonthPlan(month, yearDay);
            reality = costrlwaterMapper.getProduceDataMonthReality(month, yearDay);

        } else {
            //默认返回所有的
            return null;
        }
        //保存年度和对应实体类
        Map<String, Costbgwater> planMap = plan.stream().collect(Collectors.toMap(Costbgwater::getMonth, m -> m));
        reality.forEach(k -> {
            //将相同时间的存放在map里
            Map map = new HashMap();
            String time = k.getUpDate();
            map.put("reality", k);
            Costbgwater costbgwater = planMap.get(time);
            Costbgwater cost = new Costbgwater();
            if (StringUtil.isNull(costbgwater)) {
                cost.setMonth(k.getUpDate());
            } else {
                cost = costbgwater;
            }
            map.put("plan", cost);
            resultMap.add(map);
        });


//        //如果传的是 1，则代表导出Excel数据
//        if ("1".equals(search.getTemplateFlag())) {
//            // 根据templateServiceType,templateFlag获取对应模板数据
//            ExcelExportFileTypeEnum excelExportFileTypeEnum = ExcelExportFileTypeEnum.getExcelExportFileTypeEnum("produceComparServiceImpl", search.getTemplateFlag());
//            if (null == excelExportFileTypeEnum) {
//                return null;
//            }
//            //将查询的结果转json字符串的格式，因为导出的时候只能传一个字符串
//            String resultListToString = JSONArray.toJSONString(resultMap);
//            // 从模型类型枚举根据templateServiceType获取策略对应模板数据
//            List<Map<String, Object>> dataList = excelStrategyContext.getExportData("produceComparServiceImpl", search.getTemplateFlag(), resultListToString);
//            ExcelUtil.export(dataList.get(0), excelExportFileTypeEnum, Constant.FILE_PATH_TEST_EXPORT_EXCEL, response);
//        }
        return resultMap;
    }

    @Override
    public List<Map> getCostData(HttpServletResponse response, Page page, WaterPlanSearch search) {
        //判断是根据什么进行查询的；如：年度查询、年份查询、月度查询
        String startYear = search.getStartYear();
        String year = search.getYear();
        String month = search.getMonth();
        String yearDay = search.getYearDay();
        List<Map> resultMap = new ArrayList<>();
        List<FixedReality> reality;
        List<FixedPlan> plan;
        //首先按年度查询；以年为单位展示数据
        if (StringUtil.isNotEmpty(startYear)) {
            //修改查询结果，由于前端不不好取数据
            //计划值
            plan = baseMapper.getCostDataYearPlan(startYear);
            //实际值
            reality = baseMapper.getCostDataYearReality(startYear);

        }
        //按年份查询；以该年中每月数据展示
        else if (StringUtil.isNotEmpty(year)) {
            plan = baseMapper.getCostDataMonthByYearPlan(year);
            reality = baseMapper.getCostDataMonthByYearReality(year);
        }
        //月份查询；如2016-01 ---2021-01，则是2016-01，2017-01，2018-01，2019-01，2020-01的数据
        else if (StringUtil.isNotEmpty(month) && StringUtil.isNotEmpty(yearDay)) {
            plan = baseMapper.getCostDataMonthPlan(month, yearDay);
            reality = baseMapper.getCostDataMonthReality(month, yearDay);
        } else {
            //默认返回所有的
            return null;
        }
        //保存年度和对应实体类
        Map<String, FixedPlan> planMap = plan.stream().collect(Collectors.toMap(FixedPlan::getUpDate, m -> m));
        reality.forEach(k -> {
            //将相同时间的存放在map里
            Map map = new HashMap();
            String time = k.getUpDate();
            map.put("reality", k);
            FixedPlan fixedPlan = planMap.get(time);
            FixedPlan fixed = new FixedPlan();
            if (StringUtil.isNull(fixedPlan)) {
                fixed.setUpDate(k.getUpDate());
            } else {
                fixed = fixedPlan;
            }
            map.put("plan", fixed);
            resultMap.add(map);
        });

        //如果传的是 1，则代表导出Excel数据
//        if ("1".equals(search.getTemplateFlag())) {
//            // 根据templateServiceType,templateFlag获取对应模板数据
//            ExcelExportFileTypeEnum excelExportFileTypeEnum = ExcelExportFileTypeEnum.getExcelExportFileTypeEnum("waterPlanServiceImpl", search.getTemplateFlag());
//            if (null == excelExportFileTypeEnum) {
//                return null;
//            }
//            //将查询的结果转json字符串的格式，因为导出的时候只能传一个字符串
//            String resultListToString = JSONArray.toJSONString(result.getRecords());
//            // 从模型类型枚举根据templateServiceType获取策略对应模板数据
//            List<Map<String, Object>> dataList = excelStrategyContext.getExportData("waterPlanServiceImpl", search.getTemplateFlag(), resultListToString);
//            ExcelUtil.export(dataList.get(0), excelExportFileTypeEnum, Constant.FILE_PATH_TEST_EXPORT_EXCEL, response);
//        }
        return resultMap;
    }
}
