<template>
    <el-dialog class="windLifeDialog" :title="title" v-model="dialogVisible" :fullscreen="true"
        :close-on-click-modal="false">
        <div class="globalDiaMain" :class="!theme ? 'themeDa' : 'themeLi'">
            <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 style="width: 130px" 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" style="margin-top: 20px">
                    <el-table :data="tableData" ref="report-table" border show-summary :summary-method="getSummaries" max-height="45vh" style="width: 100%"
                        :header-cell-style="{
                        padding: '4px',
                        fontSize: '16px',
                        fontWeight: bold,
                        border: '0.5px solid rgba(0,0,0,.5) !important',
                        }">
                        <el-table-column prop="dataTime" label="时间" align="center" width="160"></el-table-column>
                        <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 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();
            },
            getSummaries(datas) {
                const {columns, data} = datas
                const sums = [];
                columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '合计';
                    return;
                }
                const values = data.map(item => Number(item[column.property]));
                if (!values.every(value => isNaN(value))) {
                    if (index === 1 || index === 2) {
                        sums[index] = values.reduce((prev, curr) => {
                            const value = Number(curr);
                            if (!isNaN(value)) {
                                return prev + curr;
                            } else {
                                return prev;
                            }
                        }, 0) / values.length;
                        sums[index] = sums[index].toFixed(2) + ' (平均值)';
                    } else {
                        sums[index] = values.reduce((prev, curr) => {
                            const value = Number(curr);
                            if (!isNaN(value)) {
                                return prev + curr;
                            } else {
                                return prev;
                            }
                        }, 0);
                        sums[index] = sums[index].toFixed(2)
                    }
                } else {
                    sums[index] = '-';
                }
                });

                return sums;
            },
            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 (name === "功率") {
                        if (datas.data.dataFormatList.length > 0) {
                            let powerArr = ["理论", "可用", "AGC", "超短期", "短期", "实际"]
                            powerArr.forEach(it =>{
                                datas.data.dataFormatList.forEach((iten) => {
                                    if (it === iten.name) {
                                        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", name, xAxis, legend, series);
                    } else {
                        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("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">
.el-overlay {
        .el-overlay-dialog {
            .windLifeDialog {
                .el-dialog__header {
                    .el-dialog__title {
                        color: #fff !important;
                    }
                }

                .el-dialog__body {
                    padding: 10px 20px;

                    .globalDiaMain {
                        .main_top {
                            display: flex;
                            justify-content: space-between;

                            .main_top_left {
                                display: flex;

                                .exceed {
                                    span {
                                        font-size: 14px;
                                        margin-left: 10px;
                                    }

                                    display: flex;
                                    margin-right: 20px;

                                    .el-select,
                                    .el-select__wrapper {
                                        height: 32px;
                                    }

                                    .el-date-editor {
                                        height: 32px;

                                        .el-input__icon,
                                        .el-range-separator {
                                            line-height: 30px;
                                        }
                                    }

                                    .select-trigger {
                                        .el-input {
                                            .el-input__wrapper {
                                                height: 30px;
                                            }
                                        }

                                        .el-input__suffix {
                                            .el-input__icon {
                                                line-height: 30px;
                                            }
                                        }
                                    }
                                }
                            }

                            .el-button {
                                height: 30px;
                                padding: 0 20px;
                                line-height: 5px;
                            }
                        }

                        .main_charts {
                            margin-top: 20px;

                            .chartsStyle {
                                height: 300px;
                                width: 100%;
                            }
                        }

                        .main_table {
                            margin: 20px 0;

                            .el-table {
                                .el-table__body-wrapper {
                                    height: 335px !important;
                                    overflow-y: auto;
                                }
                            }
                        }
                    }

                    .themeDa {
                        .main_top {
                            .main_top_left {

                                .exceed {
                                    .exceedName {
                                        color: #fff;
                                        margin: 3px 0 0 5px;
                                    }
                                }
                            }
                        }
                    }

                    .themeLi {
                        .main_top {
                            .main_top_left {

                                .exceed {
                                    .exceedName {
                                        color: #000;
                                        margin: 3px 0 0 5px;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    // .themeDa {
    //     .main_top {
    //         .main_top_left {
    //             display: flex;
    //             margin-bottom: 10px;
    //             .exceed {
    //                 color: #fff;
    //             }
    //         }
    //     }
    // }

    // .themeLi {
    //     .main_top {
    //         .main_top_left {
    //             display: flex;
    //             margin-bottom: 10px;
    //             .exceed {
    //                 color: #000;
    //             }
    //         }
    //     }
    // }
</style>