<template>
    <el-dialog custom-class="globalDiaWhite" :title="title" v-model="dialogVisible" width="90%" :close-on-click-modal="false" @close="closeDialog">
         <!-- :class="from === 'index'? 'globalDia' : 'globalDiaWhite'" -->
        <div class="globalDiaMain">
            <div class="main_top">
                <div class="main_top_left">
                    <div class="exceed">
                        <span style="margin-top: 3px;">场站名称：</span>
                        <el-select v-model="windTurbines" placeholder="请选择" @change="chooseVal" >
                            <el-option
                            v-for="item in stationData"
                            :key="item.no"
                            :label="item.stationName"
                            :value="item.no">
                            </el-option>
                        </el-select>
                    </div>
                    <div class="exceed">
                        <span style="margin-top: 3px;">时间：</span>
                        <el-date-picker
                            v-model="pickerTime"
                            @change="changeTime"
                            type="datetimerange"
                            :clearable='false'
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期">
                        </el-date-picker>
                    </div>
                    <div class="exceed" v-show="title === '功率预测'">
                        <span style="margin-top: 3px;">超前：</span>
                        <el-select class="exTime" v-model="chooseExceedTimeFv" placeholder="请选择">
                            <el-option
                            v-for="item in ExceedTimeList"
                            :key="item.value"
                            :label="item.label"
                            :disabled="item.disabled"
                            :value="item.value">
                            </el-option>
                        </el-select>
                    </div>
                    <el-button type="primary" @click="seachData">查 询</el-button>
                    <el-button @click="exportExcel">导出查询结果</el-button>
                </div>
                <div class="main_top_right">
                    <!-- <el-button type="primary" v-if="title === '全域功率预测'" @click="allStationData">全域数据</el-button> -->
                </div>
            </div>
            <div v-loading="loading">
                <div class="main_charts">
                    <div id="centerCharts" class="chartsStyle"></div>
                </div>
                <div class="main_table" v-show="title === '功率预测'">
                    <el-table :data="tableData" ref="report-table_power" border style="width: 100%">
                        <el-table-column prop="dataTime" label="时间" align="center" width="160"></el-table-column>
                        <el-table-column prop="theoreticalPower" label="理论功率" align="center"></el-table-column>
                        <el-table-column prop="availablePower" label="可用功率" align="center"></el-table-column>
                        <el-table-column label="当期数据" align="center">
                            <el-table-column prop="actualPowerDq" label="实际功率" align="center"></el-table-column>
                            <el-table-column prop="veryShortTermForecastDq" label="超短期预测" align="center"></el-table-column>
                            <el-table-column prop="shortTermForecastDq" label="短期预测" align="center"></el-table-column>
                        </el-table-column>
                        <el-table-column label="同期数据" align="center">
                            <el-table-column prop="actualPowerTq" label="实际功率" align="center"></el-table-column>
                            <el-table-column prop="veryShortTermForecastTq" label="超短期预测" align="center"></el-table-column>
                            <el-table-column prop="shortTermForecastTq" label="短期预测" align="center"></el-table-column>
                        </el-table-column>
                        <el-table-column label="同期比率" align="center">
                            <el-table-column prop="tqActualRatio" label="实际功率" align="center"></el-table-column>
                            <el-table-column prop="tqUltraRatio" label="超短期预测" align="center"></el-table-column>
                            <el-table-column prop="tqShortRatio" label="短期预测" align="center"></el-table-column>
                        </el-table-column>
                        <el-table-column label="环比数据" align="center" v-if="dateType === 3">
                            <el-table-column prop="actualPowerSy" label="实际功率" align="center"></el-table-column>
                            <el-table-column prop="veryShortTermForecastSy" label="超短期预测" align="center"></el-table-column>
                            <el-table-column prop="shortTermForecastSy" label="短期预测" align="center"></el-table-column>
                        </el-table-column>
                        <el-table-column label="环比比率" align="center" v-if="dateType === 3">
                            <el-table-column prop="hbActualRatio" label="实际功率" align="center"></el-table-column>
                            <el-table-column prop="hbUltraRatio" label="超短期预测" align="center"></el-table-column>
                            <el-table-column prop="hbShortRatio" label="短期预测" align="center"></el-table-column>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="main_table"  v-show="title === '风速预测' || title === '辐照度预测'">
                    <el-table :data="tableData" ref="report-table_wind" border style="width: 100%">
                        <el-table-column prop="dataTime" label="时间" align="center" width="160"></el-table-column>
                        <el-table-column label="当期数据" align="center">
                            <el-table-column prop="actualWindSpeedDq" label="实际" align="center"></el-table-column>
                            <el-table-column prop="forecastWindSpeedDq" label="预测" align="center"></el-table-column>
                        </el-table-column>
                        <el-table-column label="同期数据" align="center">
                            <el-table-column prop="actualWindSpeedTq" label="实际" align="center"></el-table-column>
                            <el-table-column prop="forecastWindSpeedTq" label="预测" align="center"></el-table-column>
                        </el-table-column>
                        <el-table-column label="同期比率" align="center">
                            <el-table-column prop="actualwindDq" label="实际" align="center"></el-table-column>
                            <el-table-column prop="shortTermForecastDq" label="预测" align="center"></el-table-column>
                        </el-table-column>
                        <el-table-column label="环比数据" align="center" v-if="dateType === 3">
                            <el-table-column prop="actualWindSpeedSy" label="实际" align="center"></el-table-column>
                            <el-table-column prop="forecastWindSpeedSy" label="预测" align="center"></el-table-column>
                        </el-table-column>
                        <el-table-column label="环比比率" align="center" v-if="dateType === 3">
                            <el-table-column prop="hbactualwindDq" label="实际" align="center"></el-table-column>
                            <el-table-column prop="hbshortTermForecastDq" label="预测" align="center"></el-table-column>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </div>
        <!-- <span slot="footer" class="dialog-footer">
            <el-button type="primary">确 定</el-button>
            <el-button @click="dialogVisible = false">取 消</el-button>
        </span> -->
    </el-dialog>
</template>

<script>
import  * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'
import  * as XLSXD from 'xlsx-js-style'
import { apiGetglobalPowerCharts,apiGetglobalPowerTable,apiGetglobalWindSpeedCharts,apiGetglobalWindSpeedTable,
apiGetglobalIrradianceCharts, apiGetglobalIrradianceTable } from '../../api/api'
export default {
    props:{
        from: {
            type: String,
            default: () => {
                return '';
            },
        },
        ExceedTimeList: {
            type: Array,
            default: () => {
                return [];
            },
        },
        stationData:{
            type: Array,
            default: () => {
                return [];
            },
        }
    },
    data() {
        return {
            title: '',
            dialogVisible: false,
            windTurbines: null,
            windTurbinesVal: null,
            tableData: [],
            chooseExceedTimeFv: 0,
            pickerTime: [],
            dateType: 1,
            loading: false,
            global:false, //全域数据标识
            windShow: false
        }
    },
    created() {
    },
    methods:{
        init(name) {
            if (name.indexOf('功率预测') !== -1) {
                if (this.stationData[0].no !== -1) {
                    let obj = {
                        stationName: '全域数据',
                        no: -1,
                        itemVal: 0
                    }
                    this.stationData.unshift(obj)
                    this.title = '功率预测'
                }
            } else {
                this.stationData.forEach((item, index) =>{
                    if (item.no === -1) {
                        this.stationData.shift()
                    }
                })
                if (this.windShow) {
                    this.title = '风速预测'
                } else {
                    this.title = '辐照度预测'
                }
            }
            this.windTurbines = this.stationData[0].no
            this.windTurbinesVal = this.stationData[0].itemVal
        },
        closeDialog() {
            this.$emit('notReload', true)
            this.dialogVisible = false
        },
        seachData() {
            this.global = false
            this.loading = true
            if (this.title === '功率预测') {
                this.getChartsData()
                this.getTableData()
            } else {
                this.getwindChartsData()
                this.getwindTableData()
            }
        },
        allStationData() {
            this.loading = true
            this.global = true
            this.getChartsData()
            this.getTableData()
        },
        chooseVal(val) {
            this.stationData.forEach(item => {
                if (item.no === val) {
                    this.windTurbinesVal = item.itemVal
                }
            })
        },
        changeTime(val) {
            if (val) {
                let timeC = new Date(val[1]).getTime() - new Date(val[0]).getTime()
                if (timeC <= 10*86400000) { //十天内
                    this.dateType = 1
                } else if(timeC > 10*86400000 && timeC <= 2592000000) { // 大于十天小于30天
                    this.dateType = 2
                } else {
                    this.dateType = 3
                }
            }
        },
        //转换时间
        getPowerTime(date){
            var y = date.getFullYear();  
            var m = date.getMonth() + 1;  
            m = m < 10 ? ('0' + m) : m;  
            var d = date.getDate();  
            d = d < 10 ? ('0' + d) : d;  
            var h = date.getHours();  
            h=h < 10 ? ('0' + h) : h;  
            var minute = date.getMinutes();  
            minute = minute < 10 ? ('0' + minute) : minute;  
            // var second=date.getSeconds();  
            // second=second < 10 ? ('0' + second) : second;  
            // return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second; 
            let timeF = ''
            timeF = y + '-' + m + '-' + d+' '+h+':'+minute 
            return this.$utils.changePowerPickDate(timeF)
        },
        
        // 全域功率预测echarts
        getChartsData() {
            let pickStartTime =this.getPowerTime(this.pickerTime[0])
            let pickEndTime =this.getPowerTime(this.pickerTime[1])
            let type
            if (new Date(pickEndTime).getTime() - new Date(pickStartTime).getTime() <= 10*86400000) {
                type = 1
            } else {
                type = 2
            }
            let params = {
                beginDataTime: pickStartTime,
                endDataTime: pickEndTime,
                leadTime: this.chooseExceedTimeFv,
                stationNumber: !this.global ? this.windTurbines : -1,
                itemVal: this.windTurbinesVal,
                timeType: type
            }
            apiGetglobalPowerCharts(params).then(datas =>{
                if (datas && datas.data) {
                    let xAxis = []
                    let series = []
                    let legend = []
                    if (datas.data.dateList.length > 0) {
                        if (type === 2) {
                            datas.data.dateList.forEach(item =>{
                                xAxis.push(item.substring(0, item.indexOf(' ')))
                            })
                        } else {
                            xAxis = datas.data.dateList
                        }
                    }
                    if (datas.data.dataFormatList.length > 0) {
                        datas.data.dataFormatList.forEach(iten =>{
                            legend.push(iten.name)
                            let seriesObj = {
                                name: iten.name,
                                type: 'line',
                                data: iten.data.map(it => {
                                    return this.$utils.isHasNum(it)
                                }),
                                symbol: 'none'
                            }
                            series.push(seriesObj)
                        })
                    }
                    this.getglobalLine('centerCharts', '功率', xAxis, legend, series)
                }
            })
        },
        // 全域风速预测echarts
        getwindChartsData() {
            let pickStartTime =this.getPowerTime(this.pickerTime[0])
            let pickEndTime =this.getPowerTime(this.pickerTime[1])
            let type
            if (new Date(pickEndTime).getTime() - new Date(pickStartTime).getTime() <= 10*86400000) {
                type = 1
            } else {
                type = 2
            }
            let that = this
            let params = {
                beginDataTime: pickStartTime,
                endDataTime: pickEndTime,
                stationNumber: !this.global ? this.windTurbines : -1,
                timeType: type
            }
            if (that.windShow) {
                apiGetglobalWindSpeedCharts(params).then(datas =>{
                    that.getwindSunData(datas, type)
                })
            } else {
                apiGetglobalIrradianceCharts(params).then(datas =>{
                    that.getwindSunData(datas, type)
                })
            }
        },
        // 修改风速和辐照度数据
        getwindSunData(datas, type) {
            if (datas && datas.data) {
                let xAxis = []
                let series = []
                let legend = []
                if (datas.data.dateList.length > 0) {
                    if (type === 2) {
                        datas.data.dateList.forEach(item =>{
                            xAxis.push(item.substring(0, item.indexOf(' ')))
                        })
                    } else {
                        xAxis = datas.data.dateList
                    }
                }
                if (datas.data.dataFormatList.length > 0) {
                    datas.data.dataFormatList.forEach(iten =>{
                        legend.push(iten.name)
                        let seriesObj = {
                            name: iten.name,
                            type: 'line',
                            data: iten.data.map(it => {
                                return this.$utils.isHasNum(it)
                            }),
                            symbol: 'none'
                        }
                        series.push(seriesObj)
                    })
                }
                this.getglobalLine('centerCharts', this.windShow ? '风速' : '辐照度', xAxis, legend, series)
            }
        },
        getglobalLine(name, title, xAxis, legend, series) {
            let yxname = title === '功率' ? '兆瓦(Mw)' : title === '风速' ? 'm/s' : 'W/㎡'
            let option = {
                title: {
                    text: title
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    right: '20',
                    data: legend
                },
                grid: {
                    left: '5%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: xAxis
                },
                yAxis: {
                    type: 'value',
                    name: yxname
                },
                series: series
            };
            if (this.from === 'index') {
                option.backgroundColor = ''
            }
            // 基于准备好的dom，初始化echarts实例
            let dom = document.getElementById(name);
            dom.removeAttribute("_echarts_instance_")
            let myChart = this.$echarts.init(dom);
            myChart.setOption(option);
            window.addEventListener("resize", function () {
                myChart.resize()
            })
        },
        // 全域功率预测table
        getTableData() {
            let pickStartTime =this.getPowerTime(this.pickerTime[0])
            let pickEndTime =this.getPowerTime(this.pickerTime[1])
            this.tableData = []
            let params = {
                beginDataTime: pickStartTime,
                endDataTime: pickEndTime,
                leadTime: this.chooseExceedTimeFv,
                stationNumber: !this.global ? this.windTurbines : -1,
                itemVal: this.windTurbinesVal,
                timeType: this.dateType
            }
            apiGetglobalPowerTable(params).then(datas =>{
                if (datas && datas.data) {
                    this.loading = false
                    if (datas.data.dataFormatList) {
                        datas.data.dataFormatList.forEach(item =>{
                            for(let i in item) {
                                if (i !== 'dataTime') {
                                    if (item[i] !== null && item[i] !== 'NaN') {
                                        item[i] = item[i].toFixed(3)
                                    } else {
                                        item[i] = '-'
                                    }
                                }
                            }
                            //同期实际比率
                            item.tqActualRatio = this.$utils.ratioCalculation(item.actualPowerDq, item.actualPowerTq)
                            //同期超短期比率
                            item.tqUltraRatio = this.$utils.ratioCalculation(item.veryShortTermForecastDq, item.veryShortTermForecastTq)
                            //同期短期比率
                            item.tqShortRatio = this.$utils.ratioCalculation(item.shortTermForecastDq, item.shortTermForecastTq)
                            //环比实际比率
                            item.hbActualRatio = this.$utils.ratioCalculation(item.actualPowerDq, item.actualPowerSy)
                            //环比超短期比率
                            item.hbUltraRatio = this.$utils.ratioCalculation(item.veryShortTermForecastDq, item.veryShortTermForecastSy)
                            //环比短期比率
                            item.hbShortRatio = this.$utils.ratioCalculation(item.shortTermForecastDq, item.shortTermForecastSy)
                        })
                        this.tableData = datas.data.dataFormatList
                    }
                }
            })
        },
        // 全域风速预测table
        getwindTableData() {
            let pickStartTime =this.getPowerTime(this.pickerTime[0])
            let pickEndTime =this.getPowerTime(this.pickerTime[1])
            let that = this
            that.tableData = []
            let params = {
                beginDataTime: pickStartTime,
                endDataTime: pickEndTime,
                stationNumber: !this.global ? this.windTurbines : -1,
                timeType: this.dateType
            }
            if (that.windShow) {
                apiGetglobalWindSpeedTable(params).then(datas =>{
                    that.handleWindsunData(datas)
                })
            } else {
                apiGetglobalIrradianceTable(params).then(datas =>{
                    that.handleWindsunData(datas)
                })
            }
        },
        handleWindsunData(datas) {
            if (datas && datas.data) {
                this.loading = false
                if (datas.data.dataFormatList) {
                    datas.data.dataFormatList.forEach(item =>{
                        for(let i in item) {
                            if (i !== 'dataTime') {
                                item[i] = this.$utils.isHasNum(item[i])
                            }
                        }
                        //同期实际比率
                        item.actualwindDq = this.$utils.ratioCalculation(item.actualWindSpeedDq, item.actualWindSpeedTq)
                        //同期预测比率
                        item.shortTermForecastDq = this.$utils.ratioCalculation(item.forecastWindSpeedDq, item.forecastWindSpeedTq)
                        //环比实际比率
                        item.hbactualwindDq = this.$utils.ratioCalculation(item.actualWindSpeedDq, item.actualWindSpeedSy)
                        //环比预测比率
                        item.hbshortTermForecastDq = this.$utils.ratioCalculation(item.forecastWindSpeedDq, item.forecastWindSpeedSy)
                    })
                    this.tableData = datas.data.dataFormatList
                }
            }
        },
        exportExcel() {
            let $e = null
            if (this.title === '功率预测') {
                $e = this.$refs['report-table_power'].$el
            } else {
                $e = this.$refs['report-table_wind'].$el
            }
            try {
                let $table = $e.querySelector('.el-table__fixed')
                if(!$table) {
                    $table = $e
                }
                const wb = XLSX.utils.table_to_book($table, {raw:true})
                if (wb && wb.Sheets.Sheet1) {
                    let as = ['!cols', '!fullref', '!merges', '!ref', '!rows']
                    let bs = []
                    if (this.title === '功率预测') {
                        bs = ['时间', '理论功率', '可用功率', '当期数据', '实际功率','超短期预测', '短期预测', '同期数据', '同期比率', '环比数据', '环比比率']
                    } else {
                        bs = ['时间', '当期数据', '实际','预测', '同期数据', '同期比率', '环比数据', '环比比率']
                    }
                    for(let i in wb.Sheets.Sheet1) {
                        if (as.indexOf(i)<0) {
                            if (bs.indexOf(wb.Sheets.Sheet1[i].v)>=0) {
                                wb.Sheets.Sheet1[i].s = {
                                    font:{
                                        name: '微软雅黑',
                                        sz: 11,
                                        bold: true,
                                        color: {rgb: 'ffffff'}
                                    },
                                    alignment: {
                                        horizontal: 'center',
                                        vertical: 'center'
                                    },
                                    fill:{fgColor: {rgb: '4f81bd'}}
                                }
                                if (i === 'A1') {
                                    wb.Sheets.Sheet1['!cols'].push({wch: 30})
                                } else if (i === 'B1') {
                                    wb.Sheets.Sheet1['!cols'].push({wch: 20})
                                } else {
                                    wb.Sheets.Sheet1['!cols'].push({wch: 15})
                                }
                            } else {
                                wb.Sheets.Sheet1[i].s = {
                                    font:{
                                        name: '微软雅黑',
                                        sz: 10,
                                        bold: false,
                                        color: {rgb: '000000'}
                                    },
                                    alignment: {
                                        horizontal: 'center',
                                        vertical: 'center'
                                    },
                                    // fill:{fgColor: {rgb: '4f81bd'}}
                                }
                            }
                        }
                    }
                }

                const wbout = XLSXD.write(wb, {bookType: 'xlsx', bookSST:true, type: 'array'})
                saveAs(
                    new Blob([wbout],{type: 'application/octet-stream'}),
                    `${this.title}.xlsx`,
                )
            } catch (e) {
                if (typeof console !== 'undefined') console.error(e)
            }
        }
    }
}
</script>

<style lang="less">
@import '../SecondaryPageStyle/globalblackStyle.less';
@import '../SecondaryPageStyle/globalwhiteStyle.less';
</style>