<template>
    <div class='default-main'>
        <!-- 表头 -->
        <TableHeader date-picker ref='tableHeader' showCustomColumn>
            <template v-slot:select>
                <el-form-item label='用户'>
                    <el-select v-model='tableStore.table.params.userId' filterable @change='changeUser'>
                        <el-option v-for='item in userListData' :key='item.id' :label='item.userName'
                            :value='item.id' />
                    </el-select>
                </el-form-item>
            </template>
            <template v-slot:operation>
                <!--返回按钮-->
                <back-component />
            </template>
        </TableHeader>
        <!--导入暂降数据查询框-->
        <event-upload-popup ref='eventUploadPopup' />

        <el-radio-group v-model='radio' id='tabTitle' @change='switchRadio'>
            <el-radio-button value='暂降数据' >暂降数据</el-radio-button>
            <el-radio-button value='电压暂降事件统计' >电压暂降事件统计</el-radio-button>
            <el-radio-button value='耐受曲线信息' >耐受曲线信息</el-radio-button>
        </el-radio-group>
        <div class='tableExtraButton'>
            <el-button :icon='Upload' type='primary' @click='importEventData'>导入</el-button>
            <el-button :icon='Download' type='primary' @click='exportExcel'>数据导出</el-button>
            <el-button :icon='Download' type='primary' @click='exportExcelTemplate'>下载模板</el-button>
        </div>

        <div style='position: relative;'>
            <!-- 表格 -->
            <Table ref='tableRef' />

            <Transition name='el-fade-in-linear' mode='out-in'>
                <Sags3D ref='sags3DRef' v-if="radio == '电压暂降事件统计'" />
            </Transition>

            <Transition name='el-fade-in-linear' mode='out-in'>
                <ToleranceCurve ref='toleranceCurveRef' v-if="radio == '耐受曲线信息'" />
            </Transition>

        </div>
    </div>
</template>
<script setup lang='ts'>
import { Upload, Download } from '@element-plus/icons-vue'
import { ref, provide, reactive, onMounted } from 'vue'
import TableStore from '@/utils/tableStore'
import Table from '@/components/table/index.vue'
import TableHeader from '@/components/table/header/index.vue'
import Sags3D from './sags3D.vue'
import ToleranceCurve from './toleranceCurve.vue'
import BackComponent from '@/components/icon/back/index.vue'
import { useRoute } from 'vue-router'
import { sgUserList } from '@/api/advance-boot/sgGroven/sgUser'
import EventUploadPopup from '@/views/pqs/voltageSags/sagGovern/businessUser/event/eventUploadPopup.vue'
import { calcEventLoss, deleteSgEvent, downloadTemplate, exportEventData } from '@/api/advance-boot/sgGroven/sgEvent'
import { ElMessage } from 'element-plus'

const tableHeader = ref()
const { query } = useRoute()
const userId = ref()
// 注意名字不要重复，若要保持页面存活，名字需要和路由admin后面的字符保持一致
defineOptions({
    name: 'sagVoltageData'
})
const radio = ref('暂降数据')
const eventUploadPopup = ref()
const sags3DRef = ref()
const toleranceCurveRef = ref()
const userListData: any = reactive([])

const tableStore = new TableStore({
    // 若页面表格高度需要调整，请修改publicHeight(内容区域除表格外其他内容的高度)
    url: '/advance-boot/sgEvent/list',
    method: 'POST',
    publicHeight: 40,
    column: [
    { title: '序号',  width: 80,formatter: (row: any) => {
        return (tableStore.table.params.pageNum - 1) * tableStore.table.params.pageSize + row.rowIndex + 1
      } },
        { title: '进线', field: 'incomingLineName', minWidth: '130' },
        { title: '发生时间', field: 'startTime', minWidth: '220', sortable: true },
        { title: '暂降幅值(p.u.)', field: 'featureAmplitude', minWidth: '130', sortable: true },
        { title: '持续时间(ms)', field: 'duration', minWidth: '130', sortable: true },
        { title: '预计损失(万元)', field: 'estimatedLoss', minWidth: '130', sortable: true },
        {
            title: '数据来源', field: 'dataSource', minWidth: '130',
            formatter: (obj: any) => {
                return obj.row.dataSource == 0 ? '离线导入' : '监测点同步'
            }
        },
        {
             title: '操作',fixed: 'right',
            align: 'center',
            width: '230',
            render: 'buttons',
            buttons: [
                // {
                //     name: 'productSetting',
                //     title: '波形查看',
                //     type: 'primary',
                //     icon: 'el-icon-EditPen',
                //     render: 'basicButton',
                //     disabled: row => {
                //         return row.fileFlag !== 0
                //     }
                //     // click: async row => {
                //     //     dialogFormVisible.value = true
                //     //     dialogTitle.value = '前置机修改'
                //     //     formData.value = JSON.parse(JSON.stringify(row))
                //     // }
                // },
                {
                    name: 'productSetting',
                    title: '计算损失',
                    type: 'primary',
                    icon: 'el-icon-EditPen',
                    render: 'basicButton',
                    click: row => {
                        calcEventLoss(row.id).then(res => {
                            ElMessage.success('计算成功')
                            tableStore.index()
                        })
                    }
                },
                // {
                //     name: 'productSetting',
                //     title: '暂无波形',
                //     type: 'primary',
                //     icon: 'el-icon-EditPen',
                //     render: 'basicButton',
                //     disabled: row => {
                //         return row.fileFlag !== 1
                //     }
                // },
                {
                    name: 'update',
                    title: '删除',
                    type: 'danger',
                    icon: 'el-icon-Delete',
                    render: 'confirmButton',
                    popconfirm: {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        confirmButtonType: 'danger',
                        title: '确定删除吗？'
                    },
                    click: row => {
                        deleteSgEvent(row.id).then(res => {
                            ElMessage.success('删除成功')
                            tableStore.index()
                        })
                    }
                }

            ]
        }
    ],
    beforeSearchFun: () => {
        tableStore.table.params.searchBeginTime = tableHeader.value.datePickerRef.timeValue[0]
        tableStore.table.params.searchEndTime = tableHeader.value.datePickerRef.timeValue[1]
        for (let key in tableStore.table.params) {
            if (tableStore.table.params[key] === '') {
                delete tableStore.table.params[key]
            }
        }
        sags3DRef.value?.search(userId.value, tableStore.table.params.searchBeginTime, tableStore.table.params.searchEndTime)
        toleranceCurveRef.value?.search(userId.value, tableStore.table.params.searchBeginTime, tableStore.table.params.searchEndTime)
    }
})
// 注入到子组件
provide('tableStore', tableStore)
onMounted(() => {
    // tableHeader.value.setTheDate(1)
})
//初始化页面
const initData = async () => {
    //先查询所有用户列表
    await sgUserList().then(res => {
        Object.assign(userListData, res.data)
    })
    userId.value = query.id
    tableStore.table.params.userId = userId.value
    tableStore.index()
    sags3DRef.value?.search(userId.value, tableStore.table.params.searchBeginTime, tableStore.table.params.searchEndTime)
    toleranceCurveRef.value?.search(userId.value, tableStore.table.params.searchBeginTime, tableStore.table.params.searchEndTime)
}

initData()

const switchRadio = () => {
    if (radio.value == '电压暂降事件统计') {
        sags3DRef.value?.search(userId.value, tableHeader.value.datePickerRef.timeValue[0], tableHeader.value.datePickerRef.timeValue[1])
    } else if (radio.value == '耐受曲线信息') {
        toleranceCurveRef.value?.search(userId.value, tableHeader.value.datePickerRef.timeValue[0], tableHeader.value.datePickerRef.timeValue[1])
    }
}


//用户信息更换
const changeUser = () => {
    userId.value = tableStore.table.params.userId
}

//批量导入暂降数据
const importEventData = () => {
    // 弹出框，联级选择生产线--进线，上传文件
    eventUploadPopup.value.open('导入暂降数据', userId.value)
}

// 导出表格
const exportExcel = () => {
    const param = {
        userId: userId.value,
        searchBeginTime: tableHeader.value.datePickerRef.timeValue[0],
        searchEndTime: tableHeader.value.datePickerRef.timeValue[1]
    }
    exportEventData(param).then((res: any) => {
        let blob = new Blob([res], {
            type: 'application/vnd.ms-excel'
        })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = '暂降事件数据'
        document.body.appendChild(link)
        link.click()
        link.remove()
    })
}

//导出模板
const exportExcelTemplate = () => {
    downloadTemplate().then((res: any) => {
        let blob = new Blob([res], {
            type: 'text/csv'
        })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = '暂降事件模板'
        document.body.appendChild(link)
        link.click()
        link.remove()
    })
}

</script>
<style scoped>
.tableExtraButton {
    position: absolute;
    right: 17px;
    top: 55px;
}

#tabTitle {
    border-left: 1px solid var(--el-border-color);
    border-right: 1px solid var(--el-border-color);
    width: 100%;
    padding: 0 0 5px 5px;
    margin-top: -5px;
}

.cn-table-header {
    border-bottom: 0 !important;
}
</style>
