<template>
    <div class="default-main">
        <div v-show="view">
            <TableHeader datePicker showExport showCustomColumn>
                <template #select>
                    <el-form-item label="统计类型:">
                        <el-radio-group v-model="tableStore.table.params.isType">
                            <el-radio-button :label="0">在线</el-radio-button>
                            <el-radio-button :label="1">离线</el-radio-button>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="筛选数据">
                        <el-input
                            v-model="tableStore.table.params.searchValue"
                            clearable
                            placeholder="输入关键字筛选"
                            style="width: 200px"
                            maxlength="32"
                            show-word-limit
                        />
                    </el-form-item>
                    <el-form-item label="触发类型">
                        <el-select
                            v-model="tableStore.table.params.waveType"
                            placeholder="请选择触发类型"
                            clearable
                            multiple
                            collapse-tags
                            style="width: 100%"
                            filterable
                        >
                            <el-option
                                v-for="item in triggeroptions"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="是否有波形">
                        <el-select
                            v-model="tableStore.table.params.fileFlag"
                            placeholder="请选择是否存在波形"
                            clearable
                            style="width: 100%"
                            filterable
                        >
                            <el-option
                                v-for="item in wareaoptions"
                                :key="item.id"
                                :label="item.label"
                                :value="item.id"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="暂态持续时间(s)">
                        <el-input
                            v-model="tableStore.table.params.persistMin"
                            placeholder="请输入X秒"
                            onkeyup="value=value.replace(/[^\d.]/g,'')"
                            clearable
                            style="width: 94px"
                        ></el-input>
                        <el-tag style="margin-left: 5px">&lt; 时间数 &lt;</el-tag>
                        <el-input
                            v-model="tableStore.table.params.persistMax"
                            placeholder="请输入X秒"
                            onkeyup="value=value.replace(/[^\d.]/g,'')"
                            clearable
                            style="margin-left: 5px; width: 94px"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="事件严重度">
                        <el-input
                            v-model="tableStore.table.params.severityMin"
                            placeholder="请输入正负数"
                            onkeyup="value=value.replace(/[^\d\.-]/g,'')"
                            clearable
                            style="width: 94px"
                        ></el-input>
                        <el-tag style="margin-left: 5px">&lt; 严重度 &lt;</el-tag>
                        <el-input
                            v-model="tableStore.table.params.severityMax"
                            placeholder="请输入正负数"
                            onkeyup="value=value.replace(/[^\d\.-]/g,'')"
                            clearable
                            style="margin-left: 5px; width: 94px"
                        ></el-input>
                    </el-form-item>

                    <!-- <el-form-item label="触发类型:">
                        <el-select v-model="tableStore.table.params.eventType" placeholder="请选择触发类型" clearable multiple
                            collapse-tags style="width: 100%">
                            <el-option v-for="item in typeoptions" :key="item.id" :label="item.name"
                                :value="item.id"></el-option>
                        </el-select>
                    </el-form-item> -->
                    <el-form-item label="暂态原因">
                        <el-select
                            v-model="tableStore.table.params.eventReason"
                            placeholder="请选择暂态原因"
                            clearable
                            multiple
                            collapse-tags
                            style="width: 100%"
                            filterable
                        >
                            <el-option
                                v-for="item in reasonoptions"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="暂态核实原因">
                        <el-select
                            v-model="tableStore.table.params.verifyReason"
                            placeholder="请选择暂态核实原因"
                            clearable
                            multiple
                            collapse-tags
                            collapse-tags-tooltip
                            filterable
                            >
                            <el-option
                                v-for="item in verifyReasonList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="变电站(监测点)">
                        <el-cascader
                            v-model="tableStore.table.params.lineIds"
                            :options="options"
                            :props="defaultProps"
                            collapse-tags-tooltip
                            style="width: 257px"
                            filterable
                            clearable
                            collapse-tags
                            placeholder="请选择变电站(监测点)"
                            :show-all-levels="true"
                        />
                    </el-form-item>
                </template>
                <template #operation>
                    <el-button icon="el-icon-Download" type="primary" @click="download">下载波形</el-button>
                    <!-- <el-button icon="el-icon-Download" type="primary" @click="exportEvent">导出</el-button> -->
                </template>
            </TableHeader>
            <Table ref="tableRef" />
        </div>
        <div :style="{ height: pageHeight.height }" style="padding: 10px; overflow: hidden" v-if="!view">
            <waveForm ref="waveFormRef" senior :boxoList="boxoList" :wp="wp" @backbxlb="backbxlb" />
        </div>
        <addForm ref="addFormRef" @onSubmit="tableStore.index()" />
    </div>
</template>
<script setup lang="ts">
import { ref, onMounted, provide } from 'vue'
import TableStore from '@/utils/tableStore'
import Table from '@/components/table/index.vue'
import TableHeader from '@/components/table/header/index.vue'
import { mainHeight } from '@/utils/layout'
import { useDictData } from '@/stores/dictData'
import { ElMessageBox, ElMessage } from 'element-plus'
import addForm from './addForm.vue'
import { getTransientValue } from '@/api/event-boot/report'
import { getTerminalTreeForFive } from '@/api/device-boot/terminalTree'
import { useAdminInfo } from '@/stores/adminInfo'
import waveForm from '@/components/echarts/waveForm.vue'
import { getMonitorEventAnalyseWave, downloadWaveFile } from '@/api/event-boot/transient'
defineOptions({
    name: 'Region/transientlist'
})
const dictData = useDictData()
const adminInfo = useAdminInfo()
const waveFormRef = ref()
const pageHeight = mainHeight(20)
const view = ref(true)
const addFormRef = ref()
const typeoptions = dictData.getBasicData('Event_Type')
const tableRef = ref()
const reasonoptions = dictData.getBasicData('Event_Reason')
const triggeroptions = dictData.getBasicData('Event_Statis')
const verifyReasonList: any = dictData.getBasicData('verifyReason')
const wareaoptions = ref([
    {
        id: 1,
        label: '是'
    },
    {
        id: 0,
        label: '否'
    }
])
const formData = {
    deptIndex: adminInfo.$state.deptIndex,
    monitorFlag: 2,
    powerFlag: 2,
    loadType: null,
    manufacturer: null,
    serverName: 'event-boot',
    statisticalType: dictData.getBasicData('Statistical_Type', ['Report_Type'])[0],
    scale: null
}
const tableStore = new TableStore({
    url: '/event-boot/transient/getTransientValue',
    method: 'POST',
    column: [
        { width: '60', type: 'checkbox' },
        {
            field: 'index',
            title: '序号',
            width: '80',
            formatter: (row: any) => {
                return (tableStore.table.params.pageNum - 1) * tableStore.table.params.pageSize + row.rowIndex + 1
            }
        },
        { field: 'startTime', title: '暂降发生时刻', minWidth: '200', sortable: true },
        {
            field: 'featureAmplitude',
            title: '暂降(骤升)幅值(%)',
            minWidth: '160',
            sortable: true,
            formatter: (row: any) => {
                return Math.floor(row.cellValue * 10000) / 100
            }
        },
        { field: 'duration', title: '持续时间(s)', minWidth: 120, sortable: true },
        {
            field: 'eventType',
            title: '触发类型',
            minWidth: '100',

            formatter: ({ row }: any) => {
                return triggeroptions.filter(item => item.id == row.eventType)[0]?.name
            }
        },
        {
            field: 'depth',
            title: '暂降深度(%)',
            minWidth: 120,

            formatter: ({ row }: any) =>
                row.featureAmplitude < 1 ? 100 - (row.featureAmplitude * 100).toFixed(0) : '/'
        },

        { field: 'advanceReason', title: '暂态原因', minWidth: '100' },
        {
            field: 'verifyReason',
            title: '暂态核实原因',
            minWidth: '120',
            formatter: function (row) {
                return verifyReasonList.filter(item => item.id == row.cellValue)[0]?.name || '/' //row.cellValue ? row.cellValue : '/'
            }
        },
        { field: 'gdName', title: '供电公司', minWidth: '100' },
        { field: 'subName', title: '变电站', minWidth: '200' },
        { field: 'lineName', title: '监测点', minWidth: '100' },
        { field: 'ip', title: '网络参数', width: '120px' },
        { field: 'scale', title: '电压等级(kV)', minWidth: '130', sortable: true },

        // { field: 'advanceType', title: '触发类型', minWidth: '100', },

        {
            field: 'severity',
            title: '严重度',
            minWidth: '100',
            formatter: ({ row }: any) => (row.severity < 0 ? '/' : row.severity)
        },

        {
            title: '操作',
            fixed: 'right',
            width: '150',
            render: 'buttons',

            buttons: [
                {
                    name: 'edit',
                    title: '人工维护',
                    type: 'primary',
                    icon: 'el-icon-Plus',
                    render: 'basicButton',
                    click: async row => {
                        addFormRef.value.open(row)
                    }
                },
                {
                    name: 'edit',
                    title: '波形分析',
                    type: 'primary',
                    disabled: row => {
                        return row.fileFlag == 0
                    },
                    icon: 'el-icon-Plus',
                    render: 'basicButton',
                    click: async row => {
                        // row.loading = true
                        view.value = false
                        setTimeout(() => {
                            waveFormRef.value.open(row)
                        }, 100)
                        // boxoList.value = row
                        // await getMonitorEventAnalyseWave({ id: row.eventId, systemType: 0 })
                        //     .then(res => {
                        //         row.loading = false
                        //         if (res != undefined) {
                        //             wp.value = res.data
                        //             view.value = false
                        //         }
                        //     })
                        //     .catch(() => {
                        //         row.loading = false
                        //     })
                    }
                },
                {
                    name: 'edit',
                    title: '暂无波形',
                    type: '',
                    disabled: row => {
                        return row.fileFlag == 1
                    },
                    icon: 'el-icon-Plus',
                    render: 'basicButton'
                }
            ]
        }
    ],

    loadCallback: () => {}
})
const options = ref([])
const defaultProps = {
    multiple: true,
    // checkStrictly: true,
    label: 'name',
    value: 'id',
    children: 'children',
    emitPath: false
}
const boxoList = ref({})
const wp = ref({})

provide('tableStore', tableStore)

tableStore.table.params.deptIndex = dictData.state.area[0].id
tableStore.table.params.isType = 0
tableStore.table.params.searchValue = ''
tableStore.table.params.monitorFlag = 2
tableStore.table.params.powerFlag = 2
tableStore.table.params.serverName = 'event-boot'
tableStore.table.params.statisticalType = {}
tableStore.table.params.eventValueMin = ''
tableStore.table.params.eventValueMax = ''
tableStore.table.params.persistMin = ''
tableStore.table.params.persistMax = ''
tableStore.table.params.severityMin = ''
tableStore.table.params.severityMax = ''
tableStore.table.params.eventType = []
tableStore.table.params.eventReason = []
tableStore.table.params.verifyReason = []
tableStore.table.params.lineIds = []
tableStore.table.params.waveType = []
tableStore.table.params.fileFlag = ''
onMounted(() => {
    tableStore.index()
    getTerminalTreeForFive(formData).then(res => {
        options.value = []
        let list = res.data.map((item: any) => {
            return item.children.map((vv: any) => {
                vv.children.map((kk: any) => {
                    kk.name = kk.name.replace(/\（.*?\）/, '')
                })
                return vv.children
            })
        })[0]
        list.forEach((item: any) => {
            options.value.push(...item)
        })
    })
})
const backbxlb = () => {
    view.value = true
}
// 导出列表
const exportEvent = () => {
    let form = JSON.parse(JSON.stringify(tableStore.table.params))
    form.pageNum = 1
    form.pageSize = tableStore.table.total
    getTransientValue(form).then(res => {
        tableRef.value.getRef().exportData({
            filename: '暂态列表', // 文件名字
            sheetName: 'Sheet1',
            type: 'xlsx', //导出文件类型 xlsx 和 csv
            useStyle: true,
            data: res.data.records, // 数据源 // 过滤那个字段导出
            columnFilterMethod: function (column, $columnIndex) {
                return !(column.$columnIndex === 0)
            }
        })
    })
}
const download = () => {
    if (!tableStore.table.selection.length) {
        ElMessage.warning('请选择数据')
        return
    }
    downloadWaveFile({
        lineId: tableStore.table.selection.map((item: any) => item.eventId)
    }).then((res: any) => {
        if (res.type == 'application/json') {
            ElMessage.warning('暂无可下载的波形文件!')
            return
        }
        ElMessage.info('下载中......')
        let blob = new Blob([res], { type: 'application/zip' }) // console.log(blob) // var href = window.URL.createObjectURL(blob); //创建下载的链接
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a') // 创建a标签
        link.href = url
        link.download = '波形分析下载' // 设置下载的文件名
        document.body.appendChild(link)
        link.click() //执行下载
        document.body.removeChild(link) //释放标签
        ElMessage.success('波形下载成功')
    })
}
</script>
<style scoped lang="scss">
:deep(.el-tag.is-closable) {
    width: 100px;
}
</style>
