package com.nantian.cloud.dbcapp.service.impl;



import com.nantian.cloud.dbcapp.dto.ElectricityDataDto;

import com.nantian.cloud.dbcapp.mapper.record.ElectricityMapper;

import com.nantian.cloud.dbcapp.mapper.record.EnergyMapper;
import com.nantian.cloud.dbcapp.service.ElectricityService;

import com.nantian.cloud.dbcapp.service.EnergyService;
import com.nantian.cloud.dbcapp.service.EnterpriseService;
import com.nantian.cloud.dbcapp.tool.AreaCode;
import com.nantian.cloud.dbcapp.tool.IndustryCode;
import com.nantian.cloud.dbcapp.vo.CoalVo;
import com.nantian.cloud.dbcapp.vo.ElectricityDataVo;
import com.nantian.cloud.dbcapp.vo.ElectricityIndex;
import com.nantian.cloud.dbcapp.vo.KeyValueVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;


/**
 * <p>
 * 电力 服务实现类
 * </p>
 *
 * @author zfw
 * @since 2020-08-05
 */
@Service("electricity")
public class ElectricityServiceImpl implements ElectricityService {

    @Autowired
    private ElectricityMapper electricityMapper;
    @Autowired
    private AreaCode areaCode;
    @Autowired
    private IndustryCode industryCode;
    @Autowired
    private EnergyService energyService;
    @Autowired
    private EnergyMapper energyMapper;
    @Autowired
    private EnterpriseService enterpriseService;


    /**
    * @Description: 用能单位接入数量
    * @Param: [area, industry, time]
    * @return: java.lang.Integer
    * @Author: zfw
    * @Date: 2020/12/22
    * @Date: 20:28
    */
    @Override
    public Integer  getTotal(String area ,String industry,String time) {
        if("".equals(time)||time==null){
            time = "2020-01-01&2020-12-31";
        }
        //截取时间
        String startTime=time.split("&")[0];
        String endTime=time.split("&")[1];
        startTime.substring(0,7);
        endTime.substring(0,7);
        HashMap<String, String> areaAndIndustryCode = energyService.getAreaAndIndustryCode(area, industry);
        area = (area.trim().equals("53") || area.trim().equals("云南")) ? "53" : areaAndIndustryCode.get("地区");
        industry = industry.trim().equals("全部") ? null : areaAndIndustryCode.get("行业");

        return electricityMapper.getTotal(area,industry);
    }

    /**
    * @Description: 电力企业数量
    * @Param: [area, industry, time]
    * @return: java.lang.Integer
    * @Author: zfw
    * @Date: 2020/12/22
    * @Date: 20:29
    */
    @Override
    public Integer  getInfo(String area ,String industry,String time) {
        return electricityMapper.getInfo(area,industry,time);
    }

    /**
     *  电力数据
     * @param area
     * @param industry
     * @param time
     * @return
     */
    @Override
    public ElectricityIndex getInfoData(String area, String industry, String time) {
        HashMap<String, String> areaAndIndustryCode =getAreaAndIndustryCode(area, industry);
        String industryName = areaAndIndustryCode.get("行业");
        String areaName = areaAndIndustryCode.get("地区");
        Calendar calendar = Calendar.getInstance();
        String nowYear=String.valueOf(calendar.get(Calendar.YEAR));
        if(time==null||"".equals(time)){
            time = nowYear+"-01-01-"+nowYear+"-12-31";
        }
        String preYear = time.substring(0,4);
        String endYear = time.substring(11,15);
        String preTime = time.substring(0,7) ;
        String endTime = time.substring(11,18);
        List<ElectricityDataVo> valuesList2019 = null ;
        List<ElectricityDataVo> valuesList2020 = null;
        //查询公司list
        Integer num = 0;
        if(Integer.parseInt(endYear)<=2019){
            valuesList2019 =  electricityMapper.selectElectricityData2019(areaName+"%",industryName,preTime,endTime);
            num = electricityMapper.countCmpNum2019(areaName+"%",industryName);
        }else if(Integer.parseInt(preYear)<=2019&&Integer.parseInt(endYear)>=2020){
             valuesList2019 =  electricityMapper.selectElectricityData2019(areaName+"%",industryName,preTime,"2019-12");
             valuesList2020 =  electricityMapper.selectElectricityData2020(areaName+"%",industryName,"2020-01",endTime);
            Integer num1 = electricityMapper.countCmpNum2019(areaName+"%",industryName);
            Integer num2 =  electricityMapper.countCmpNum2020(areaName+"%",industryName);
            num = Math.max(num1,num2);
        }else {
            valuesList2020 =  electricityMapper.selectElectricityData2020(areaName+"%",industryName,preTime,endTime);
            num = electricityMapper.countCmpNum2020(areaName+"%",industryName);
        }
        // 分月分析数据
        LinkedList<ElectricityDataVo> valueLists = new LinkedList<>();
        if(valuesList2019!=null){
            valueLists.addAll(valuesList2019);
        }if(valuesList2020!=null){
            valueLists.addAll(valuesList2020);
        }
        return GroupByMonth(preYear,valueLists,endYear,time,num);
    }

    @Override
    public ElectricityIndex getEnterpriseInfoData(String enterpriseCode, String time) throws ParseException {
        if(time==null||time.equals("")){
            //time = "2021-01-01-2021-12-31";
            Calendar cal = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
            String year = sdf.format(cal.getTime());
            time = year + "-01-01-" + year + "-12-31";
        }
        if(time.length()!=21){
            String[] split = time.split("&");
            String newTime = split[0]+"-01&"+split[1]+"-31";
            time = newTime ;
        }
        String preYear = time.substring(0,4);
        String endYear = time.substring(11,15);
        //String preTime = time.substring(0,7) ;
        //String endTime = time.substring(11,18);
        HashMap<String, String> needTime = enterpriseService.getNeedTime(time);
        String startTime = needTime.get("开始时间");
        String endTime = needTime.get("结束时间");
        Map<String, String> jzTime = enterpriseService.timeStr(enterpriseCode);
        String timeStr = jzTime.get("截止日期");
        String timeStr1 = jzTime.get("下一阶段的开始时间");
        List<ElectricityDataVo> valuesList2019 = null;
        List<ElectricityDataVo> valuesList2020 = null;
        /*
        * 查询数据分为 电网数据和企业自己上传数据 做对比
        * */
        //查询企业上传 单位为千瓦时

        //企业电力数据查询，优先级为：10>11>20>21
        KeyValueVO eleDataCode = electricityMapper.getEleDataCode(enterpriseCode); //获取在线电力数据编码  11>20>21>10
        if(endTime.compareTo(timeStr) <= 0){ //历史数据
            valuesList2019 =  electricityMapper.selectEnterpriseData2019(enterpriseCode,startTime,endTime);
        }else if(startTime.compareTo(timeStr1) >= 0){ //新平台数据
            //valuesList2020 =  electricityMapper.selectCollectByMonthEnt(enterpriseCode,preTime,endTime);
            //valuesList2020 =  electricityMapper.getMaterialElectricEnt(enterpriseCode,startTime,endTime);
            valuesList2020 = electricityMapper.selectCollectEleByMonth(enterpriseCode,eleDataCode.getKey1(),startTime,endTime);
        }else {
            valuesList2019 =  electricityMapper.selectEnterpriseData2019(enterpriseCode,startTime,timeStr);
            valuesList2020 = electricityMapper.selectCollectEleByMonth(enterpriseCode,eleDataCode.getKey1(),startTime,endTime);
        }

        //在线采集电力数据外供量
        List<ElectricityDataVo> valuesListout =  electricityMapper.selectCollectEleByMonth(enterpriseCode,"0000000001330060,0000000002330060",startTime,endTime);

        //在线采集电力数据消耗量
        LinkedList<ElectricityDataVo> valueLists = new LinkedList<>();
        if(valuesList2019!=null){
            valueLists.addAll(valuesList2019);
        }if(valuesList2020!=null){
            valueLists.addAll(valuesList2020);
        }

        //查询电网公司电力数据
        LinkedList<ElectricityDataVo> list = new LinkedList<>();
        list.addAll(electricityMapper.selectEnterpriseData2020(enterpriseCode,startTime,endTime));
        ElectricityIndex electricityIndex = GroupByMonth1(preYear, valueLists, valuesListout, list, endYear, time, 1);
        return electricityIndex;
    }

    @Override
    public List<CoalVo> getInfoDataByArea(String area, String industry, String time) {
        return null ;
    }

    @Override
    public ElectricityIndex getEnterpriseInfoDataDetail(String enterpriseCode, String time) {
        if(time==null||time.length()>7||"".equals(time)){
            time = "2021-01";
        }
        // 首先查询电力数量
        List<ElectricityDataDto> list = electricityMapper.selectByDay(enterpriseCode,time+"%");
        // 查询在线监测数据
        KeyValueVO eleData = electricityMapper.getEleDataCode(enterpriseCode);//获取在线电力数据编码  11>20>21>10
        List<ElectricityDataDto> collect = electricityMapper.selectCollectEleByDay(enterpriseCode,time+"%", eleData.getKey1()); //消耗值
        List<ElectricityDataDto> collectOut = electricityMapper.selectCollectEleByDay(enterpriseCode,time+"%", "0000000001330060,0000000002330060"); //外供值
        // 在线转map
        HashMap<String, Float> map = new HashMap<>();
        HashMap<String, Float> uploadMap = new HashMap<>();
        HashMap<String, Float> outMap = new HashMap<>();
        for (int i = 0; i < collect.size(); i++) {
            uploadMap.put(collect.get(i).getMonth(),collect.get(i).getUploadValue());
        }
        for (int i = 0; i < collectOut.size(); i++) {
            outMap.put(collectOut.get(i).getMonth(),collectOut.get(i).getUploadValue());
        }
        for (int i = 0; i < list.size(); i++) {
            map.put(list.get(i).getMonth(),list.get(i).getValue());
        }
        ElectricityIndex electricityIndex = new ElectricityIndex();
        // 封装
        String month = time.substring(5);
        Integer day = 31 ;
        Integer integer = Integer.valueOf(month);
        if(integer ==4||integer==6||integer==9||integer==11){
            day = 30 ;
        }else if(integer==2){
            day = 28 ;
        }
        ArrayList<ElectricityDataDto> resultList = new ArrayList<>();
        String newTime = null ;
            for (int i = 1; i <= day; i++) {
                if(i<10){
                    newTime = time+"-0"+i ;
                }else {
                    newTime = time+"-"+i ;
                }
                ElectricityDataDto dataDto = new ElectricityDataDto(newTime, map.get(newTime), uploadMap.get(newTime), outMap.get(newTime));
               resultList.add(dataDto);
            }
        electricityIndex.setList(resultList);
        return electricityIndex;
    }

    @Override
    public List<CoalVo> getCollectData(String area, String industry, String time) throws ParseException, ParseException {
        HashMap<String, String> areaAndIndustryCode = getAreaAndIndustryCode(area, industry);
        String industruyCode = areaAndIndustryCode.get("行业");
        String areaCode = areaAndIndustryCode.get("地区");//2020-01-01-2020-12-31
        String pre = time.substring(0, 7);
        String end = time.substring(11, 18);
        List<CoalVo> list  = new ArrayList<>();
        //ArrayList<String> eleEnergyList = new ArrayList<>();
        //eleEnergyList.add("3300");
        //获取采集点信息
        //List<String> dataCodeList = energyService.parseFormulToSimpleAndParamsMap(area, industry, time, pre, end, eleEnergyList);
        List<String> companyList2020 = energyService.getCompanyList2020(areaCode, industruyCode, time, null);
        if(Integer.valueOf(pre.substring(0,4))>=2020){
            //根据公式反推电耗信息
            //list = electricityMapper.selectCollectData(areaCode,industruyCode, pre, end);
            //list = energyService.selectEnergyByFormul(dataCodeList, pre, end, "0.0001");
            // 从中间表 t_energy_consumption 获取能源消耗
            list = energyMapper.selectEnergyByConsumption(companyList2020, pre, end, "电力", "0.0001");
        }else if (Integer.valueOf(end.substring(0,4))<2020){
            list = electricityMapper.selectCollectData2019(areaCode,industruyCode, pre, end);
        }else {
            //List<CoalVo>  list2020 = electricityMapper.selectCollectData2019(areaCode,industruyCode, pre, "2019-12");
            //List<CoalVo>  list2020 = energyService.selectEnergyByFormul(dataCodeList, pre, end, "0.0001");
            List<CoalVo> list2020 = energyMapper.selectEnergyByConsumption(companyList2020,  pre, end, "电力", "0.0001");
            List<CoalVo>  list2019 = electricityMapper.selectCollectData(areaCode,industruyCode, "2020-01", end);
            list.addAll(list2020);
            list.addAll(list2019);
        }
        return list;
    }

    /**
     * 按年或月统计电力数据
     * @param preYear
     * @param valuesList
     * @return
     */
    private ElectricityIndex GroupByMonth(String preYear,List<ElectricityDataVo> valuesList,String endYear,String time,Integer num) {
        // 按年返回,否则按月返回
        ElectricityIndex electricityIndex = new ElectricityIndex();
        LinkedList<ElectricityDataDto> resultList = new LinkedList<>();
            Integer startMonth = Integer.parseInt(time.substring(5, 7));
            Integer endMonth = Integer.parseInt(time.substring(16,18));
            //  对月份进行修正
            int differYear = Integer.parseInt(endYear)- Integer.parseInt(preYear);
            if(differYear!=0){
                endMonth = endMonth + differYear*12 ;
            }
            Integer j = startMonth ;
            Integer k = Integer.parseInt(preYear);
            for (int i = startMonth; i <=endMonth; i++) {
                float sum = 0f;
                String baseTime =null;
                if(j<=12){
                    if(j<10){
                        baseTime = (k)+"-0"+j;
                    }else {
                        baseTime = k+"-"+j;
                    }
                }else if(j>12){
                    k = k + 1 ;
                    j= j-12;
                    if(j<10){
                        baseTime =k+"-0"+j;
                    }else {
                        baseTime = k+"-"+j;
                    }
                }
                j++;
                for (ElectricityDataVo data :valuesList) {
                    if(data.getStatDate().substring(0,7).equals(baseTime)){
                        sum = sum + data.getDataValue();
                    }
                }
                ElectricityDataDto electricityDataDto = new ElectricityDataDto(baseTime, sum/10000,null, null);
                resultList.add(electricityDataDto);
            }
            // 查询企业一级电力数据
            electricityIndex.setList(resultList);
            electricityIndex.setNumber(num);
            return electricityIndex ;
        //}
    }

    /**
     * 按年或月统计电力数据 (返回电力和企业上传的全厂电力list)
     * @param preYear
     * @param valuesList
     * @return
     */
    private ElectricityIndex GroupByMonth1(String preYear, List<ElectricityDataVo> valuesList, List<ElectricityDataVo> valuesListout, List<ElectricityDataVo> electricityList,String endYear,String time,Integer num) {

        ElectricityIndex electricityIndex = new ElectricityIndex();
        LinkedList<ElectricityDataDto> resultList = new LinkedList<>();
        Integer startMonth = Integer.parseInt(time.substring(5, 7));
        Integer endMonth = Integer.parseInt(time.substring(16,18));
        //  对月份进行修正
        int differYear = Integer.parseInt(endYear)- Integer.parseInt(preYear);
        if(differYear!=0){
            endMonth = endMonth + differYear*12 ;
        }
        Integer j = startMonth ;
        Integer k = Integer.parseInt(preYear);
        HashMap<String, Float> collect = new HashMap<>();
        HashMap<String, Float> collectOut = new HashMap<>();
        HashMap<String, Float> electricity = new HashMap<>();
        DecimalFormat df = new DecimalFormat(".0000"); //保留4位小数

        for (int i = 0; i < valuesList.size(); i++) {
            collect.put(valuesList.get(i).getStatDate(),valuesList.get(i).getDataValue());
        }
        for (int i = 0; i < valuesListout.size(); i++) {
            collectOut.put(valuesListout.get(i).getStatDate(),valuesListout.get(i).getDataValue());
        }
        for (int i = 0; i < electricityList.size(); i++) {
            electricity.put(electricityList.get(i).getStatDate(),electricityList.get(i).getDataValue());
        }
        for (int i = startMonth; i <=endMonth; i++) {
            String baseTime =null;
            if(j<=12){
                if(j<10){
                    baseTime = (k)+"-0"+j;
                }else {
                    baseTime = k+"-"+j;
                }
            }else if(j>12){
                k = k + 1 ;
                j= j-12;
                if(j<10){
                    baseTime =k+"-0"+j;
                }else {
                    baseTime = k+"-"+j;
                }
            }
            j++;

            ElectricityDataDto electricityDataDto = new ElectricityDataDto();
            electricityDataDto.setMonth(baseTime);
            if(electricity.get(baseTime)!=null){

                electricityDataDto.setValue(Float.parseFloat(df.format(electricity.get(baseTime)/10000)));
            }
            if(collect.get(baseTime)!=null){
                electricityDataDto.setUploadValue(Float.parseFloat(df.format(collect.get(baseTime)/10000)));
            }
            if(collectOut.get(baseTime)!=null){
                electricityDataDto.setOutValue(Float.parseFloat(df.format(collectOut.get(baseTime)/10000)));
            }
            resultList.add(electricityDataDto);
        }
        // 查询企业一级电力数据
        electricityIndex.setList(resultList);
        electricityIndex.setNumber(num);
        return electricityIndex ;
    }

    private HashMap<String,String> getAreaAndIndustryCode(String area, String industry) {
        HashMap<String, String> map = new HashMap<>();
        HashMap<String, String> areaMapA = areaCode.getAreaMapA();
        HashMap<String, String> industryMap = industryCode.getIndustryMap();
        String areaName;
        if(isNUm(area)){
            areaName = area;
        }else {
            areaName = areaMapA.get(area);
        }

        String industryName = industryMap.get(industry);
        map.put("地区",areaName);
        map.put("行业",industryName);
        return map;
    }

    private Boolean isNUm(String area) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(area).matches();
    }
}

