<template>
    <div class="pd10">
        <el-form :inline="true" class="demo-form-inline">

            <el-row>
                <el-col :span="24">
                    <el-form-item label="日期">
                        <div style="display: flex">
                            <el-select v-model="statisticalType" style="width: 180px; margin-right: 5px"
                                @change="timeChange">
                                <el-option label="年" value="01"></el-option>
                                <el-option label="月" value="02"></el-option>
                                <el-option label="日" value="03"></el-option>
                            </el-select>
                            <el-date-picker style="width: 180px" v-model="searchBeginTime"
                                v-if="statisticalType == '01'" type="year" value-format="yyyy-MM-dd"
                                @change="yearChange" placeholder="选择年"></el-date-picker>
                            <el-date-picker style="width:180px" v-if="statisticalType == '02'" value-format="yyyy-MM-dd"
                                v-model="searchBeginTime" @change="monthChange" type="month"
                                placeholder="选择日期"></el-date-picker>
                            <el-date-picker style="width:180px" v-if="statisticalType == '03'" value-format="yyyy-MM-dd"
                                v-model="searchBeginTime" @change="dateChange" type="date"
                                placeholder="选择日期"></el-date-picker>
                        </div>
                    </el-form-item>
                    <el-button size="small" type="primary" icon="el-icon-search" @click="
                        pageNum = 1;
                    pageListInit()">
                        查询
                    </el-button>
                    <el-button type="primary" class="ml10" icon="el-icon-search" @click="uploadGw()">上送网公司
                    </el-button>
                    <el-button type="primary" icon="el-icon-download" @click="exportEvent">导出</el-button>

                    <el-button type="primary" icon="" @click="relCal">重新计算</el-button>
                </el-col>


            </el-row>


        </el-form>

        <el-row>
            <el-col :span="24">
                <vxe-table :data="pageData" :height="height" border size="mini" ref="workOrderTable" style="width: 100%"
                    v-loading="isLoading" header-cell-class-name="table_header" @checkbox-all="selectAllChangeEvent"
                    @checkbox-change="handleSelectionChange">
                    <!--          <vxe-table-column key="checkboxs" type="checkbox" align="center" width="55"></vxe-table-column>-->

                    <template v-for="(item, index) in tableData">
                        <vxe-table-column align="center" :field="item.prop" :title="item.label" :key="index"
                            :min-width="item.width" :formatter="tableDateFilter">
                        </vxe-table-column>
                    </template>

                    <vxe-table-column key="uploadStatus" field="uploadStatus" title="状态" fixed="right" align="center"
                        width="100">
                        <template slot-scope="scope">
                            <el-tag type="primary" size="small" style="color: rgba(6,45,241,0.98); background: #ecf5ff"
                                v-if="scope.row.uploadStatus == 0">
                                未上送
                            </el-tag>
                            <el-tag type="primary" size="small" style="color: #34fc3e; background: #f0f9eb"
                                v-if="scope.row.uploadStatus == 1">
                                已上送
                            </el-tag>
                            <el-tag type="primary" size="small" style="color: #991717; background: #f4f4f5"
                                v-if="scope.row.uploadStatus == 2">
                                取消上送
                            </el-tag>
                            <el-tag type="primary" size="small"
                                style="color: rgba(236,143,21,0.92); background: #f4f4f5"
                                v-if="scope.row.uploadStatus == 3">
                                待重新上送
                            </el-tag>

                        </template>
                    </vxe-table-column>


                </vxe-table>
                <el-pagination background align="right" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" :current-page="pageNum" :page-sizes="[20, 30, 40, 50, 100]"
                    :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"
                    class="mt10"></el-pagination>
            </el-col>
        </el-row>


    </div>
</template>

<script>


import { dicData } from '@/assets/commjs/dictypeData'
import { getMainMonitorPage, uploadMainGw } from '@/api/pmsUpload/mainMonitor'
import { relcal } from '@/api/pmsUpload/commPoint'

export default {
    components: {},
    data() {
        return {
            vh: '',
            height: null,
            isLoading: false,
            form: {},
            dialogVisible: false,
            diaTitle: '',
            statisticalType: '03',
            searchBeginTime: '',
            searchEndTime: '',

            multipleSelection: [],


            tableData: [
                { prop: 'provinceOrgName', label: '所属省份', width: 180 },
                { prop: 'cityOrgName', label: '所属地市', width: 180 },
                { prop: 'maintOrgName', label: '运维单位', width: 180 },


                { prop: 'statisticalDate', label: '统计日期', width: 180 },
                { prop: 'statisticalType', label: '统计数据类型', width: 180 },

                { prop: 'monitorName', label: '监测点名称', width: 180 },
                { prop: 'monitorVoltageLevel', label: '监测点电压等级', width: 180 },
                { prop: 'monitorId', label: '监测点编码', width: 180 },
                { prop: 'monitorStatus', label: '监测点状态', width: 180 },


                { prop: 'substationName', label: '所属电站名称', width: 180 },
                { prop: 'busName', label: '监测母线名称', width: 180 },
                { prop: 'monitorObjTypeBig', label: '监测对象大类', width: 180 },
                { prop: 'monitorObjTypeSmall', label: '监测对象小类', width: 180 },
                { prop: 'monitorTag', label: '监测点标签', width: 180 },
                { prop: 'monitorObjName', label: '监测对象名称', width: 180 },

                { prop: 'minShortCapacity', label: '最小短路容量MVA', width: 180 },
                { prop: 'supplyEquipCapacity', label: '供电设备容量MVA', width: 180 },
                { prop: 'userProtocolCapacity', label: '用户协议容量MVA', width: 180 },
                {
                    prop: 'isMonitorOnline',
                    label: '监测点是否在线',
                    width: 100
                },
                { prop: 'isTerminalOnline', label: '监测终端是否在线', width: 180 },
                { prop: 'onlineMonitorNum', label: '在线监测点数量', width: 180 },

                { prop: 'runMonitorNum', label: '在运监测点数量', width: 180 },
                { prop: 'onlineMonitorRate', label: '监测点在线率', width: 180 },
                { prop: 'expectCollectNum', label: '应收采集数', width: 180 },
                { prop: 'actualCollectNum', label: '实收采集数', width: 180 },
                { prop: 'dataFullRate', label: '监测数据完整率', width: 180 },
                { prop: 'monitorOperateDate', label: '监测点投运日期', width: 180 },
                { prop: 'monitorStopDate', label: '监测点停运日期', width: 180 }
            ],
            pageData: [],

            objId: '',

            operateType: 0, //0.新增 1.修改
            rules: {},

            pageNum: 1,
            pageSize: 20,
            total: 0

        }
    },
    created() {

        let day = new Date()
        day.setDate(day.getDate() - 1)
        this.statisticalType = '03'
        this.searchBeginTime = this.$tools.formatDate(day, 'yyyy-MM-dd')
    },
    mounted() {
        this.pageListInit()
        this.setHeight()
        window.addEventListener('resize', this.setHeight)
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.setHeight)
    },
    methods: {
        setHeight() {
            this.height = window.sessionStorage.getItem('appheight') - 110
        },
        //获取主网运行指标统计数据
        pageListInit() {
            this.isLoading = true
            let param = {
                pageNum: this.pageNum,
                pageSize: this.pageSize,
                orgId: JSON.parse(window.sessionStorage.getItem('Info')).deptId,
                dataType: this.statisticalType,
                searchBeginTime: this.searchBeginTime
            }
            getMainMonitorPage(param).then(res => {
                this.total = res.data.total
                this.pageData = res.data.records
                this.isLoading = false
            })
        },

        getLastDayOfMonth(date) {
            // 创建一个新的日期对象，避免修改原始日期对象
            let lastDay = new Date(date)

            // 将日期设置为下个月的第一天，然后减去1毫秒（或1天）以获取当月的最后一天
            lastDay.setMonth(lastDay.getMonth() + 1, 0)

            // 返回最后一天的日期对象（或者只返回日期部分）
            return lastDay
        },

        getLastDayOfYear(date) {
            // 创建一个新的日期对象，设置为当年的12月31日
            let lastDay = new Date(date.getFullYear(), 11, 31)

            // 检查是否是闰年，如果是闰年且日期是2月29日之后的日期（理论上不可能，但为严谨性检查）
            if (lastDay.getMonth() !== 11) {
                // 这种情况理论上不会发生，但为了保险起见，重新设置为12月31日
                lastDay = new Date(date.getFullYear(), 11, 31)
            }

            // 返回最后一天的日期对象（或者只返回日期部分）
            return lastDay
        },

        relCal() {
            const queryDate = this.$tools.parseDate(this.searchBeginTime)
            let temData = []
            let date
            if (this.statisticalType == '01') {
                temData = ['r_upload_main_monitor_data_y']
                date = this.$tools.formatDate(this.getLastDayOfYear(queryDate), "yyyy-MM-dd")
            } else if (this.statisticalType == '02') {
                temData = ['r_upload_main_monitor_data_m']
                date = this.$tools.formatDate(this.getLastDayOfMonth(queryDate), "yyyy-MM-dd")
            } else if (this.statisticalType == '03') {
                temData = ['r_upload_main_monitor_data_d']
                date = this.searchBeginTime
            }
            this.$confirm('确认重算？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {

                let data = {
                    'fullChain': false,
                    'repair': false,
                    'beginTime': '',
                    'endTime': '',
                    'dataDate': date,
                    'tagNames': temData,
                    'idList': []
                }
                relcal(data).then(res => {


                })

                this.$message({
                    type: 'success',
                    message: '算法执行,请大约20s后刷新页面确认算法是否执行成功；'
                })

            })
        },

        //每页条数改变时触发 选择一页显示多少行
        handleSizeChange(val) {
            this.pageSize = val
            this.pageListInit()
        },
        //当前页改变时触发 跳转其他页
        handleCurrentChange(val) {
            this.pageNum = val
            this.pageListInit()
        },
        //重置
        Reset() {
            this.$refs.area.form.valueTitle = '全国'
            this.$refs.interval.intervald = 1
        },
        //导出
        exportEvent() {
            this.$refs.workOrderTable.exportData({
                filename: 'export', // 文件名字
                sheetName: 'Sheet1',
                type: 'xlsx', //导出文件类型 xlsx 和 csv
                useStyle: true,
                data: this.pageData
            })
        },


        handleClose() {
            this.resetForm('ruleForm')
            this.dialogVisible = false
        },


        //上报网公司按钮触发
        uploadGw() {
            let type
            if (this.statisticalType == '03') {
                type = '日'
            } else if (this.statisticalType == '02') {
                type = '月'
            } else {
                type = '年'
            }

            this.$confirm('是否确认上送' + type + '主网测点数据?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let data = {
                    dataType: this.statisticalType,
                    searchBeginTime: this.searchBeginTime
                }
                uploadMainGw(data).then(res => {
                    console.log(res)
                    if ((res.code == 'A0000')) {
                        this.$message({
                            type: 'success',
                            message: res.message
                        })
                    }
                    this.pageListInit()
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消上送'
                })
            })

        },


        handleSelectionChange(val) {
            this.multipleSelection = val.records
        },
        selectAllChangeEvent(val) {
            this.multipleSelection = val.records
        },

        tableDateFilter(row, column) {
            if (row.column.property == 'stationType') {
                if ('zf01' == row.row.stationType) {
                    return '变电站'
                }
            } else if (row.column.property == 'dataSource') {
                if ('01' == row.row.dataSource) {
                    return '监测数据'
                }
            } else {
                return row.row[row.column.property]
            }
        },


        timeChange() {
            let day = new Date()
            day.setDate(day.getDate() - 1)
            if (this.statisticalType == '01') {
                this.searchBeginTime = this.$tools.formatDate(day, 'yyyy-MM-dd').substring(0, 5) + '01-01'
                this.searchEndTime = this.searchBeginTime.substring(0, 5) + '12-31'
            } else if (this.statisticalType == '02') {
                this.searchBeginTime = this.$tools.formatDate(day, 'yyyy-MM-dd').substring(0, 8) + '01'
                this.searchEndTime =
                    this.$tools.formatDate(day, 'yyyy-MM-dd').substring(0, 8) +
                    this.getDaysInMonth(
                        this.searchBeginTime.substring(5, 7) - 0,
                        this.searchBeginTime.substring(0, 4) - 0
                    )
            } else {
                this.searchBeginTime = this.$tools.formatDate(day, 'yyyy-MM-dd')
                this.searchEndTime = this.searchBeginTime
            }
        },

        dateChange(e) {
            this.searchEndTime = this.searchBeginTime
        },
        monthChange(e) {
            this.searchEndTime = this.searchBeginTime.substring(0, 8) + this.getDaysInMonth(e.substring(5, 7), e.substring(0, 4))
        },
        yearChange(e) {
            this.searchEndTime = this.searchBeginTime.substring(0, 5) + '12-31'
        },
        getDaysInMonth(month, year) {
            return new Date(year, month, 0).getDate()
        }

    }
}
</script>
<style lang="less" scoped></style>
