<template>
    <div class="optimizationSuggestions">
        <div class="main_top">
            <div class="form-wrapper">
                <div class="station">
                    场站：
                    <el-select v-model="reportStation" placeholder="选择场站">
                        <el-option v-for="item in stationList" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </div>
                <div class="station">
                    机组：
                    <el-select v-model="windStation" placeholder="选择机组" @change="changeWt">
                        <el-option v-for="item in windList" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </div>
                <div class="station">
                    报告月份
                    <el-date-picker style="width: 120px" v-model="reportParamDate" type="month" value-format="YYYY-MM"
                        placeholder="请选择" />
                </div>
                <div class="but">
                    <el-button type="primary" @click="handleReportOp">查询</el-button>
                    <el-button style="width: 100px" type="danger" @click="exportPDFop" :loading="loading">导出 PDF
                    </el-button>
                </div>
            </div>
        </div>
        <div class="infoBox">
            <div id="pdfDom" ref="pdfContent" :style="!theme ? 'background-color: #040c0b' : 'background-color: #fff'">
                <h2 style="
            font-weight: bolder;
            text-align: center;
            margin-bottom: 20px;
            text-align: center;
          " :style="!theme ? 'color: #fff' : 'color: #000'">
                    {{ OperationName }}
                </h2>
                <!-- 单机运行指标性能分析 -->
                <h3 style="
            text-indent: 2em;
            font-weight: bolder;
            margin-bottom: 10px;
            margin-top: 10px;
          " :style="!theme ? 'color: #fff' : 'color: #000'">
                    单机运行指标性能分析
                </h3>
                <div class="warn-table">
                    <el-table class="toolSty" :data="jjyxList" border style="width: 100%; margin: 10px 0" stripe
                        :header-cell-style="{
                        padding: '4px',
                        fontSize: '12px',
                        fontWeight: bold,
                        border: '0.5px solid rgba(0,0,0,.5) !important',
                        }" :cell-style="{
                        height: '40px',
                        padding: '3px',
                        fontSize: '12px',
                        'border-top': '0px solid rgba(0,0,0,.5)',
                        'border-bottom': '1px solid rgba(0,0,0,.5)',
                        'border-right': '1px solid rgba(0,0,0,.5)',
                        }">
                        <el-table-column v-for="(item, index) in jjyxTableColumn" :key="index" :label="item.name"
                            :width="item.width" align="center">
                            <template #default="scope">
                                <span>
                                    {{ scope.row[item.code] ? scope.row[item.code] : "-" }}
                                </span>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>

                <!-- 本月运行情况总结 -->
                <h3 style="
                text-indent: 2em;
                font-weight: bolder;
                margin-bottom: 10px;
                margin-top: 10px;
            " :style="!theme ? 'color: #fff' : 'color: #000'">
                    本月运行情况总结：
                </h3>
                <p style="font-size: 16px;font-weight: bolder;margin: 10px 0 10px 40px"
                    :style="!theme ? 'color: #fff' : 'color: #000'">{{operationStatus}}</p>

                <p style="font-size: 16px;font-weight: bolder;margin: 10px 0 10px 40px"
                    :style="!theme ? 'color: #fff' : 'color: #000'">{{operationStatus2}}</p>

                <div id="powerAndspeed" style="width:100%;height:500px"></div>
            </div>
        </div>
    </div>
</template>

<script>
    import html2canvas from 'html2canvas';
    import jsPDF from 'jspdf';
    import dayjs from "dayjs";
    import {
        getWpList,
        getWtList,
        apiGeWarningeconreportReport
    } from "@/api/zhbj";
    import jsonData from "./dataJson.json";
    export default {
        name: "yhjyReport",
        data() {
            return {
                stationList: [],
                windList: [],
                reportStation: "",
                windStation: "",
                windStationName: "",
                OperationName: "经济运行分析报告",
                jjyxTableColumn: jsonData.jjyxTableColumn,
                jjyxList: [],
                operationStatus: "",
                operationStatus2: "",
                loading: false,
                reportParamDate: dayjs()
                    .subtract(1, "month")
                    .startOf("month")
                    .format("YYYY-MM"),
            };
        },

        created() {
            this.theme = this.$store.state.theme;
        },

        mounted() {
            this.funGetStation();
        },

        methods: {
            changeWt(value) {
                this.windList.forEach(it => {
                    if (value === it.id) {
                        this.windStationName = it.name
                    }
                })
            },
            /**场站 */
            funGetStation() {
                let that = this;
                // this.renderReportPage({
                //     data: jsonData.data
                // });
                that.stationList = [];
                that.windStation = ""
                getWpList().then((res) => {
                    if (res) {
                        that.stationList = res.data;
                        if (that.stationList.length) {
                            that.reportStation = that.stationList[0].id;
                            that.funGetWind(that.reportStation);
                        }
                    }
                });
            },
            funGetWind(wpId) {
                let that = this;
                that.windList = []
                that.windStation = ""
                getWtList({
                    wpId: wpId
                }).then((res) => {
                    if (res) {
                        that.windList = res.data.data;
                        if (that.windList.length) {
                            that.windStation = that.windList[0].id;
                            that.windStationName = that.windList[0].name;
                            that.handleReportOp();
                        }
                    }
                });
            },
            async exportPDFop() {
                this.loading = true;
                try {
                    // 获取要转换为PDF的内容
                    const element = this.$refs.pdfContent;

                    // 保存当前滚动位置
                    const originalScrollTop = window.scrollY;

                    // 将页面滚动到顶部
                    window.scrollTo(0, 0);

                    // 设置元素的高度为内容的实际高度
                    const originalHeight = element.style.height;
                    const originalOverflow = element.style.overflow;
                    if (originalHeight) {
                        element.style.height = `${element.scrollHeight}px`;
                    }
                    if (originalOverflow) {
                        element.style.overflow = 'hidden';
                    }

                    // 使用html2canvas将HTML内容转换为canvas
                    const canvas = await html2canvas(element, {
                        scale: 2, // 提高分辨率
                        logging: true, // 开启日志记录
                        useCORS: true // 处理跨域图片
                    });

                    // 恢复原来的样式
                    element.style.height = originalHeight || '';
                    element.style.overflow = originalOverflow || '';

                    // 恢复滚动位置
                    window.scrollTo(0, originalScrollTop);

                    // 将canvas转换为Data URL
                    const imgData = canvas.toDataURL('image/png');

                    // 创建一个新的jsPDF实例
                    const doc = new jsPDF('p', 'mm', 'a4');

                    // 计算图片在PDF中的位置和大小
                    const imgProps = doc.getImageProperties(imgData);
                    const pdfWidth = doc.internal.pageSize.getWidth();
                    const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;

                    // 计算每页的高度
                    const pageHeight = doc.internal.pageSize.getHeight();
                    let heightLeft = pdfHeight;

                    // 添加第一页
                    doc.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);

                    // 添加后续页面
                    while (heightLeft > pageHeight) {
                        heightLeft -= pageHeight;
                        doc.addPage();
                        doc.addImage(imgData, 'PNG', 0, -pdfHeight + heightLeft, pdfWidth, pdfHeight);
                    }

                    // 保存PDF文件
                    doc.save('经济运行分析报告.pdf');
                    this.loading = false;
                } catch (error) {
                    console.error('Error generating PDF:', error);
                    this.loading = false
                }
            },
            handleReportOp() {
                if (this.reportParamDate) {
                    this.OperationName = "";
                    this.jjyxList = [];

                    let params = {
                        reportParamDate: this.reportParamDate,
                        windStation: this.windStation
                    }
                    apiGeWarningeconreportReport(params).then((res) => {
                            this.renderReportPage(res);
                        })
                        .catch(() => {
                            this.renderReportPage({
                                data: jsonData.data,
                            });
                        });
                }
            },

            renderReportPage(res) {
                let date = this.reportParamDate.split("-");
                this.OperationName =
                    date[0] +
                    "年" +
                    date[1] +
                    "月" +
                    this.windStationName +
                    "指标性能分析及运行情况报告";
                this.jjyxList = res.data.lb;
                this.operationStatus = res.data.wz1
                this.operationStatus2 = res.data.wz2

                let tbdata = res.data.tb
                let xAxis = []
                let servesBar = []
                let servesLine = []
                tbdata.forEach((it, index) => {
                    xAxis.push((dayjs(it.recordDate).format('D')) + '日')
                    servesBar.push(it.rfdl)
                    servesLine.push(it.pjfs)
                })
                this.getcharts(xAxis, servesBar, servesLine)
            },

            getcharts(xAxis, servesBar, servesLine) {
                let option = {
                    tooltip: {
                        trigger: 'axis',
                    },
                    legend: {
                        textStyle: {
                            color: '#fff'
                        },
                        data: ['发电量(万kwh)', '风速(m/s)']
                    },
                    xAxis: [{
                        type: 'category',
                        data: xAxis,
                        axisTick: {
                            show: true, // 显示刻度线
                            lineStyle: {
                                color: '#fff' // 设置刻度线颜色为红色
                            }
                        },
                        axisLine: {
                            lineStyle: {
                                color: '#fff' // 设置轴线颜色为蓝色（可选）
                            }
                        },
                        axisPointer: {
                            type: 'shadow'
                        }
                    }],
                    yAxis: [{
                            type: 'value',
                            name: '发电量(万kwh)',
                            min: 0,
                            axisTick: {
                                show: true, // 显示刻度线
                                lineStyle: {
                                    color: '#fff' // 设置y轴刻度线颜色为红色
                                }
                            },
                            axisLine: {
                                show: true, // 如果需要显示轴线
                                lineStyle: {
                                    color: '#fff' // 设置y轴轴线颜色为蓝色（可选）
                                }
                            },
                            splitLine: {
                                show: false, // 如果需要显示分割线
                                lineStyle: {
                                    color: ['#333'] // 设置分割线颜色（可选）
                                }
                            }
                        },
                        {
                            type: 'value',
                            name: '风速(m/s)',
                            min: 0,
                            axisTick: {
                                show: true, // 显示刻度线
                                lineStyle: {
                                    color: '#fff' // 设置y轴刻度线颜色为红色
                                }
                            },
                            axisLine: {
                                show: true, // 如果需要显示轴线
                                lineStyle: {
                                    color: '#fff' // 设置y轴轴线颜色为蓝色（可选）
                                }
                            },
                            splitLine: {
                                show: false, // 如果需要显示分割线
                                lineStyle: {
                                    color: ['#333'] // 设置分割线颜色（可选）
                                }
                            }
                        }
                    ],
                    series: [{
                            name: '发电量(万kwh)',
                            type: 'bar',
                            data: servesBar
                        },
                        {
                            name: '风速(m/s)',
                            type: 'line',
                            yAxisIndex: 1,
                            data: servesLine
                        }
                    ]
                };
                // 基于准备好的dom，初始化echarts实例
                let dom = document.getElementById('powerAndspeed');
                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();
                });
            },
        },
    };
</script>

<style lang="less" scoped>
    .optimizationSuggestions {
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
        align-content: center;

        .main_top {
            height: 40px;
            display: flex;
            align-items: center;

            .form-wrapper {
                display: flex;
                flex-direction: row;
                align-items: center;
                margin: 10px 0 10px 20px;

                .station {
                    display: flex;
                    flex-direction: row;
                    align-items: center;
                    font-size: 14px;
                    font-family: Microsoft YaHei;
                    font-weight: 400;
                    color: #b3b3b3;
                    margin-right: 10px;
                }

                .search-input {
                    margin-left: 10px;
                }

                .but {
                    display: flex;
                    flex-direction: row;
                    align-content: center;
                    margin-left: 20px;
                }

                .buttons {
                    background-color: rgba(5, 187, 76, 0.2);
                    border: 1px solid #3b6c53;
                    color: #b3b3b3;
                    font-size: 14px;

                    &:hover {
                        background-color: rgba(5, 187, 76, 0.5);
                        color: #ffffff;
                    }
                }
            }
        }

        .infoBox {
            height: calc(100% - 80px);
            overflow: scroll;

            #pdfDom {
                margin: 20px;
            }
        }

        &.themeLight {
            .topPsty {
                color: #2778ff;
                background: #ffffff;
            }
        }

        &.themeDark {
            .topPsty {
                color: #1c99ff;
                background: #1e2126;
            }
        }
    }
</style>
<style lang="less">
    .el-overlay {
        .el-overlay-dialog {
            .reportDia {
                margin-top: 0 !important;
            }
        }
    }

    .reportDia {
        .repoerDateBox {
            width: calc(100% - 40px);
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 12px;
        }
    }
</style>