<template>
    <el-dialog custom-class="windLifeDialog" :title="title" v-model="dialogVisible" width="90%"
        :close-on-click-modal="false" @close="closeDialog">
        <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="dateVal" 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>
                    <!-- <div class="exceed">
                        <span style="margin-top: 3px;">间隔：</span>
                        <el-select class="exTime" v-model="rJianStr" placeholder="请选择">
                            <el-option v-for="item in rJian" :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">
                <div class="main_charts">
                    <div id="centerCharts" class="chartsStyle"></div>
                </div>
                <div class="main_table warn-table">
                    <el-table :data="tableData" ref="report-table_day" 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 prop="veryShortTermForecastDq" label="累计" align="center">
                                </el-table-column>
                                <el-table-column prop="veryTimeVs" label="时刻" align="center"></el-table-column>
                            </el-table-column>
                            <el-table-column prop="shortTermForecastDq" label="短期预测" align="center">
                                <el-table-column prop="shortTermForecastDq" label="累计" align="center"></el-table-column>
                                <el-table-column prop="shortTimeVs" label="时刻" align="center"></el-table-column>
                            </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>
                </div>
            </div>
        </div>
    </el-dialog>
</template>

<script>
    import * as XLSX from 'xlsx'
    import {
        saveAs
    } from 'file-saver'
    import * as XLSXD from 'xlsx-js-style'
    import {
        apiGetdailyPowerComparisonChartData,
        apiGetdailyPowerComparisonTableData
    } from '../../../api/api'
    export default {
        props: {
            from: {
                type: String,
                default: () => {
                    return '';
                },
            },
            ExceedTimeList: {
                type: Array,
                default: () => {
                    return [];
                },
            },
            stationData: {
                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,
                rJianStr: 1,
                dateVal: [],
                loading: false,
                rJian: []
            }
        },
        created() {
            this.rJian = [{
                    label: '15分钟',
                    value: 1
                },
                {
                    label: '1小时',
                    value: 2
                }
            ]
        },
        methods: {
            closeDialog() {
                this.dialogVisible = false
            },
            seachData() {
                this.loading = true
                this.getChartsData()
                this.getTableData()

            },
            allStationData() {
                this.getChartsData()
                this.getTableData()
            },
            chooseVal(val) {
                this.stationData.forEach(item => {
                    if (item.no === val) {
                        this.windTurbinesVal = item.itemVal
                    }
                })
            },
            // 日发电量预测echarts
            getChartsData() {
                let that = this
                let pickStartTime = that.getElecTime(that.dateVal[0])
                let pickStartTime15 = that.getElecTime(that.dateVal[0], '15')
                let pickEndTime = that.getElecTime(that.dateVal[1])
                let pickEndTime15 = that.getElecTime(that.dateVal[1], '15')
                let params = {
                    beginDataTime: pickStartTime,
                    beginDataTime15: pickStartTime15,
                    endDataTime: pickEndTime,
                    endDataTime15: pickEndTime15,
                    leadTime: that.chooseExceedTimeFv,
                    stationNumber: that.windTurbines,
                    itemVal: that.windTurbinesVal,
                    // jg: that.rJianStr
                    jg: 1
                }
                apiGetdailyPowerComparisonChartData(params).then(datas => {
                    if (datas && datas.data) {
                        let xAxis = []
                        let series = []
                        let legend = []
                        if (datas.data.dateList.length > 0) {
                            // datas.data.dateList.forEach(item =>{
                            //     xAxis.push(item.substring(item.indexOf(' '), item.length))
                            // })
                            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 that.$utils.isHasNum(it)
                                    }),
                                    symbol: 'none'
                                }
                                series.push(seriesObj)
                            })
                        }
                        that.getglobalLine('centerCharts', xAxis, legend, series)
                    }
                })
            },
            getglobalLine(name, xAxis, legend, series) {
                let option = {
                    title: {
                        text: '电量'
                    },
                    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: '万千瓦时(Wkw/h)'
                    },
                    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);
                window.addEventListener("resize", function () {
                    myChart.resize()
                })
            },
            // 日发电量预测table
            getTableData() {
                let that = this
                let pickStartTime = that.getElecTime(that.dateVal[0])
                let pickStartTime15 = that.getElecTime(that.dateVal[0], '15')
                let pickEndTime = that.getElecTime(that.dateVal[1])
                let pickEndTime15 = that.getElecTime(that.dateVal[1], '15')
                that.tableData = []
                let params = {
                    beginDataTime: pickStartTime,
                    beginDataTime15: pickStartTime15,
                    endDataTime: pickEndTime,
                    endDataTime15: pickEndTime15,
                    leadTime: that.chooseExceedTimeFv,
                    stationNumber: that.windTurbines,
                    itemVal: that.windTurbinesVal,
                    // jg: that.rJianStr
                    jg: 1
                }
                apiGetdailyPowerComparisonTableData(params).then(datas => {
                    if (datas && datas.data) {
                        that.loading = false
                        if (datas.data.dataFormatList) {
                            datas.data.dataFormatList.forEach(item => {
                                for (let i in item) {
                                    if (i !== 'dataTime') {
                                        item[i] = that.$utils.isHasNum(item[i])
                                    }
                                }
                                //同期实际比率
                                item.tqActualRatio = that.$utils.ratioCalculation(item.actualPowerDq,
                                    item.actualPowerTq)
                                //同期超短期比率
                                item.tqUltraRatio = that.$utils.ratioCalculation(item
                                    .veryShortTermForecastDq, item.veryShortTermForecastTq)
                                //同期短期比率
                                item.tqShortRatio = that.$utils.ratioCalculation(item
                                    .shortTermForecastDq, item.shortTermForecastTq)
                            })
                            that.tableData = datas.data.dataFormatList

                            for (let i = 0; i < that.tableData.length; i++) {
                                let item = that.tableData[i]
                                let items = that.tableData[i + 1]
                                if (i === 0) {
                                    item.veryTimeVs = item.veryShortTermForecastDq
                                    item.shortTimeVs = item.shortTermForecastDq
                                    if (item.veryShortTermForecastDq !== '-' && items
                                        .veryShortTermForecastDq !== '-') {
                                        items.veryTimeVs = Number(Number(items.veryShortTermForecastDq) -
                                            Number(item.veryShortTermForecastDq)).toFixed(2)
                                    } else {
                                        items.veryTimeVs = '-'
                                    }
                                    if (item.shortTermForecastDq !== '-' && items.shortTermForecastDq !== '-') {
                                        items.shortTimeVs = Number(Number(items.shortTermForecastDq) - Number(
                                            item.shortTermForecastDq)).toFixed(2)
                                    } else {
                                        items.shortTimeVs = '-'
                                    }
                                } else {
                                    if (items) {
                                        if (item.veryShortTermForecastDq !== '-' && items
                                            .veryShortTermForecastDq !== '-') {
                                            items.veryTimeVs = Number(Number(items.veryShortTermForecastDq) -
                                                Number(item.veryShortTermForecastDq)).toFixed(2)
                                        } else {
                                            items.veryTimeVs = '-'
                                        }
                                        if (item.shortTermForecastDq !== '-' && items.shortTermForecastDq !==
                                            '-') {
                                            items.shortTimeVs = Number(Number(items.shortTermForecastDq) -
                                                Number(item.shortTermForecastDq)).toFixed(2)
                                        } else {
                                            items.shortTimeVs = '-'
                                        }
                                    }
                                    // else {
                                    //     items.veryTimeVs = '-'
                                    //     items.shortTimeVs = '-'
                                    // }
                                }
                            }
                        }
                    }
                })
            },
            //转换时间
            getElecTime(date, type) {
                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
                if (type !== '15') {
                    return this.$utils.changeElectricPickDate(timeF) + ':00'
                } else {
                    return this.$utils.changePowerPickDate(timeF) + ':00'
                }
            },
            exportExcel() {
                let $e = this.$refs['report-table_day'].$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 = ['时间', '理论电量', '当期数据', '可用电量', '实际电量', '超短期预测', '短期预测', '同期数据', '同期比率', '环比数据', '环比比率',
                            '累计', '时刻'
                        ]
                        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">
    .globalDiaMain {
        .main_top {
            .main_top_left {
                .exceed {
                    .el-date-editor {
                        .el-input__prefix {
                            margin-left: 5px !important;
                        }
                    }
                }
            }
        }
    }

    .themeDark {

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

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