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


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nantian.cloud.dbcapp.dto.ExceptionByAreaBo;
import com.nantian.cloud.dbcapp.mapper.jly.EnergyInfoMapper;
import com.nantian.cloud.dbcapp.mapper.record.EnergyMapper;
import com.nantian.cloud.dbcapp.mapper.record.MobileMapper;
import com.nantian.cloud.dbcapp.service.MobileService;
import com.nantian.cloud.dbcapp.tool.AreaCode;
import com.nantian.cloud.dbcapp.tool.IndustryCode;
import com.nantian.cloud.dbcapp.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;


/**
 * <p>
 * 综合能耗 服务实现类
 * </p>
 *
 * @author zfw
 * @since 2020-08-05
 */
@Service("mobileService")
public class MobileServiceImpl implements MobileService {

    @Autowired
    private MobileMapper mobileMapper;

    @Autowired
    private AreaCode areaCode;

    @Autowired
    private IndustryCode industryCode;

    @Autowired
    EnergyServiceImpl energyService;

    @Autowired
    EnergyMapper energyMapper ;

    @Autowired
    EnergyInfoMapper energyInfoMapper ;
    /**
    * @Description: 根据不同的条件查询综合能耗
    * @Param: [area, industry, time]
    * @return: java.lang.Float
    * @Author: zfw
    * @Date: 2020/12/26
    * @Date: 15:00
    */
    @Override
    public  JSONArray getTotal(String area ,String industry,String time) {
        JSONArray jsonArray = new JSONArray();
        //截取时间
        String startTime = null;
        String endTime = null;
        if (time.contains("&")) {
            startTime = time.split("&")[0];
            endTime = time.split("&")[1];
            startTime = startTime.substring(0, 7);
            endTime = endTime.substring(0, 7);
        }
        //匹配地区 昆明市、曲靖市、玉溪市、昭通市、丽江市、普洱市、保山市、临沧市、楚雄州、红河州、迪庆州、文山州、西双版纳州、大理州、德宏州、怒江州
        HashMap<String, String> areaAndIndustryCode = energyService.getAreaAndIndustryCode(area, industry);
        String areaCode = (area.trim().equals("53") || area.trim().equals("云南")) ? "53" : areaAndIndustryCode.get("地区");
        int code = Integer.parseInt(areaCode);
        String inde1 = industry.trim().equals("全部") ? null : areaAndIndustryCode.get("行业");

        List<String> companyList=new ArrayList<>();
        List<CoalVo> list=new ArrayList<>();
        List<CoalVo> list1=new ArrayList<>();
        String startYear=startTime.substring(0,4);
        if(Integer.valueOf(startTime.substring(0,4))>=2020){ //查询2020年
            companyList=mobileMapper.getCompanyListByYear(code,inde1);
            if(companyList!=null & companyList.size()>0) {
                list = mobileMapper.getInfo1(companyList, startTime, endTime);
                // 按月遍历
                for (int i = Integer.parseInt(startTime.substring(5,7)); i <=Integer.parseInt(endTime.substring(5,7)); i++) {
                    CoalVo coalVo;
                    if(i<10){
                        coalVo = new CoalVo(startYear+"-0" + i, "0");
                    }else {
                        coalVo = new CoalVo(startYear+"-"+i, "0");
                    }
                    for (CoalVo data:list) {
                        if(coalVo.getMonth().endsWith(data.getMonth())){
                            coalVo.setValue(data.getValue());
                        }
                    }
                    list1.add(coalVo);
                }


                for (int i =0;i< list1.size();i++){
                    JSONObject jo = new JSONObject();
                    jo.put("name",list1.get(i).getMonth());
                    jo.put("value",list1.get(i).getValue());
                    jsonArray.add(jo);
                }
            }
        }else{//查询2019年
                //查询企业
            companyList=  mobileMapper.getAllCompanyList2019(code,inde1,null);
            //把list转为老的entid
            List<String> entidList=getentIdByEnterpriseCode(companyList);
               if (companyList.size()>0 && companyList !=null){
                   list=mobileMapper.getTce2019(entidList,startTime,endTime);
                   for (int i = Integer.parseInt(startTime.substring(5,7)); i <=Integer.parseInt(endTime.substring(5,7)); i++) {
                       CoalVo coalVo;
                       if(i<10){
                           coalVo = new CoalVo(startYear+"-0" + i, "0");
                       }else {
                           coalVo = new CoalVo(startYear+"-"+i, "0");
                       }
                       for (CoalVo data:list) {
                           if(coalVo.getMonth().endsWith(data.getMonth())){
                               coalVo.setValue(data.getValue());
                           }
                       }
                       list1.add(coalVo);
                   }
                   for (int i =0;i< list1.size();i++){
                       JSONObject jo = new JSONObject();
                       jo.put("name",list1.get(i).getMonth());
                       jo.put("value",list1.get(i).getValue());
                       jsonArray.add(jo);
                   }
               }
        }

        return jsonArray;
    }

    /**
    * @Description: 查询企业信息信息
    * @Param: [enterpriseCode, time]
    * @return: com.nantian.cloud.dbcapp.vo.MobileInfoVO
    * @Author: zfw
    * @Date: 2021/1/13
    * @Date: 17:42
    */
    @Override
    public MobileInfoVO getCompanyInfo(String enterpriseCode, String time) {
        MobileInfoVO mobileInfoVO =new MobileInfoVO();
        String startTime=null;
        String endTime=null;
        if (time.contains("&")) {
            startTime = time.split("&")[0];
            endTime = time.split("&")[1];
            startTime=startTime.substring(0,7);
            endTime=endTime.substring(0,7);

        }
        List<CoalVo> list=new ArrayList<>();
        List<CoalVo> list1=new ArrayList<>();
        List<CoalVo> list2=new ArrayList<>();
        Float sum=0.0f;
        Integer startYear=Integer.valueOf(startTime.substring(0,4));
        if(startYear>=2020){
            mobileInfoVO=mobileMapper.getCompanyByCode(enterpriseCode);
            //通过企业id查询综合能耗
            list=mobileMapper.getTce2020(enterpriseCode,startTime,endTime);
//            for (int i = Integer.parseInt(startTime.substring(5,7)); i <=Integer.parseInt(endTime.substring(5,7)); i++) {
//            for (int i = 0; i <list.size(); i++) {
//                CoalVo coalVo;
//                if(i<10){
//                    coalVo = new CoalVo(startYear+"-0" + i, "0");
//                }else {
//                    coalVo = new CoalVo(startYear+"-"+i, "0");
//                }
//                for (CoalVo data:list) {
//                    if(coalVo.getMonth().endsWith(data.getMonth())){
//                        coalVo.setValue(data.getValue());
//                    }
//                }
//                list1.add(coalVo);
//            }
            for (int i=0;i<list.size();i++){
                sum+=Float.valueOf(list.get(i).getValue());
            }
            //查询联系人
            list2=mobileMapper.getNameAndPhone(enterpriseCode);
            List<CoalVo> list4=new ArrayList<>();
            if (list2!= null && list2.size()>0){
                if (list2.size()==1){//1个联系人
                    list4.add(0,list2.get(0));
                    list4.add(1,list2.get(0));
                    for (int i=0;i<list2.size();i++){
                        list4.add(list2.get(i));
                    }
                }else  if (list2.size()==2) {//2个联系人
                    list4.add(0,list2.get(0));
                    for (int i=0;i<list2.size();i++){
                        list4.add(list2.get(i));
                    }
                }else{ //>=3
                    for (int i=0;i<3;i++){
                        list4.add(list2.get(i));
                    }
                }
            }
            //查询采集点
            Integer collection=mobileMapper.getCollectionByCode(enterpriseCode);
            mobileInfoVO.setCollection(collection);
            mobileInfoVO.setContactList(list4);
            mobileInfoVO.setTceList(list);
            mobileInfoVO.setTce(sum.toString());
        }else{ //2019年
            Integer entID=getEntIdByenterpriseCode(enterpriseCode);
            mobileInfoVO=mobileMapper.getCompanyByCode2019(entID);
            //通过企业id查询综合能耗
            list=mobileMapper.getEnterpriceTce2019(entID,startTime,endTime);
            for (int i = Integer.parseInt(startTime.substring(5,7)); i <=Integer.parseInt(endTime.substring(5,7)); i++) {
                CoalVo coalVo;
                if(i<10){
                    coalVo = new CoalVo(startYear+"-0" + i, "0");
                }else {
                    coalVo = new CoalVo(startYear+"-"+i, "0");
                }
                for (CoalVo data:list) {
                    if(coalVo.getMonth().endsWith(data.getMonth())){
                        coalVo.setValue(data.getValue());
                    }
                }
                list1.add(coalVo);
            }
            for (int i=0;i<list.size();i++){
                sum+=Float.valueOf(list.get(i).getValue());
            }
            //查询联系人
           // list2=mobileMapper.getNameAndPhone(enterpriseCode);
            List<CoalVo> list4=new ArrayList<>();
            /*if (list2!= null && list2.size()>0){
                if (list2.size()==1){//1个联系人
                    list4.add(0,list2.get(0));
                    list4.add(1,list2.get(0));
                    for (int i=0;i<list2.size();i++){
                        list4.add(list2.get(i));
                    }
                }else  if (list2.size()==2) {//2个联系人
                    list4.add(0,list2.get(0));
                    for (int i=0;i<list2.size();i++){
                        list4.add(list2.get(i));
                    }
                }else{ //>=3
                    for (int i=0;i<3;i++){
                        list4.add(list2.get(i));
                    }
                }
            }*/
            if(mobileInfoVO.getMan1()!=null && mobileInfoVO.getPhone1()!=null){//第一个联系人
                CoalVo coalVo=new CoalVo();
                coalVo.setMonth(mobileInfoVO.getMan1());
                coalVo.setValue(mobileInfoVO.getPhone1());
                list4.add(0,coalVo);
            }
            if(mobileInfoVO.getMan2()!=null && mobileInfoVO.getPhone2()!=null){//第二个联系人
                CoalVo coalVo=new CoalVo();
                coalVo.setMonth(mobileInfoVO.getMan2());
                coalVo.setValue(mobileInfoVO.getPhone2());
                list4.add(1,coalVo);
            }else{
                CoalVo coalVo=new CoalVo();
                coalVo.setMonth(mobileInfoVO.getMan1());
                coalVo.setValue(mobileInfoVO.getPhone1());
                list4.add(0,coalVo);
            }
            if(mobileInfoVO.getMan3()!=null && mobileInfoVO.getPhone3()!=null){//第三个联系人
                CoalVo coalVo=new CoalVo();
                coalVo.setMonth(mobileInfoVO.getMan3());
                coalVo.setValue(mobileInfoVO.getPhone3());
                list4.add(2,coalVo);
            }else{
                CoalVo coalVo=new CoalVo();
                coalVo.setMonth(mobileInfoVO.getMan1());
                coalVo.setValue(mobileInfoVO.getPhone1());
                list4.add(0,coalVo);
                list4.add(1,coalVo);
            }
            //查询采集点
            Integer collection=mobileMapper.getCollectionByCode2019(entID);
            mobileInfoVO.setCollection(collection);
            mobileInfoVO.setContactList(list4);
            mobileInfoVO.setTceList(list1);
            mobileInfoVO.setTce(sum.toString());
        }
        return mobileInfoVO;
    }

    /**
    * @Description: 计量人员合计
    * @Param: []
    * @return: com.alibaba.fastjson.JSONArray
    * @Author: zfw
    * @Date: 2021/1/15
    * @Date: 15:18
    */
    @Override
    public JSONArray getSumMeasurer(String areaCode) {
        areaCode = substringAreaCode(areaCode);
        Map<Integer,Integer> map =energyInfoMapper.getMeasureTol(areaCode);
        JSONArray jsonArray = new JSONArray();
        JSONObject jo = new JSONObject();
        jo.put("cz",map.get("cz"));
        jo.put("wcz",map.get("wcz"));
        jo.put("total",map.get("total"));
        jsonArray.add(jo);
        return jsonArray;
    }

    private String substringAreaCode(String areaCode) {
        ArrayList<String> strings = new ArrayList<>();
        Collections.addAll(strings,"530100" ,"530300" ,"530400" ,"530500","530600" ,"530700" ,"530800" ,"530900" ,"532300","532500","532600","532800","532900","533100","533300","533400");
        if(areaCode.equals("530000")){
            areaCode = areaCode.substring(0,2);
        }else if(strings.contains(areaCode)){
            areaCode= areaCode.substring(0, 4);
        }else {
            areaCode = areaCode ;
        }
        return areaCode;
    }

    @Override
    public List<MobileMeasureVODto> getSumMeasurerList(String cmpName, String area, String industry) {
        ArrayList<String> strings = new ArrayList<>();
        Collections.addAll(strings,"530100" ,"530300" ,"530400" ,"530500","530600" ,"530700" ,"530800" ,"530900" ,"532300","532500","532600","532800","532900","533100","533300","533400");
        if("".equals(area)&&"".equals(industry)){
            area = "53";
            industry = null ;
        }
        if("".equals(area.trim()) || null==area.trim() ){
            area=null;
        }

//        if("".equals(industry.trim()) || null==industry.trim() ){
//            industry=null;
//        }else{
//            industry=industry.trim()+'%';
//        }
        if (!"".equals(cmpName) && cmpName!=null ){
            cmpName='%'+cmpName.trim()+'%';
        }else{
            cmpName=null;
        }
        String substring=null;
        if(area.equals("530000")){
            substring = area.substring(0,2)+"%";
        }else if(strings.contains(area)){
            substring= area.substring(0, 4)+'%';
        }else {
            substring = area + "%";
        }
        // 获取行业编码
        if("全部".equals(industry)){
            industry = null ;
        }else {
            industry =mobileMapper.selectIndustryByName(industry);
        }

        //查询公司名称
        List<String> compList=mobileMapper.getComList(cmpName,substring,industry);
        List<MobileMeasureVO> list=new ArrayList<>();
        //查询计量人员
        if (compList !=null &&compList.size()>0){
            list=mobileMapper.getMeasureList(compList);
        }
        HashMap<String, List<MobileMeasureVO>> resultMap = new HashMap<>();
        for (int i = 0; i < compList.size(); i++) {
            resultMap.put(compList.get(i),new ArrayList<MobileMeasureVO>());
        }
        for (int i = 0; i < list.size(); i++) {
            MobileMeasureVO  mobileVO = list.get(i);
            String enterpriseCode = mobileVO.getEpcCode();
            List<MobileMeasureVO> instrumentsInfos = resultMap.get(enterpriseCode);
            instrumentsInfos.add(mobileVO);
        }
        ArrayList<MobileMeasureVODto> resultList = new ArrayList<>();
        for (String epcCode: resultMap.keySet()) {
            List<MobileMeasureVO> instrumentsInfos = resultMap.get(epcCode);
            if(instrumentsInfos.size()>0){
                MobileMeasureVO mobileMeasureVO = instrumentsInfos.get(0);
                resultList.add(new MobileMeasureVODto(mobileMeasureVO.getCmpName(),epcCode,instrumentsInfos.size(),instrumentsInfos));
            }
        }
        return resultList;
    }

    /**
    * @Description: 能源计量审查任务统计
    * @Param: []
    * @return: java.lang.Integer
    * @Author: zfw
    * @Date: 2021/1/15
    * @Date: 17:05
    */
    @Override
    public Integer getSumTask(String areaCode) {
        String substring=null;
        if(areaCode.equals("530000")){
            substring = areaCode.substring(0,2)+"%";
        }else if(areaCode.substring(4, 2).equals("00")){
            substring= areaCode.substring(0, 4)+'%';
        }else {
            substring = areaCode + "%";
        }
        Integer num=energyInfoMapper.getSumTask(substring);
        return num;
    }

    /**
    * @Description:  能源计量审查任务明细
    * @Param: [name, type]
    * @return: java.util.List<com.nantian.cloud.dbcapp.vo.MobileTaskVO>
    * @Author: zfw
    * @Date: 2021/1/15
    * @Date: 17:15
    */
    @Override
    public List<MobileTaskVO> getSumTaskList(String name, String type) {
        if(!"".equals(name.trim()) && null != name.trim()){
            name='%'+name+'%';
        }else{
            name=null;
        }
        if(!"".equals(type.trim()) && null != type.trim()){
            type=type;
        }else{
            type=null;
        }

        //查询任务列表
        List<MobileTaskVO> list =energyInfoMapper.getTaskList(name,type);

        if (list!=null && list.size()>0){
            for (int i=0;i<list.size();i++){
                //MobileTaskVO mobileTaskVO =new MobileTaskVO();
                //查询该审核任务下面的企业
                List<MobileCompVO> list1=energyInfoMapper.getCompListByPlanId(list.get(i).getId());
                //mobileTaskVO.setCmpList(list1);
                list.get(i).setCmpList(list1);
            }

        }


        return list;
    }

    @Override
    public List<MobileUpDateCountryVo> getUpDateCountryInfo(String time, String area, String industry) {
        HashMap<String, String> areaAndIndustryCode = energyService.getAreaAndIndustryCode(area, industry);
        String areaName = areaAndIndustryCode.get("地区");
        String industryName = areaAndIndustryCode.get("行业");
        //获取在线监测企业数量
        List<String> companyList2020 = energyService.getCompanyList2020(areaName, industryName, null, null);
        //获取电网公司企业数量
        List<String> electricityCompanyList2020 =energyService.getElectricityCompanyList(areaName,industryName,null);
        // 按月获取
        if("".equals(time)||time==null){
            time = "2021" ;
        }
        if(time.length()==4){
            List<MobileUpDateCountryVo> upCountryList = getUpCountryList(time, areaName, industryName, companyList2020, electricityCompanyList2020, "SUBSTRING( a.statDate,1,7)", "SUBSTRING(a.time,1,7)",areaName,industryName);
            // 将上传国家平台数据转化为当月的最后一天数据
            // 获取系统当前时间
            Date date=new Date();
            DateFormat format=new SimpleDateFormat("yyyy-MM-dd");
            String format1 = format.format(date); //2021-02-23
            //系统时间减-1
            Integer day=Integer.valueOf(format1.substring(8,10))-1;
            String substring = format1.substring(0, 7);
            format1 = format1.substring(0, 7)+"-"+day.toString();
            for (int i = 0; i < upCountryList.size(); i++) {
                MobileUpDateCountryVo mobileUpDateCountryVo = upCountryList.get(i);
                String statDate = mobileUpDateCountryVo.getStatDate();
                if(i==0||i==2||i==4||i==6||i==7||i==9||i==11){
                    statDate = statDate + "-31";
                }else if (i==1){
                    statDate = statDate + "-28";
                }else {
                    statDate = statDate + "-30";
                }
                if(statDate.substring(0,7).equals(substring)){
                    // 获取当前最新时间
                  String maxTime = mobileMapper.selectMaxTime();
                    statDate = maxTime;
                }
                // 查询该天上传国家情况
                List<Integer> integers = mobileMapper.selectUpdateCountryByDay(areaName+"%", industryName, statDate);
                mobileUpDateCountryVo.setUpdateCountryNUm(integers.get(0)+integers.get(2));
                mobileUpDateCountryVo.setUpdateCountryNUmSuccess(integers.get(1)+integers.get(3));
                mobileUpDateCountryVo.setUpdateCountryNUmFail(mobileUpDateCountryVo.getUpdateCountryNUm()-mobileUpDateCountryVo.getUpdateCountryNUmSuccess());
            }
            return upCountryList;
        }
        //按天获取
        else if(time.length()==7){
            return getUpCountryList(time, areaName, industryName, companyList2020, electricityCompanyList2020,"SUBSTRING( a.statDate,1,10)","SUBSTRING(a.time,1,10)",areaName,industryName);
        }else {
            return getUpCountryList(time, areaName, industryName, companyList2020, electricityCompanyList2020,"SUBSTRING( a.statDate,1,10)","SUBSTRING(a.time,1,10)",areaName,industryName);
        }
    }

    @Override
    public List<MobileEnterpriseVo> getUpDateEnterpriseInfo(String cmpName, String area, String industry) {
        HashMap<String, String> areaAndIndustryCode = energyService.getAreaAndIndustryCode(area, industry);
        String areaName = areaAndIndustryCode.get("地区");
        String industryName = areaAndIndustryCode.get("行业");
        if("".equals(cmpName)){
            cmpName=null;
        }else {
            cmpName = "%"+cmpName+"%";
        }
        //首先筛选企业  首先查询企业基本信息 去除重复企业
        List<MobileEnterpriseVo> result = mobileMapper.selectEnterpriseBaseInfo(areaName+"%",industryName,cmpName);

        // 查询在线监测企业情况
        List<MobileEnterpriseVo> resultCollect = mobileMapper.selectEnterpriseCollectInfo();

        // 查询电网公司上送情况
        List<MobileEnterpriseVo> resultElectricity = mobileMapper.selectEnterpriseElectricityInfo();
        // 查询上传国家情况
        List<MobileEnterpriseVo> resultUpdate = mobileMapper.selectEnterpriseUpdateInfo("count(a.channelType=\"1\" or null)","count(a.channelType!=\"1\" or null)");
        List<MobileEnterpriseVo> resultUpdate1 = mobileMapper.selectEnterpriseUpdateInfo1("count(a.channelType=\"1\" or null)","count(a.channelType!=\"1\" or null)");
        List<MobileEnterpriseVo> resultUpdate2 = mobileMapper.selectEnterpriseUpdateInfo2("count(a.channelType=\"1\" or null)","count(a.channelType!=\"1\" or null)");
        for (int i = 0; i < result.size(); i++) {
            MobileEnterpriseVo mobileEnterpriseVo = result.get(i);
            for (int j = 0; j < resultCollect.size(); j++) {
                MobileEnterpriseVo mobileEnterpriseVo1 = resultCollect.get(j);
                if(mobileEnterpriseVo1.getEnterpriseCode().equals(mobileEnterpriseVo.getEnterpriseCode())){
                    mobileEnterpriseVo.setCollectValue(mobileEnterpriseVo1.getCollectValue());
                    break;
                }
            }
            for (int k = 0; k < resultElectricity.size(); k++) {
                MobileEnterpriseVo mobileEnterpriseVo2 = resultElectricity.get(k);
                Integer electricity = mobileEnterpriseVo2.getElectricity();
                if(mobileEnterpriseVo2.getEnterpriseCode().equals(mobileEnterpriseVo.getEnterpriseCode())){
                    mobileEnterpriseVo.setElectricity(electricity);
                    break;
                }
            }
            for (int z = 0; z < resultUpdate.size(); z++) {
                MobileEnterpriseVo mobileEnterpriseVo3 = resultUpdate.get(z);
                MobileEnterpriseVo mobileEnterpriseVo4;
                if(resultUpdate1.size()>0&&z<resultUpdate1.size()){
                    mobileEnterpriseVo4 = resultUpdate1.get(z);
                }else {
                    mobileEnterpriseVo4=null;
                }
                MobileEnterpriseVo mobileEnterpriseVo5;
                if(resultUpdate2.size()>0&&z<resultUpdate2.size()){
                    mobileEnterpriseVo5 = resultUpdate2.get(z);
                }else {
                     mobileEnterpriseVo5 = null ;
                }
                if(mobileEnterpriseVo3.getEnterpriseCode().equals(mobileEnterpriseVo.getEnterpriseCode())){
                    mobileEnterpriseVo.setUpdateCountryNum(mobileEnterpriseVo3.getUpdateCountryNum());
                   if(resultUpdate1.size()>0&&mobileEnterpriseVo4!=null){
                       mobileEnterpriseVo.setUpdateCountryCollectNum(mobileEnterpriseVo4.getUpdateCountryNum());
                   }
                   if(resultUpdate2.size()>0&&mobileEnterpriseVo5!=null){
                       mobileEnterpriseVo.setUpdateCountryElectricityNum(mobileEnterpriseVo5.getUpdateCountryNum());
                   }
                    break;
                }
            }
        }
        return result;
    }

    @Override
    public HashMap<String, List<UpdateEnterpriseInfo>>  getUpDateEnterpriseSimple(String cmpName, String time) {
        if("".equals(cmpName)||cmpName==null){
            cmpName=null;
        }else {
            cmpName = "%"+cmpName+"%";
        }
        List<MobileEnterpriseVo> mobileEnterpriseVos = mobileMapper.selectEnterpriseBaseInfo("53%", null, cmpName);
        ArrayList<String> strings = new ArrayList<>();
        for (MobileEnterpriseVo data:mobileEnterpriseVos) {
            if(data.getEnterpriseCode()!=null||!data.getEnterpriseCode().equals("")){
                if(!strings.contains(data.getEnterpriseCode())){
                    strings.add(data.getEnterpriseCode());
                }
            }
        }

        if(strings.size()==0){
            strings=null;
        }
        List<UpdateEnterpriseInfo> mobileEnterpriseInfos = mobileMapper.selectUpdateInfo(strings,time);
        for (int i = 0; i < mobileEnterpriseInfos.size(); i++) {
            UpdateEnterpriseInfo updateEnterpriseInfo = mobileEnterpriseInfos.get(i);
            String dataCode = updateEnterpriseInfo.getDataCode();
            String substring = dataCode.substring(13, 17);
            for (int j = 0; j < mobileEnterpriseVos.size(); j++) {
                MobileEnterpriseVo mobileEnterpriseVo = mobileEnterpriseVos.get(j);
                if(updateEnterpriseInfo.getEnterpriseCode().equals(mobileEnterpriseVo.getEnterpriseCode())){
                   updateEnterpriseInfo.setEnterpriseName(mobileEnterpriseVo.getEnterpriseName());
                   updateEnterpriseInfo.setAreaName(mobileEnterpriseVo.getAreaName());
                   updateEnterpriseInfo.setIndustryName(mobileEnterpriseVo.getIndustryName());
                }
            }
            if(updateEnterpriseInfo.getFrequency().equals("1")){
                updateEnterpriseInfo.setFrequency("日");
            }
            if(updateEnterpriseInfo.getChannelType().equals("3")){
                updateEnterpriseInfo.setChannelType("电网渠道");
            }else {
                updateEnterpriseInfo.setChannelType("在线监测");
            }
            if(substring.equals("3300")){
                updateEnterpriseInfo.setDataValue(updateEnterpriseInfo.getDataValue()+"万千瓦时");
            }
        }
        HashMap<String, List<UpdateEnterpriseInfo>> stringListHashMap = new HashMap<>();
            for (String data: strings) {
            ArrayList<UpdateEnterpriseInfo> updateEnterpriseInfos = new ArrayList<>();
            for (int i = 0; i < mobileEnterpriseInfos.size(); i++) {
                UpdateEnterpriseInfo updateEnterpriseInfo = mobileEnterpriseInfos.get(i);
                if(data.equals(updateEnterpriseInfo.getEnterpriseCode())){
                    updateEnterpriseInfos.add(updateEnterpriseInfo);
                }
            }
            stringListHashMap.put(data,updateEnterpriseInfos);
        }
        return stringListHashMap;
    }

    @Override
    public String getName(String code) {
        return mobileMapper.selectNameByCode(code);
    }
    /*
     按天查询异常记录
     */
    @Override
    public List<ExceptionByDay> getExceptionByDay(String time,String area) {
        HashMap<String, String> areaMapA = areaCode.getAreaMapA();
        String areaCode = areaMapA.get(area);
        List<ExceptionByDay> exceptionByDay = mobileMapper.selectExceptionByDay(time,areaCode);
        List<ExceptionInfoVo> exceptionInfoVoList = mobileMapper.selectExceptionInfos(areaCode,time);
        ArrayList<String> days = new ArrayList<>();
        HashMap<String, List<ExceptionInfoVo>> stringExceptionInfoVoHashMap = new HashMap<>();
        for (int i = 0; i < exceptionInfoVoList.size(); i++) {
            ExceptionInfoVo exceptionInfoVo = exceptionInfoVoList.get(i);
            String statDate = exceptionInfoVo.getStatDate();
            if(!days.contains(statDate)){
                days.add(statDate);
            }
        }
        if(days.size()>0){
            for (int i = 0; i < days.size(); i++) {
                ArrayList<ExceptionInfoVo> value = new ArrayList<>();
                stringExceptionInfoVoHashMap.put(days.get(i), value);
            }
            for (int i = 0; i < exceptionInfoVoList.size(); i++) {
                ExceptionInfoVo exceptionInfoVo = exceptionInfoVoList.get(i);
                String statDate = exceptionInfoVo.getStatDate();
                List<ExceptionInfoVo> exceptionList = stringExceptionInfoVoHashMap.get(statDate);
                exceptionList.add(exceptionInfoVo);
            }
            for (int i = 0; i <exceptionByDay.size(); i++) {
                ExceptionByDay exceptionByDay1 = exceptionByDay.get(i);
                String list = exceptionByDay1.getList();
                Pattern p = Pattern.compile("[,]");
                String[] split = p.split(list);
                List<String> enterpriseCodes1 = Arrays.asList(split);
                List<String> enterpriseCodes = new ArrayList<>(enterpriseCodes1);
                String statDate = exceptionByDay1.getStatDate();
                List<ExceptionInfoVo> exceptionInfoVoList1 = stringExceptionInfoVoHashMap.get(statDate);
                exceptionByDay1.setInfoList(exceptionInfoVoList1);
                ArrayList<CoalVo> numList = new ArrayList<>();
                for (int j = 0; j < enterpriseCodes.size(); j++) {
                    String epc = enterpriseCodes.get(j);
                    int num = 0;
                    for (int k = 0; k <exceptionInfoVoList1.size() ; k++) {
                        ExceptionInfoVo exceptionInfoVo = exceptionInfoVoList1.get(k);
                        String enterpriseCode = exceptionInfoVo.getEnterpriseCode();
                        if(enterpriseCode.equals(epc)){
                            num++;
                        }
                    }
                    CoalVo coalVo = new CoalVo(epc, Integer.toString(num));
                    numList.add(coalVo);
                }
                exceptionByDay1.setNumList(numList);
            }
            return exceptionByDay;
        }else {
            return exceptionByDay ;
        }
    }

    @Override
    public List<ExceptionByAreaBo> getExceptionByArea(String time, String area) {
        HashMap<String, String> areaAndIndustryCode = energyService.getAreaAndIndustryCode(area, null);
        String areaRegionCode = areaAndIndustryCode.get("地区");
        String pre = time.substring(0, 10);
        String end = time.substring(11);
        List<ExceptionByAreaBo> list =  mobileMapper.selectExceptionByArea(pre,end,areaRegionCode);
        //HashMap<String, List<ExceptionInfoVo>> listHashMap = new HashMap<>();
//        for (int i = 0; i < list.size(); i++) {
//            listHashMap.put(list.get(i).getEnterpriseCode(),list.get(i).getInfoList());
//        }
        // 查询异常明细详情
        //List<ExceptionInfoVo> detialList = mobileMapper.selectExceptionInfosByarea(areaRegionCode,pre,end)
        return list ;
    }

    @Override
    public List<InstrumentsByArea> getSumMeasurerByArea(String cmpName, String area, String industry) {
        HashMap<String, String> areaAndIndustryCode = energyService.getAreaAndIndustryCode(area, null);
        String regionCode = areaAndIndustryCode.get("地区");
        if(regionCode.length()==2){
             List<InstrumentsByArea> instrumentsByAreas = mobileMapper.selectCountByArea(regionCode, "SUBSTR(b.region_code,1,4)");
            getRegionName(instrumentsByAreas);
            return instrumentsByAreas;
         }else {
             return mobileMapper.selectCountByArea(regionCode,"b.region_code");
         }
    }

    @Override
    public List<InstrumentsByArea> getInstrumentsNumByArea(String cmpName, String area, String industry, String level) {
        HashMap<String, String> areaAndIndustryCode = energyService.getAreaAndIndustryCode(area, null);
        String regionCode = areaAndIndustryCode.get("地区");
        if(regionCode.length()==2){
            List<InstrumentsByArea> instrumentsByAreas = mobileMapper.selectCountNumByArea(regionCode, "SUBSTR(b.region_code,1,4)");
            getRegionName(instrumentsByAreas);
            return instrumentsByAreas;
        }else {
            return mobileMapper.selectCountNumByArea(regionCode,"b.region_code");
        }
    }

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

    @Override
    public List<Integer> getEnterpriseNum(String industry, String area) {
        HashMap<String, String> areaMapA = areaCode.getAreaMapA();
        HashMap<String, String> industryMap = industryCode.getIndustryMap();
        String areaNum ;
        if(isNUm(area)){
            areaNum = area ;
        }else {
            areaNum = areaMapA.get(area);
        }
        String industryNum = industryMap.get(industry);
        List<Integer> result = mobileMapper.getEnterpriseNum(industryNum,areaNum);
        return result;
    }

    private void getRegionName(List<InstrumentsByArea> instrumentsByAreas) {
        HashMap<String, String> areaMapB = areaCode.getAreaMapB();
        for (int i = 0; i < instrumentsByAreas.size(); i++) {
            InstrumentsByArea instrumentsByArea = instrumentsByAreas.get(i);
            instrumentsByArea.setAreaName(areaMapB.get(instrumentsByArea.getAreaCode()));
        }
    }

    private List<MobileUpDateCountryVo>  getUpCountryList(String time, String areaName, String industryName, List<String> companyList2020, List<String> electricityCompanyList2020,String index,String elecgtricityIndex,String area,String industry) {
        // 获取在线监测总检测数量
        List<MobileUpdateInfoBo> collectNum = new ArrayList<>();
        // 获取电力总记录数
        List<MobileUpdateInfoBo> electricityValue = new ArrayList<>();
        // 查询记录总数 电力 + 在线监测记录数
        List<MobileUpdateInfoBo> lists =  mobileMapper.selectAllInfos(time+"%",index,elecgtricityIndex,area,industry);
        // 拆分电网数据和在线监测数据
        for (int i = 0; i < lists.size(); i++) {
            MobileUpdateInfoBo mobileUpdateInfoBo = lists.get(i);
            if(mobileUpdateInfoBo.getType().equals("1")){
                collectNum.add(mobileUpdateInfoBo);
            }else {
                electricityValue.add(mobileUpdateInfoBo);
            }
        }
        // 上送国家在线企业情况
        List<MobileUpdateInfoBo> updateCountryCollect = new ArrayList<>();
        // 上送国家在线企业情况 成功
        List<MobileUpdateInfoBo>  updateCountryCollectSuccess =new ArrayList<>();
        // 上送国家电网企业情况
        List<MobileUpdateInfoBo>  updateCountryElectricity = new ArrayList<>();
        // 上送国家电网企业情况 成功
        List<MobileUpdateInfoBo>  updateCountryElectricitySuccess = new ArrayList<>();
        index = "SUBSTRING( a.uploadDate,1,10)" ;
        List<MobileUpdateInfoBo> updateLists= mobileMapper.selectUpdateAll(areaName+"%",industryName,time+"%",index);
        for (int i = 0; i < updateLists.size(); i++) {
            MobileUpdateInfoBo mobileUpdateInfoBo = updateLists.get(i);
            if(mobileUpdateInfoBo.getType().equals("1")){
                updateCountryCollect.add(mobileUpdateInfoBo);
            }else if(mobileUpdateInfoBo.getType().equals("2")){
                updateCountryCollectSuccess.add(mobileUpdateInfoBo);
            }else if(mobileUpdateInfoBo.getType().equals("3")){
                updateCountryElectricity.add(mobileUpdateInfoBo);
            }else {
                updateCountryElectricitySuccess.add(mobileUpdateInfoBo);
            }
        }
        List<MobileUpDateCountryVo> mobileUpdateInfoVos = new ArrayList<>();
        if(time.length()==4){
            return getMobileUpDateCountryVos(12,time, companyList2020, electricityCompanyList2020, collectNum, electricityValue, updateCountryCollect, updateCountryCollectSuccess, updateCountryElectricity, updateCountryElectricitySuccess, mobileUpdateInfoVos);
        }else if(time.length()==7){
            String substring = time.substring(5, 7);
            Integer integer = Integer.valueOf(substring);
            Integer max ;
            if(integer==1||integer==3||integer==5||integer==7||integer==8||integer==10||integer==12){
                max = 31;
            }else if(integer==2){
                max = 28;
            }else {
                max = 30;
            }
            return getMobileUpDateCountryVos(max,time, companyList2020, electricityCompanyList2020, collectNum, electricityValue, updateCountryCollect, updateCountryCollectSuccess, updateCountryElectricity, updateCountryElectricitySuccess, mobileUpdateInfoVos);
        }else {
            return getMobileUpDateCountryVos(1,time, companyList2020, electricityCompanyList2020, collectNum, electricityValue, updateCountryCollect, updateCountryCollectSuccess, updateCountryElectricity, updateCountryElectricitySuccess, mobileUpdateInfoVos);
        }
    }

    private List<MobileUpDateCountryVo> getMobileUpDateCountryVos(Integer max,String time, List<String> companyList2020, List<String> electricityCompanyList2020, List<MobileUpdateInfoBo> collectNum, List<MobileUpdateInfoBo> electricityValue, List<MobileUpdateInfoBo> updateCountryCollect, List<MobileUpdateInfoBo> updateCountryCollectSuccess, List<MobileUpdateInfoBo> updateCountryElectricity, List<MobileUpdateInfoBo> updateCountryElectricitySuccess, List<MobileUpDateCountryVo> mobileUpdateInfoVos) {
        Date date=new Date();
        DateFormat format=new SimpleDateFormat("yyyy-MM-dd");
        String nowTime = format.format(date); //2021-02-23
        String monthTime = nowTime.substring(0,7);
        String baseTime = null;
        // 将list转化为map
        HashMap<String, Integer> stringIntegerHashMap = new HashMap<>();
        HashMap<String, Integer> stringIntegerHashMap1 = new HashMap<>();
        HashMap<String, Integer> stringIntegerHashMap2 = new HashMap<>();
        HashMap<String, Integer> stringIntegerHashMap3 = new HashMap<>();
        for (int j = 0; j < updateCountryCollect.size(); j++) {
            MobileUpdateInfoBo mobileUpdateInfoBo = updateCountryCollect.get(j);
            stringIntegerHashMap.put(mobileUpdateInfoBo.getAnalysisTime(),mobileUpdateInfoBo.getDataNum());
        }
        for (int j = 0; j < updateCountryCollectSuccess.size(); j++) {
            MobileUpdateInfoBo mobileUpdateInfoBo = updateCountryCollectSuccess.get(j);
            stringIntegerHashMap1.put(mobileUpdateInfoBo.getAnalysisTime(),mobileUpdateInfoBo.getDataNum());
        }
        for (int j = 0; j < updateCountryElectricity.size(); j++) {
            MobileUpdateInfoBo mobileUpdateInfoBo = updateCountryElectricity.get(j);
            stringIntegerHashMap2.put(mobileUpdateInfoBo.getAnalysisTime(),mobileUpdateInfoBo.getDataNum());
        }
        for (int j = 0; j < updateCountryElectricitySuccess.size(); j++) {
            MobileUpdateInfoBo mobileUpdateInfoBo = updateCountryElectricitySuccess.get(j);
            stringIntegerHashMap3.put(mobileUpdateInfoBo.getAnalysisTime(),mobileUpdateInfoBo.getDataNum());
        }
        for (int i = 1; i <=max;i++) {
            MobileUpDateCountryVo mobileUpDateCountryVo = new MobileUpDateCountryVo();
            if(i<10&&max>1){
                baseTime = time + "-0" + i;
            }else if(i>=10&&max>1){
                baseTime = time + "-" + i ;
            }else {
                baseTime = time ;
            }
            mobileUpDateCountryVo.setStatDate(baseTime);
            mobileUpDateCountryVo.setCollectCompanyNum(companyList2020.size());
            mobileUpDateCountryVo.setElectricityCompanyNUm(electricityCompanyList2020.size());
            for (MobileUpdateInfoBo data:collectNum) {
                if(data.getAnalysisTime().equals(baseTime)){
                    mobileUpDateCountryVo.setCollectNum(data.getDataValue());
                    break;
                }
            }
            for (MobileUpdateInfoBo data:electricityValue) {
                if(data.getAnalysisTime().equals(baseTime)){
                    mobileUpDateCountryVo.setElectricityNum(data.getDataValue());
                    break;
                }
            }
            if(stringIntegerHashMap2.get(baseTime)!=null&&stringIntegerHashMap3.get(baseTime)!=null){
                mobileUpDateCountryVo.setUpdateCountryNUm(stringIntegerHashMap2.get(baseTime));
                mobileUpDateCountryVo.setUpdateCountryNUmSuccess(stringIntegerHashMap3.get(baseTime));
                mobileUpDateCountryVo.setUpdateCountryNUmFail(mobileUpDateCountryVo.getUpdateCountryNUm()-mobileUpDateCountryVo.getUpdateCountryNUmSuccess());
            }
            if(stringIntegerHashMap.get(baseTime)!=null&&stringIntegerHashMap1.get(baseTime)!=null&&stringIntegerHashMap2.get(baseTime)!=null&&stringIntegerHashMap3.get(baseTime)!=null){
                mobileUpDateCountryVo.setUpdateCountryNUm(stringIntegerHashMap.get(baseTime)+stringIntegerHashMap2.get(baseTime));
                mobileUpDateCountryVo.setUpdateCountryNUmSuccess(stringIntegerHashMap1.get(baseTime)+stringIntegerHashMap3.get(baseTime));
                mobileUpDateCountryVo.setUpdateCountryNUmFail(mobileUpDateCountryVo.getUpdateCountryNUm()-mobileUpDateCountryVo.getUpdateCountryNUmSuccess());
            }
            mobileUpdateInfoVos.add(mobileUpDateCountryVo);
            if(baseTime.length()==7&&baseTime.compareTo(monthTime)>=0){
                break;
            }
            if(baseTime.length()==10&&baseTime.compareTo(nowTime)>=0){
                break;
            }
        }
        return mobileUpdateInfoVos ;
    }
    @Override
    public Map<String, Integer> getInstrumentsNum(String areaCode) {
        String substring=null;
        if(areaCode.equals("530000")){
            substring = areaCode.substring(0,2)+"%";
        }else if(areaCode.substring(4, 2).equals("00")){
            substring= areaCode.substring(0, 4)+'%';
        }else {
            substring = areaCode + "%";
        }
        Map<String, Integer> instrumentVOS = energyInfoMapper.selectInstrumentsNum(substring);
        return instrumentVOS;
    }

    @Override
    public List<InstrumentsInfoVo> getInstrumentsInfo(String cmpName, String area, String industry,String level) {
        if("".equals(area)&&"".equals(industry)){
            area = "53";
            industry = null ;
        }
        if("".equals(area.trim()) || null==area.trim() ){
            area=null;
        }
        ArrayList<String> strings = new ArrayList<>();
        Collections.addAll(strings,"530100" ,"530300" ,"530400" ,"530500","530600" ,"530700" ,"530800" ,"530900" ,"532300","532500","532600","532800","532900","533100","533300","533400");
        if("".equals(area.trim()) || null==area.trim() ){
            area=null;
        }else{

        }
        if("全部".equals(industry)){
            industry = null ;
        }else {
            industry =mobileMapper.selectIndustryByName(industry);
        }
        if (!"".equals(cmpName) && cmpName!=null ){
            cmpName='%'+cmpName.trim()+'%';
        }else{
            cmpName=null;
        }

        if (!"".equals(level) && level!=null ){
            level=level;
        }else{
            level=null;
        }

        String substring=null;
        if(area.equals("530000")){
            substring = area.substring(0,2)+"%";
        }else if(strings.contains(area)){
            substring= area.substring(0, 4)+'%';
        }else {
            substring = area + "%";
        }

        //查询公司名称
        List<String> compList=mobileMapper.getComList(cmpName,substring,industry);
        HashMap<String, List<InstrumentsInfo>> resultMap = new HashMap<>();
        List<InstrumentsInfo> list =new ArrayList<>();
        if (compList !=null &&compList.size()>0){
            list=mobileMapper.getInstrumentsInfo(compList,level);
        }
        for (int i = 0; i < compList.size(); i++) {
            resultMap.put(compList.get(i),new ArrayList<InstrumentsInfo>());
        }
        for (int i = 0; i < list.size(); i++) {
            InstrumentsInfo instrumentsInfo = list.get(i);
            String enterpriseCode = instrumentsInfo.getEnterpriseCode();
            List<InstrumentsInfo> instrumentsInfos = resultMap.get(enterpriseCode);
            instrumentsInfos.add(instrumentsInfo);
        }
        ArrayList<InstrumentsInfoVo> resultList = new ArrayList<>();
        for (String epcCode: resultMap.keySet()) {
            List<InstrumentsInfo> instrumentsInfos = resultMap.get(epcCode);
            if(instrumentsInfos.size()>0){
                InstrumentsInfo instrumentsInfo = instrumentsInfos.get(0);
                resultList.add(new InstrumentsInfoVo(instrumentsInfo.getEnterpriseName(),epcCode,instrumentsInfos,instrumentsInfos.size()));
            }
        }
        return resultList;
    }


    public List<String> getentIdByEnterpriseCode(List<String> companyList){
        return mobileMapper.getentIdByEnterpriseCode(companyList);
    }

    public Integer getEntIdByenterpriseCode(String enterpriseCode){

        Integer entId=mobileMapper.getEntId(enterpriseCode);
        return entId;
    }

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

