package com.nantian.cloud.dbcapp.task;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.nantian.cloud.dbcapp.config.OpsConfig;
import com.nantian.cloud.dbcapp.entity.CompanyMaterielProduct;
import com.nantian.cloud.dbcapp.mapper.collectmaster.CollectMasterDataMapper;
import com.nantian.cloud.dbcapp.mapper.energyinfo.EnergyInfoDataMapper;
import com.nantian.cloud.dbcapp.mapper.jly.EnergyInfoMapper;
import com.nantian.cloud.dbcapp.mapper.jly.SysInfoMapper;
import com.nantian.cloud.dbcapp.mapper.record.EnterpriseDataInfoMapper;
import com.nantian.cloud.dbcapp.mapper.record.EnterpriseEnergyDataMapper;
import com.nantian.cloud.dbcapp.service.ConfigureGaugeRelevanceService;
import com.nantian.cloud.dbcapp.service.EnergyCalculateService;
import com.nantian.cloud.dbcapp.service.EnergyService;
import com.nantian.cloud.dbcapp.vo.*;
import com.nantian.scheduling.core.context.XxlJobHelper;
import com.nantian.scheduling.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
@EnableScheduling
public class CalculateTask {
    @Autowired
    EnergyCalculateService energyCalculateService;

    @Autowired
    EnterpriseDataInfoMapper enterpriseDataInfoMapper;

    @Autowired
    EnterpriseEnergyDataMapper energyDataMapper;

    @Autowired
    EnergyInfoDataMapper energyInfoDataMapper;

    @Autowired
    EnergyInfoMapper infoMapper;

    @Autowired
    SysInfoMapper sysInfoMapper;

    @Autowired
    CollectMasterDataMapper collectMasterDataMapper;

    @Autowired
    EnergyService energyService;

    @Autowired
    private ConfigureGaugeRelevanceService configureGaugeRelevanceService;

    private static String DB_NAME = OpsConfig.getOpsConfig("ops-db");

    /**
     * 备份实时库采集数据
     */
    @XxlJob("collectDataBackup")
    public void collectDataBackup(){
        List<String> tableNameList = collectMasterDataMapper.getTableNameList();
        String[] tableNames = tableNameList.toArray(new String[tableNameList.size()]);
        collectMasterDataMapper.saveCollectDataBackup(tableNames);
    }


    /**
     * configure_data_collect_new 与 configure_data_collect 保持一致
     */
    //@Scheduled(cron = "0 40 5 * * ?")
    @XxlJob("renewCollect")
    public void renewCollect(){
        //删除存在configure_data_collect_new，不在configure_data_collect的数据
        enterpriseDataInfoMapper.deleteNewCollect();
        //configure_data_collect_new 与 configure_data_collect 采集频率保持一致
        enterpriseDataInfoMapper.updateNewCollect();
        //插入新增的数据
        enterpriseDataInfoMapper.insertNewCollect();
    }

    /**
     * 同步产品数据
     */
    //@Scheduled(cron = "0 40 5 * * ?")
    @XxlJob("renewMaterielProduct")
    public void renewMaterielProduct(){
        //获取采集系统的产品数据
        List<CompanyMaterielProduct> productList = energyInfoDataMapper.getProductList();
        //同步数据至应用分析系统
        if(productList!=null &&  productList.size()>0){
            int num = 0;
            for (CompanyMaterielProduct item : productList) {
                num += enterpriseDataInfoMapper.renewMaterielProduct(item);
            }
            XxlJobHelper.handleSuccess("同步产品数据完成，本次更新数据 " + num + " 条。");
        }else{
            XxlJobHelper.handleSuccess("采集库产品数据为空，无法同步产品数据！");
        }
    }

    /**
     * 定时任务 ： 每天7点执行一次 在线监测企业自动注册用能单位子系统账户
     */
    //@Scheduled(cron = "0 0 7 * * ?")
    @XxlJob("addEpcAccount")
    public void addEpcAccount(){
        //获取已有账户的企业
        List<String> accountList = sysInfoMapper.getEpcByAccount(DB_NAME);
        //获取新注册企业
        List<Map<String, String>> registerEnterpriseList = energyDataMapper.getRegisterEnterprise(accountList);
        //注册用能单位子系统账户
        for (Map<String, String> map : registerEnterpriseList) {
            EnergyVo vo = new EnergyVo();
            Integer id = sysInfoMapper.insertAccount(map.get("enterpriseCode"),map.get("cmpName"),map.get("regionCode"),DB_NAME);
        }
    }

    /**
     * 处理energy_record企业信息、企业新老数据截止日期表
     */
    //@Scheduled(cron = "0 0 2 * * ?")
    @XxlJob("distinctEnterpriseInfo")
    public void distinctEnterpriseInfo(){
        //设置老平台企业名称
        enterpriseDataInfoMapper.updateOldEnterpriseName();
        //设置端系统接入企业，行业信息
        enterpriseDataInfoMapper.updateEnterpriseTrade();
        //企业表信息中间表
        enterpriseDataInfoMapper.insertEnterpriseTmp();
        //配置history_config_endtime表
        enterpriseDataInfoMapper.configEndTime();
        //配置t_configure_energykinds表
        //enterpriseDataInfoMapper.configEnergyKinds();
        //将energy_record库的enterprise_info表信息 同步至 jly库的enterprise_info表
        enterpriseDataInfoMapper.insertEnterpriseJly();
    }

    /**
     * 每6小时更新在线采集、电网、上送国家、异常的数值 中间表
     */
    //@Scheduled(cron = "0 0 0,6,12,18 * * ?")
    @XxlJob("renewEnterpriseDataAll")
    public void renewEnterpriseDataAll() {
        //在线监测企业数据中间表
        enterpriseDataInfoMapper.insertEnterpriseDataTmp();
    }

    /**
     * 每天10:30 22:30 同步在线采集计量器具、计量人员、计量设备信息 至 应用分析系统jly库
     */
    //@Scheduled(cron = "0 30 10,22 * * ? ")
    @XxlJob("ynenergyInfo")
    public void ynenergyInfo() throws ParseException {
        try{
            //获取应用分析系统计量器具引用id
            List<String> gaugeIds = infoMapper.getIdsByGauge();
            //同步在线采集新增计量器具信息，至应用分析系统
            List<ConfigureGaugeVo> configureGaugeVos = energyInfoDataMapper.getConfigureById(gaugeIds);
            if(configureGaugeVos!=null && configureGaugeVos.size()>0){
                for (ConfigureGaugeVo gaugeVo : configureGaugeVos) {
                    gaugeVo.setDateTmp();
                }
                infoMapper.insertConfigureGauge(configureGaugeVos); //jly库
                enterpriseDataInfoMapper.insertConfigureGauge(configureGaugeVos); //energy_record库
            }

            //获取应用分析系统计量人员引用id
            List<String> calculaterIds = infoMapper.getIdsByCalculater();
            //同步在线采集新增计量人员信息，至应用分析系统
            List<CompanyCalculaterVo> companyCalculaterVos = energyInfoDataMapper.getCalculaterById(calculaterIds);
            if(companyCalculaterVos!=null && companyCalculaterVos.size()>0){
                infoMapper.insertCalculater(companyCalculaterVos); //jly库
            }

            //获取应用分析系统计量设备引用id
            List<String> deviceIds = infoMapper.getIdsByDevice();
            //同步在线采集新增计量设备信息，至应用分析系统
            List<ConfigureDeviceVo> configureDeviceVos = energyInfoDataMapper.getDeviceById(deviceIds);
            if(configureDeviceVos!=null && configureDeviceVos.size()>0){
                infoMapper.insertDevice(configureDeviceVos); //jly库
            }
        }catch (Exception e){
            System.err.println(e);
        }
    }

    public void ynenergyInfoOld() throws ParseException {
        //获取应用分析系统计量器具的企业编码
        List<String> epcList = enterpriseDataInfoMapper.getConfigureGaugeEpc();
        //在线监测新增企业，同步一次计量器具信息至应用分析系统
        List<ConfigureGaugeVo> configureGaugeVos = energyInfoDataMapper.getConfigureAllInfo(epcList);
        if(configureGaugeVos!=null && configureGaugeVos.size()>0){
            for (ConfigureGaugeVo gaugeVo : configureGaugeVos) {
                gaugeVo.setDateTmp();
            }
            infoMapper.insertConfigureGauge(configureGaugeVos); //jly库
            enterpriseDataInfoMapper.insertConfigureGauge(configureGaugeVos); //energy_record库
        }
        //获取应用分析系统计量人员的企业编码
        List<String> epcList2 = infoMapper.getInfoEpc();
        //在线监测新增企业，同步一次计量人员至应用分析系统
        List<CompanyCalculaterVo> companyCalculaterVos = energyInfoDataMapper.getCalculaterAllInfo(epcList);
        if(companyCalculaterVos!=null && companyCalculaterVos.size()>0){
            infoMapper.insertCalculater(companyCalculaterVos); //jly库
        }
    }

    /**
     * 能报单位产值综合能耗数据录入t_output_value表
     */
    //@Scheduled(cron = "0 0 20 * * ?")
    @XxlJob("unitEnergyConsumption")
    public void unitEnergyConsumption(){
        enterpriseDataInfoMapper.insertUnitEnergyConsumption();
    }

    /**
     * 能报 推送滞留在州市的报表至省级
     */
    @XxlJob("reportPush")
    public void reportPush(){
        String param = XxlJobHelper.getJobParam();
        // 默认企业上报10天后，州市部门未审核报表将自动推送至省级部门
        int step = 10;
        //任务调度的参数
        if (StringUtils.isNotEmpty(param)){
            step = Integer.parseInt(param);
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String date = df.format(new Date());
        //州市未审核日志
        int i = enterpriseDataInfoMapper.noProvStatusLog(date,step);
        //定时推送滞留在州市的报表至省级
        int j = enterpriseDataInfoMapper.upProvStatus(date,step);
        XxlJobHelper.handleSuccess("【返回信息】记录州市未审核日志 "+i+" 条，推送滞留在州市的报表至省级 "+j+" 张。");
    }

    /**
     * 更新中间表(根据公式反推企业能源消耗量)
     */
    @XxlJob("energyConsumption")
    public void energyConsumption() throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
        String date = df.format(new Date());
        //获取公式中计算点
        List<String> dataCodeList = energyService.parseFormulToSimpleAndParamsMap("云南", "全部", "2020-01&" + date, "2020-01", date, null);
        energyService.renewEnergyConsumptionByForuml(dataCodeList, "2020-01", date);
        XxlJobHelper.handleSuccess("【返回信息】更新各能源品种消耗量。");
    }

    @XxlJob("autoMatchRelevance")
    public void autoMatchRelevance(){
        int total = configureGaugeRelevanceService.autoMatchRelevance();
        XxlJobHelper.log("计量器具与采集配置项自动匹配新增：" + total + "条");
    }
}
