<template>
    <el-dialog custom-class="windLifeDialog" :title="title" v-model="dialogVisible" width="90%"
        :close-on-click-modal="false">
        <div class="globalDiaMain" :class="!theme ? 'themeDark' : 'themeLight'">
            <div class="main_top">
                <div class="main_top_left">
                    <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">
                        <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>
            <div v-loading="loading">
                <el-row class="main_charts">
                    <el-col :span="12">
                        <div id="centerCharts" class="chartsStyle"></div>
                    </el-col>
                    <el-col :span="12">
                        <div id="windCharts" class="chartsStyle"></div>
                    </el-col>
                </el-row>
                <div class="main_table warn-table">
                    <el-table :data="tableData" ref="report-table" border max-height="400px" 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>
        </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,
        apiGetglobalIrradianceCharts
    } from '../../../api/api'
    export default {
        props: {
            from: {
                type: String,
                default: () => {
                    return '';
                },
            },
            ExceedTimeList: {
                type: Array,
                default: () => {
                    return [];
                },
            },
            echartsTheme: {
                type: String,
                default: () => {
                    return '';
                },
            },
            theme: {
                type: Boolean,
                default: () => {
                    return false;
                },
            },
        },
        data() {
            return {
                title: '',
                dialogVisible: false,
                windTurbines: null,
                windTurbinesVal: null,
                tableData: [],
                chooseExceedTimeFv: 0,
                pickerTime: [],
                dateType: 1,
                stationData: {},
                loading: false,
                global: false //全域数据标识
            }
        },
        created() {},
        methods: {
            seachData() {
                this.global = false
                this.getChartsData()
                this.getTableData()
            },
            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
                    }
                    console.log(timeC)
                    console.log(this.dateType)
                }
            },
            //转换时间
            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;
                let timeF = ''
                timeF = y + '-' + m + '-' + d + ' ' + h + ':' + minute
                return this.$utils.changePowerPickDate(timeF)
            },
            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 that = this
                that.loading = true
                // 功率
                let params = {
                    beginDataTime: pickStartTime,
                    endDataTime: pickEndTime,
                    leadTime: that.chooseExceedTimeFv,
                    stationNumber: that.stationData.stationNumber,
                    // itemVal: that.stationData.itemVal,
                    itemVal: 0,
                    timeType: type
                }
                //风速
                //光伏
                let params1 = {
                    beginDataTime: pickStartTime,
                    endDataTime: pickEndTime,
                    stationNumber: that.stationData.stationNumber,
                    timeType: type
                }
                apiGetglobalPowerCharts(params).then(datas => {
                    that.commonFn(datas, type, '功率')
                })
                if (that.stationData.itemVal === "0") {
                    apiGetglobalWindSpeedCharts(params1).then(datas => {
                        that.commonFn(datas, type, '风速')
                    })
                } else {
                    apiGetglobalIrradianceCharts(params1).then(datas => {
                        that.commonFn(datas, type, '光伏')
                    })
                }
            },
            commonFn(datas, type, name) {
                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)
                        })
                    }
                    if (name === '功率') {
                        this.getglobalLine('centerCharts', name, xAxis, legend, series)
                    } else {
                        this.getglobalLine('windCharts', name, xAxis, legend, series)
                    }
                }
            },
            getglobalLine(name, title, xAxis, legend, series) {
                let Yname = 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: Yname
                    },
                    series: series
                };
                if (this.from === 'index') {
                    option.backgroundColor = ''
                }
                if (!this.theme) {
                    option.backgroundColor = ''
                }
                // 基于准备好的dom，初始化echarts实例
                let dom = document.getElementById(name);
                dom.removeAttribute("_echarts_instance_") ? dom.removeAttribute("_echarts_instance_") : ''
                let myChart = this.$echarts.init(dom, this.echartsTheme);
                myChart.setOption(option);
                myChart.on('mousemove', this.setTooltip('centerCharts', 'windCharts', 0))
                window.addEventListener("resize", function () {
                    myChart.resize()
                })
            },
            setTooltip(name1, name2, num) {
                const myChart1 = this.$echarts.init(document.getElementById(name1))
                const myChart2 = this.$echarts.init(document.getElementById(name2))
                this.$utils.setTooltip(myChart1, myChart2, num)
            },
            getTableData() {
                let pickStartTime = this.getPowerTime(this.pickerTime[0])
                let pickEndTime = this.getPowerTime(this.pickerTime[1])
                let params = {
                    beginDataTime: pickStartTime,
                    endDataTime: pickEndTime,
                    leadTime: this.chooseExceedTimeFv,
                    stationNumber: this.stationData.stationNumber,
                    itemVal: this.stationData.itemVal,
                    timeType: this.dateType
                }
                apiGetglobalPowerTable(params).then(datas => {
                    if (datas && datas.data) {
                        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.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
                            this.loading = false
                        }
                    }
                })
            },
            exportExcel() {
                try {
                    const $e = this.$refs['report-table'].$el
                    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 = ['时间', '理论功率', '可用功率', '当期数据', '实际功率', '超短期预测', '短期预测', '同期数据', '同期比率', '环比数据', '环比比率']
                        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">
    .themeDark {

        .main_top {
            .main_top_left {
                .exceed {
                    color: #fff;
                }
            }
        }
    }

    .themeLight {
        .main_top {
            .main_top_left {
                .exceed {
                    color: #000;
                }
            }
        }
    }
</style>