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

import com.tofly.common.core.util.StringUtil;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.xrtygis.custom.entity.dataquery.WaterPlanSearch;
import com.tofly.xrtygis.custom.service.zsdata.DataTrendService;
import com.tofly.xrtygis.mapper.CostrlfixedMapper;
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/29 14:59
 */
@Service
@AllArgsConstructor
public class DataTrendServiceImpl implements DataTrendService {
    private final CostrlwaterMapper waterMapper;
    private final CostrlfixedMapper costrlfixedMapper;

    /**
     * 水量查询
     *
     * @param response
     * @param search
     * @return
     */
    @Override
    public Map getWaterData(HttpServletResponse response, WaterPlanSearch search) {

        String startYear = search.getStartYear();
        String endYear = search.getEndYear();
        String type = search.getType();
        if (StringUtil.isEmpty(type)) {
            throw new ToflyDeniedException("类别必传");
        }
        List<String> ids = Arrays.asList(type.split(","));
        List<Map> cnameList = costrlfixedMapper.getCodeByIds(ids);
        StringBuilder c = new StringBuilder("");
        StringBuilder sumType = new StringBuilder("");
        cnameList.forEach(k -> {
            //查询具体字段SQL
            c.append("nvl(" + k.get("ccode") + ",0)" + k.get("ccode") + ",");
            //具体字段求和SQL
            sumType.append("nvl(SUM(" + k.get("ccode") + "),0)" + k.get("ccode") + ",");
        });
        //去除最后一个逗号
        c.deleteCharAt(c.length() - 1);
        sumType.deleteCharAt(sumType.length() - 1);
        //type赋值
        type = c.toString();
        //根据月份展示
        List<Map> monthData = waterMapper.getWaterDataMonth(type, startYear, endYear);
        //根据季度展示
        List<Map> quarterData = waterMapper.getWaterDataQuarter(type, startYear, endYear, sumType.toString());
        //根据年份展示
        List<Map> yearData = waterMapper.getWaterDataYear(type, startYear, endYear, sumType.toString());
        //替换月度、季度、年度查询中的字段为中文公共方法
        Map<String, Map> reslutMap = commonCnameExchange(cnameList, monthData, quarterData, yearData);
//        //调用数据转换方法
//        Map<String, Map> reslutMap = transfer1(monthData, quarterData, yearData, startYear, endYear);

        return reslutMap;
    }

    /**
     * 用电量查询
     *
     * @param response
     * @param search
     * @return
     */
    @Override
    public Map getElectricityData(HttpServletResponse response, WaterPlanSearch search) {
        String startYear = search.getStartYear();
        String endYear = search.getEndYear();
        String type = search.getType();
        //动力电耗
        StringBuilder dldh = new StringBuilder();
        StringBuilder sumDldh = new StringBuilder();
        //动力电量
        StringBuilder dldl = new StringBuilder();
        StringBuilder sumDldl = new StringBuilder();
        if (StringUtil.isEmpty(type)) {
            throw new ToflyDeniedException("类别必传");
        }
        List<String> ids = Arrays.asList(type.split(","));
        List<Map> cnameList = costrlfixedMapper.getCodeByIds(ids);
        cnameList.forEach(k -> {
            //做个判断，由于有用电量类别，动力电耗在单耗表里面，动力电量又在用水量表里面，所以根据字段判断具体用哪个表
            if ("DH_ONE".equals(k.get("ccode").toString()) || "DH_TWO".equals(k.get("ccode").toString()) || "DH_TOTAL".equals(k.get("ccode").toString())){
                //查询具体字段SQL
                dldh.append("nvl(" + k.get("ccode") + ",0)" + k.get("ccode") + ",");
                //具体字段求和SQL
                sumDldh.append("nvl(SUM(" + k.get("ccode") + "),0)" + k.get("ccode") + ",");
            }else {
                //查询具体字段SQL
                dldl.append("nvl(" + k.get("ccode") + ",0)" + k.get("ccode") + ",");
                //具体字段求和SQL
                sumDldl.append("nvl(SUM(" + k.get("ccode") + "),0)" + k.get("ccode") + ",");
            }
        });
        //根据月份展示
        List<Map> monthData = new ArrayList<>();
        //根据季度展示
        List<Map> quarterData = new ArrayList<>();
        //根据年份展示
        List<Map> yearData = new ArrayList<>();
        if (StringUtil.isNotEmpty(dldh.toString()) && StringUtil.isNotEmpty(sumDldh.toString())){
            //去除最后一个逗号
            dldh.deleteCharAt(dldh.length() - 1);
            sumDldh.deleteCharAt(sumDldh.length() - 1);
            String tableName = "TF_YWPN_COSTRLUNIT_W";
            List<Map> dhMonthData = waterMapper.getElectricityDataMonth(dldh.toString(), startYear, endYear, tableName);
            //根据季度展示
            List<Map> dhQuarterData = waterMapper.getElectricityDataQuarter(dldh.toString(), startYear, endYear, tableName , sumDldh.toString());
            //根据年份展示
            List<Map> dhYearData = waterMapper.getElectricityDataYear(dldh.toString(), startYear, endYear, tableName , sumDldh.toString());
            monthData.addAll(dhMonthData);
            quarterData.addAll(dhQuarterData);
            yearData.addAll(dhYearData);
        }
        if (StringUtil.isNotEmpty(dldl.toString()) && StringUtil.isNotEmpty(sumDldl.toString())){
            //去除最后一个逗号
            dldl.deleteCharAt(dldl.length() - 1);
            sumDldl.deleteCharAt(sumDldl.length() - 1);
            String tableName = "TF_YWPN_COSTRLWATER_W";
            //根据月份展示
            List<Map> dlMonthData = waterMapper.getElectricityDataMonth(dldl.toString(), startYear, endYear, tableName);
            //根据季度展示
            List<Map> dlQuarterData = waterMapper.getElectricityDataQuarter(dldl.toString(), startYear, endYear, tableName , sumDldl.toString());
            //根据年份展示
            List<Map> dlYearData = waterMapper.getElectricityDataYear(dldl.toString(), startYear, endYear, tableName , sumDldl.toString());
            monthData.addAll(dlMonthData);
            quarterData.addAll(dlQuarterData);
            yearData.addAll(dlYearData);
        }
        //替换月度、季度、年度查询中的字段为中文公共方法
        Map<String, Map> reslutMap = commonCnameExchange(cnameList, monthData, quarterData, yearData);
        return reslutMap;
    }

    /**
     * 材料单耗查询
     *
     * @param response
     * @param search
     * @return
     */
    @Override
    public Map getMaterialsData(HttpServletResponse response, WaterPlanSearch search) {
        String startYear = search.getStartYear();
        String endYear = search.getEndYear();
        String type = search.getType();
        if (StringUtil.isEmpty(type)) {
            throw new ToflyDeniedException("类别必传");
        }
        List<String> ids = Arrays.asList(type.split(","));
        List<Map> cnameList = costrlfixedMapper.getCodeByIds(ids);
        StringBuilder c = new StringBuilder("");
        StringBuilder sumType = new StringBuilder("");
        cnameList.forEach(k -> {
            //查询具体字段SQL
            c.append("nvl(" + k.get("ccode") + ",0)" + k.get("ccode") + ",");
            //具体字段求和SQL
            sumType.append("nvl(SUM(" + k.get("ccode") + "),0)" + k.get("ccode") + ",");
        });
        //去除最后一个逗号
        c.deleteCharAt(c.length() - 1);
        sumType.deleteCharAt(sumType.length() - 1);
        //type赋值
        type = c.toString();
        //根据月份展示
        List<Map> monthData = waterMapper.getMaterialsDataMonth(type, startYear, endYear);
        //根据季度展示
        List<Map> quarterData = waterMapper.getMaterialsDataQuarter(type, startYear, endYear, sumType.toString());
        //根据年份展示
        List<Map> yearData = waterMapper.getMaterialsDataYear(type, startYear, endYear, sumType.toString());
        //替换月度、季度、年度查询中的字段为中文公共方法
        Map<String, Map> reslutMap = commonCnameExchange(cnameList, monthData, quarterData, yearData);
//        Map<String, Map> reslutMap = transfer1(monthData, quarterData, yearData, startYear, endYear);

        return reslutMap;
    }


    /**
     * 单价
     *
     * @param response
     * @param search
     * @return
     */
    @Override
    public Map getPriceData(HttpServletResponse response, WaterPlanSearch search) {
        String startYear = search.getStartYear();
        String endYear = search.getEndYear();
        String type = search.getType();
        if (StringUtil.isEmpty(type)) {
            throw new ToflyDeniedException("类别必传");
        }
        List<String> ids = Arrays.asList(type.split(","));
        List<Map> cnameList = costrlfixedMapper.getCodeByIds(ids);
        StringBuilder c = new StringBuilder("");
        cnameList.forEach(k -> {
            //查询具体字段SQL
            c.append("nvl(" + k.get("ccode") + ",0)" + k.get("ccode") + ",");
        });
        //去除最后一个逗号
        c.deleteCharAt(c.length() - 1);
        //type赋值
        type = c.toString();
        //根据月份展示
        List<Map> monthData = waterMapper.getPriceDataMonth(type, startYear, endYear);
        //根据季度展示
        List<Map> quarterData = waterMapper.getPriceDataQuarter(type, startYear, endYear);
        //根据年份展示
        List<Map> yearData = waterMapper.getPriceDataYear(type, startYear, endYear);
        //替换月度、季度、年度查询中的字段为中文公共方法
        Map<String, Map> reslutMap = commonCnameExchange(cnameList, monthData, quarterData, yearData);
//        Map<String, Map> reslutMap = transfer1(monthData, quarterData, yearData, startYear, endYear);

        return reslutMap;
    }

    /**
     * 数据转换处理；返回给前端才写的  我淦  浪费时间
     *
     * @param monthData   月份数据
     * @param quarterData 季度数据
     * @param yearData    年度数据
     * @param startYear   开始年份
     * @param endYear     结束年份
     * @return
     */
    @Override
    public Map transfer(List<Map> monthData, List<Map> quarterData, List<Map> yearData, String startYear, String endYear) {
        //转月份数据
        int start = Integer.valueOf(startYear);
        int end = Integer.valueOf(endYear);
        //应查询出来的个数
        int size = end - start + 1;
        Map<String, Map> reslutMap = new HashMap();
        Map<String, Map> monthMap = new HashMap();
        Map<String, Map> quarterMap = new HashMap();
        Map yearMap = new HashMap();
        //月份转换
        for (int i = 0; i < size; i++) {
            String year = (start + i) + "";
            //过滤出某一年的数据
            List<Map> dataMapMonth = monthData.stream().filter(m -> year.equals(m.get("year"))).collect(Collectors.toList());
            Map map = new HashMap();
            //取这一年中的月份数据
            dataMapMonth.forEach(k -> {
//                k.get("month");//月份作为键
//                k.get("reslutdata");//结果作为值
                map.put(k.get("month"), k.get("reslutdata"));
                monthMap.put(year, map);
            });
        }
        //季度转换
        for (int i = 0; i < size; i++) {
            String year = (start + i) + "";
            //过滤出某一年的数据
            List<Map> dataMapMonth = quarterData.stream().filter(m -> year.equals(m.get("year"))).collect(Collectors.toList());
            Map map = new HashMap();
            //取这一年中的月份数据
            dataMapMonth.forEach(k -> {
//                k.get("month");//月份作为键
//                k.get("reslutdata");//结果作为值
                map.put(k.get("month"), k.get("reslutdata"));
                quarterMap.put(year, map);
            });
        }
        //年度转换
        yearData.forEach(k -> {
            yearMap.put(k.get("year"), k.get("reslutdata"));
        });

        reslutMap.put("month", monthMap);
        reslutMap.put("quarterMap", quarterMap);
        reslutMap.put("yearMap", yearMap);
        return reslutMap;
    }

    /**
     * 替换月度、季度、年度查询中的字段为中文公共方法
     * 转换数据格式
     * @param cnameList
     * @param monthData
     * @param quarterData
     * @param yearData
     */
    private Map<String, Map> commonCnameExchange(List<Map> cnameList, List<Map> monthData, List<Map> quarterData, List<Map> yearData) {
        //结果集
        Map<String, Map> reslutMap = new HashMap();
        //月份数据
        Map<String, Map> monthMap = new HashMap();
        //季度数据
        Map<String, Map> quarterMap = new HashMap();
        //年份数据
        Map<String , Map> yearMap = new HashMap();
        //这里需要替换成中文；必须用双层for循环，暂时不知道有没有其他办法可以优化解决
        for (Map value : cnameList) {
            for (Map map : monthData) {
                //第一层 年份
                Map<String , Map> yearOneMap = null;
                //第二次 月份和具体值
                Map<String , String> monthTwoMap = null;
                if (map.containsKey(value.get("ccontert"))) {
                    String year = map.get("year").toString();
                    String month = map.get("month").toString();
                    //对应类别的结果值
                    String reslut = map.get(value.get("ccontert")).toString();
                    //中文类别名
                    String key = String.valueOf(value.get("cname"));
                    //判断有没有类别
                    if(monthMap.containsKey(key)){
                        //有类别就拿出来
                        yearOneMap = monthMap.get(key);
                    }else {
                        yearOneMap = new HashMap<>();
                        //如果没有，则放进来
                        monthMap.put(key,yearOneMap);
                    }
                    //判断有没有相同的年份
                    if (yearOneMap.containsKey(year)){
                        //有相同年份就拿出来
                        monthTwoMap = yearOneMap.get(year);
                    }else {
                        monthTwoMap = new HashMap<>();
                        yearOneMap.put(year,monthTwoMap);
                    }
                    //统一存放数据；月和对应的值
                    monthTwoMap.put(month,reslut);
                }
            }
            //季度转换
            for (Map map : quarterData) {
                //第一层 年份
                Map<String , Map> yearOneMap = null;
                //第二次 季度和具体值
                Map<String , String> quarterTwoMap = null;
                if (map.containsKey(value.get("ccontert"))) {
                    String year = map.get("year").toString();
                    String quarter = map.get("month").toString();
                    //对应类别的结果值
                    String reslut = map.get(value.get("ccontert")).toString();
                    //中文类别名
                    String key = String.valueOf(value.get("cname"));
                    //判断有没有类别
                    if(quarterMap.containsKey(key)){
                        //有类别就拿出来
                        yearOneMap = quarterMap.get(key);
                    }else {
                        yearOneMap = new HashMap<>();
                        //如果没有，则放进来
                        quarterMap.put(key,yearOneMap);
                    }
                    //判断有没有相同的年份
                    if (yearOneMap.containsKey(year)){
                        //有相同年份就拿出来
                        quarterTwoMap = yearOneMap.get(year);
                    }else {
                        quarterTwoMap = new HashMap<>();
                        yearOneMap.put(year,quarterTwoMap);
                    }
                    //统一存放数据；月和对应的值
                    quarterTwoMap.put(quarter,reslut);
                }
            }
            //年份转换
            //季度转换
            for (Map map : yearData) {
                Map<String , String> yearOneMap = null;
                if (map.containsKey(value.get("ccontert"))) {
                    String year = map.get("year").toString();
                    //对应类别的结果值
                    String reslut = map.get(value.get("ccontert")).toString();
                    //中文类别名
                    String key = String.valueOf(value.get("cname"));
                    //判断有没有类别
                    if(yearMap.containsKey(key)){
                        yearOneMap = yearMap.get(key);
                    }else {
                        yearOneMap = new HashMap<>();
                        yearMap.put(key , yearOneMap);
                    }
                    yearOneMap.put(year , reslut);
                }
            }
        }
        reslutMap.put("month", monthMap);
        reslutMap.put("quarterMap", quarterMap);
        reslutMap.put("yearMap", yearMap);
        return reslutMap;
    }
}
