import moment = require("moment");
import { dataCenterInterfaceConfig, systemConfig } from "../../config/serverConfig";
import { get } from "../../util/request";
import { guangfuTableData } from "../table/tableData";
import { BizError } from "../../util/bizError";


/**
 * 光伏
 * @returns 
 */
export async function getGuangFu() {
    let result = {
        jbqk:[], //基本情况
        nhfx:{count:[], charData:[], dayData:[]}, //能耗分析 
        trsy:{count:[], charData:[]}, //投入使用
        ztsj:[], //整体数据
        xyfxfd:{count:[], chartData:[]}, //效益分析-发电
        xyfx:{count:[], chartData:{}}, //效益分析
        jnjp:{count:[], chartData:[]} //节能减排
    };

    // let userquery = {user_name:systemConfig.userName};
    let header = {token:systemConfig.token};
    let hqmdzsjgl:any = await get(dataCenterInterfaceConfig.hqmdzsjgl, {plant_id:systemConfig.plantId}, header);
    if (!hqmdzsjgl.body) console.log("接口请求失败-获取某电站数据概览：hqmdzsjgl");

    let nowTime = new Date().valueOf();

    /**基本情况 */
    let jbqkData = {
        安全运行天数:0,
        组件总功率:0,//todo
        设备总数:0//todo
    };

    let hqmdzjbxx:any = await get(dataCenterInterfaceConfig.hqmdzjbxx, {plant_id:systemConfig.plantId}, header);
    if (!hqmdzjbxx.body) console.log("接口请求失败-获取某电站基本信息：hqmdzjbxx");
    let jzmqts = 0;
    if (hqmdzjbxx.body) {
        let createDate = new Date(hqmdzjbxx.body.create_date).valueOf();
        console.log(moment(nowTime).format("YYYY-MM-DD"))
        console.log(moment(createDate).format("YYYY-MM-DD"))
        jzmqts = (nowTime - createDate) / (1000 * 60 * 60 * 24); //当前时间-建站日期=当前安全运行天数
        jbqkData.安全运行天数 = Math.ceil(jzmqts) || 0;
        for (let key in jbqkData) {
            result.jbqk.push( {key, value:jbqkData[key]} );
        }
    }
    

    /**能耗分析 */
    let nhfxData = {
        "年用电量":0,
        "光伏发电量":0
    }

    if (hqmdzsjgl.body) nhfxData.光伏发电量 = hqmdzsjgl.body.total_energy || 0;
    
    let nowYearAgo = moment(nowTime).format("YYYY-MM-DD");
    let sixYearAgo = moment().subtract(6, 'years');
    let startYear = moment(sixYearAgo).format("YYYY");

    let nhfxquery = {
        plant_id:systemConfig.plantId,
        start_date:`${startYear}-01-01`,
        end_date:nowYearAgo,
        time_unit:"year",
    }
    let pjzData:any = await get(dataCenterInterfaceConfig.hqmdzlsfdl, nhfxquery, header);
    if (!pjzData.body) console.log("接口请求失败-获取某电站历史发电量：hqmdzlsfdl");
    let nowYear = moment(nowTime).format("YYYY");
    //平均值
    if (pjzData.body) {
        pjzData.body.energys.forEach( info => {
            let {date, energy} = info;
            let value = Math.round((energy/365)*100)/100;
            result.nhfx.charData.push({key:date, value});
        
            if (date == nowYear) nhfxData.年用电量 = energy;
        })
    }
   

    //当天功率
    let query = {
        plant_id:systemConfig.plantId,
        date:nowYearAgo,
    }
    let hqmdzmytglData:any = await get(dataCenterInterfaceConfig.hqmdzmytgl, query, {token:systemConfig.token});
    if (!hqmdzmytglData.body) console.log("接口请求失败-获取某电站某一天功率数据：hqmdzmytgl");
    let dayData = {};
    if (hqmdzmytglData.body) {
        hqmdzmytglData.body.powers.forEach( info => {
            let {time, power} = info;
            let dayTime = moment(time).format("HH:00");
            if (!dayData[dayTime]) dayData[dayTime] = 0;
            if (power) dayData[dayTime] += power;
            
        })
    }
    
    for(let key in dayData) {
        result.nhfx.dayData.push({key, value:dayData[key]});
    }
    result.nhfx.dayData.sort((a, b) => {
        return a.key - b.key
    })
    
    //汇总数据
    for (let key in nhfxData) {
        result.nhfx.count.push( {key, value:nhfxData[key]} );
    }

    /**投入使用 */
    let excelData = guangfuTableData();

    let trsyCount = {
        发电量:0,
        发电时长:0
    }
    if (hqmdzsjgl.body) trsyCount.发电量 = hqmdzsjgl.body.total_energy;
    trsyCount.发电时长 = jzmqts * 24; //当前安全运行天数，天换算成小时
    
    for (let key in trsyCount) {
        excelData["投入使用"].dataList.push({key, value:trsyCount[key]});
    }
    result.trsy.count = excelData["投入使用"].dataList;
    result.trsy.charData = excelData["投入使用趋势"].dataList;

    /**整体数据 */
    let ssData = {
        装机容量:0,
        总发电量:0,
        实时功率:0
    };

    if (hqmdzsjgl.body) {
        ssData.装机容量 = hqmdzsjgl.body.peak_power_actual;
        ssData.总发电量 = hqmdzsjgl.body.total_energy;
        ssData.实时功率 = hqmdzsjgl.body.current_power;
    }
    
    for (let key  in ssData) {
        result.ztsj.push({key, value:ssData[key]});
    }

    /**效益分析-发电 */
    let xyfxfdData = {
        今日发电:0,
        日功率:0,
        当前功率:0,
        等效小时数:0
    }
    if (hqmdzmytglData.body) {
        hqmdzmytglData.body.powers.forEach( info => {
            xyfxfdData.日功率 += info.power;
        })
    }
    
    if (hqmdzsjgl.body) {
        xyfxfdData.今日发电 = hqmdzsjgl.body.today_energy;
        xyfxfdData.当前功率 = hqmdzsjgl.body.current_power;
    }

    let xyfxdayAgo = moment().subtract(7, 'days');
    let xyfxnowTime = moment(xyfxdayAgo).format("YYYY-MM-DD");
    let xyfxendTime = moment(new Date()).format("YYYY-MM-DD");

    let hqmdzlsfdlQuery = {
        plant_id:systemConfig.plantId,
        start_date:xyfxnowTime,
        end_date:xyfxendTime,
        time_unit: "day",
    }
    /** todo 接口调用频率限制---------------------------------------------------------------------------------------- */
    // let hqmdzlsfdlData:any = await get(dataCenterInterfaceConfig.hqmdzlsfdl, hqmdzlsfdlQuery, {token:systemConfig.token});
    // if (!hqmdzlsfdlData) throw new BizError('数据未返回');
    // hqmdzlsfdlData.body.energys.forEach( info => {
    //     let {date, energy} = info;
    //     result.xyfxfd.chartData.push({key:date, value:energy});
    // })

    // for (let key in xyfxfdData) {
    //     result.xyfxfd.count.push( {key, value:xyfxfdData[key]} );
    // }
    /** todo 接口调用频率限制---------------------------------------------------------------------------------------- */

    /**效益分析 */
    let xyfxData = {
        今日收益:0,
        当月收益:0,
        累计收益:0
    };

    let price = 0;
    let ljsy = 0;
    excelData["效益分析"].dataList.forEach( info => {
        if (info.key == "电价") price = info.value; //今日电价
        if (info.key == "累计收益") ljsy = info.value;
    })

    if (hqmdzsjgl.body) {
        xyfxData.今日收益 = hqmdzsjgl.body.today_energy * price;
        xyfxData.当月收益 = hqmdzsjgl.body.monthly_energy * price;
    }
    xyfxData.累计收益 = ljsy;

    for (let key in xyfxData) {
        result.xyfx.count.push({key, value:xyfxData[key]});
    }

    // 今年
    let thisYear = [];
    /** todo 接口调用频率限制---------------------------------------------------------------------------------------- */
    // hqmdzlsfdlData.body.energys.forEach( info => {
    //     let {date, energy} = info;
    //     let thisPrice = energy * price;
    //     thisYear.push({key:date, value:thisPrice});
    // });
    /** todo 接口调用频率限制---------------------------------------------------------------------------------------- */
    result.xyfx.chartData["今年"] = thisYear;

    //去年
    /** todo 接口调用频率限制---------------------------------------------------------------------------------------- */
    // let yearAgo = moment().subtract(1, 'years');
    // let dayAgo = moment().subtract(7, 'days');
    // let startDate = `${yearAgo}-${moment(dayAgo).format("-MM-DD")}`;
    // let endDate = `${yearAgo}-${moment(nowTime).format("MM-DD")}`;
    // let xyfxquery = {
    //     plant_id:systemConfig.plantId,
    //     start_date:startDate,
    //     end_date:endDate,
    //     time_unit:"year",
    // }
    // let hqmdzlsfdl:any = await get(dataCenterInterfaceConfig.hqmdzlsfdl, xyfxquery, header);
    // if (!hqmdzlsfdl) throw new BizError('数据未返回');
    let lastyear = [];
    // hqmdzlsfdl.body.energys.forEach( info => {
    //     let {date, energy} = info;
    //     let thisPrice = energy * price; 
    //     lastyear.push({key:date, value:thisPrice});
    // });
    result.xyfx.chartData["去年"] = lastyear;
    /** todo 接口调用频率限制---------------------------------------------------------------------------------------- */

    /**节能减排 */
    result.jnjp.count = excelData["节能减排"].dataList;



    return result;
}




