<template>
    <div>
        <!-- 监测点列表 -->
        <TableHeader
            ref="TableHeaderRef"
            :showReset="false"
            @selectChange="selectChange"
            datePicker
            v-if="fullscreen"
        ></TableHeader>
        <Table
            ref="tableRef"
            @cell-click="cellClickEvent"
            :height="`calc(${prop.height} - ${headerHeight}px + ${fullscreen ? -58 : 56}px )`"
        ></Table>
        <!-- 指标越限详情 -->
        <OverLimitDetails ref="OverLimitDetailsRef" />

        <!-- 上传对话框 -->
        <el-dialog v-model="uploadDialogVisible" title="上传报告" width="500px" @closed="handleDialogClosed">
            <el-upload
                ref="uploadRef"
                class="upload-demo"
                :auto-upload="true"
                :on-change="handleChange"
                :before-upload="beforeUpload"
                :http-request="handleUpload"
                :limit="1"
                :on-exceed="handleExceed"
                :file-list="fileList"
            >
                <el-button type="primary">点击上传</el-button>
                <template #tip>
                    <div class="el-upload__tip">只能上传Word或PDF文件，且不超过10MB</div>
                </template>
            </el-upload>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="uploadDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="uploadDialogVisible = false">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, provide, reactive, watch, h } from 'vue'
import TableStore from '@/utils/tableStore'
import Table from '@/components/table/index.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import OverLimitDetails from '@/components/cockpit/monitoringPointList/components/overLimitDetails.vue'
import TableHeader from '@/components/table/header/index.vue'
import { uploadReport, getReportUrl } from '@/api/harmonic-boot/cockpit/cockpit'
import { getTime } from '@/utils/formatTime'

const prop = defineProps({
    w: { type: [String, Number] },
    h: { type: [String, Number] },
    width: { type: [String, Number] },
    height: { type: [String, Number] },
    timeKey: { type: [String, Number] },
    timeValue: { type: Object },
    interval: { type: Number }
})

const headerHeight = ref(57)

const TableHeaderRef = ref()

// 上传相关
const uploadDialogVisible = ref(false)
const currentUploadRow = ref<any>(null)
const uploadRef = ref()
const fileList = ref([])

const selectChange = (showSelect: any, height: any, datePickerValue?: any) => {
    headerHeight.value = height

    if (datePickerValue && datePickerValue.timeValue) {
        // 更新时间参数
        tableStore.table.params.searchBeginTime = datePickerValue.timeValue[0]
        tableStore.table.params.searchEndTime = datePickerValue.timeValue[1]
    }
}

// 计算是否全屏展示
const fullscreen = computed(() => {
    const w = Number(prop.w)
    const h = Number(prop.h)
    if (!isNaN(w) && !isNaN(h) && w === 12 && h === 6) {
        // 执行相应逻辑
        return true
    } else {
        return false
    }
})

const OverLimitDetailsRef = ref()
const tableStore: any = new TableStore({
    url: '/cs-device-boot/csline/getSensitiveUserLineList',
    method: 'POST',
    showPage: fullscreen.value ? true : false,
    exportName: '监测点列表',
    column: [
        {
            field: 'index',
            title: '序号',
            width: '80',
            formatter: (row: any) => {
                return (tableStore.table.params.pageNum - 1) * tableStore.table.params.pageSize + row.rowIndex + 1
            }
        },
        {
            title: '治理对象',
            field: 'sensitiveUser',
            minWidth: '80'
        },

        {
            title: '电压等级',
            field: 'volGrade',
            minWidth: '70'
        },
        {
            title: '是否治理',
            field: 'govern',
            minWidth: '70'
        },

        // {
        //     title: '治理前报告',
        //     field: 'reportFileName',
        //     minWidth: '80',
        //     render: 'customTemplate',
        //     customTemplate: (row: any) => {
        //         return `<span style='cursor: pointer;text-decoration: underline;'>${row.reportFileName}</span>`
        //     }
        // },
        {
            title: '监测点名称',
            field: 'lineName',
            minWidth: '70',
            render: 'customTemplate',
            customTemplate: (row: any) => {
                return `<span style='cursor: pointer;text-decoration: underline;'>${row.lineName}</span>`
            }
        },
        { title: '监测类型', field: 'position', minWidth: '60' },
        {
            title: '监测点状态',
            field: 'runStatus',
            minWidth: '60',
            render: 'customTemplate',
            customTemplate: (row: any) => {
                return `<span style='color: ${row.runStatus === '中断' ? '#FF0000' : ''}'>${row.runStatus}</span>`
            }
        },
        {
            title: '最新数据时间',
            field: 'latestTime',
            minWidth: '140',
            render: 'customTemplate',
            customTemplate: (row: any) => {
                if (row.latestTime) {
                    return `<span>${row.latestTime}</span>`
                } else {
                    return `<span>/</span>`
                }
            }
        },
        {
            title: '操作',
            minWidth: 120,
            // fixed: 'right',
            render: 'buttons',
            buttons: [
                {
                    name: 'productSetting',
                    title: '上传报告',
                    type: 'primary',
                    icon: 'el-icon-upload',
                    render: 'basicButton',
                    click: row => {
                        uploadReportRow(row)
                    },
                    disabled: row => {
                        return row.reportFilePath
                    }
                },

                {
                    name: 'productSetting',
                    title: '下载报告',
                    type: 'primary',
                    icon: 'el-icon-EditPen',
                    render: 'basicButton',
                    click: row => {
                        downloadTheReport(row.lineId)
                    },
                    disabled: row => {
                        return row.reportFilePath == null || row.reportFilePath.length == 0
                    }
                },
                {
                    name: 'productSetting',
                    title: '重新上传',
                    type: 'primary',
                    icon: 'el-icon-upload',
                    render: 'basicButton',
                    click: row => {
                        uploadReportRow(row)
                    },
                    disabled: row => {
                        return row.reportFilePath == null || row.reportFilePath.length == 0
                    }
                }
            ]
        }
    ],
    beforeSearchFun: () => {
        setTime()
    },
    loadCallback: () => {
        tableStore.table.height = `calc(${prop.height} - 80px)`
    }
})

const tableRef = ref()
provide('tableRef', tableRef)
tableStore.table.params.keywords = ''
provide('tableStore', tableStore)

const setTime = () => {
    const time = getTime(
        (TableHeaderRef.value?.datePickerRef.interval || prop.interval) ?? 0,
        prop.timeKey,
        fullscreen.value
            ? [tableStore.table.params.searchBeginTime, tableStore.table.params.searchEndTime]
            : prop.timeValue
    )

    if (Array.isArray(time)) {
        tableStore.table.params.searchBeginTime = time[0]
        tableStore.table.params.searchEndTime = time[1]
        TableHeaderRef.value?.setInterval(time[2] - 0)
        TableHeaderRef.value?.setTimeInterval([time[0], time[1]])
    } else {
        console.warn('获取时间失败，time 不是一个有效数组')
    }
}

// 点击行
const cellClickEvent = ({ row, column }: any) => {
    if (column.field == 'lineName') {
        OverLimitDetailsRef.value.open(
            row,
            tableStore.table.params.searchBeginTime || prop.timeValue?.[0],
            tableStore.table.params.searchEndTime || prop.timeValue?.[1]
        )
    }
}

// 下载报告
const downloadTheReport = (lineId: string) => {
    getReportUrl({ lineId: lineId }).then((res: any) => {
        const link = document.createElement('a')
        link.href = res.data
        link.download = '治理报告'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
    })
}

// 上传报告
const uploadReportRow = (row: any) => {
    currentUploadRow.value = row
    // 打开弹窗前清空文件列表
    fileList.value = []
    uploadDialogVisible.value = true
}

// 处理弹窗关闭事件
const handleDialogClosed = () => {
    // 清空文件列表
    fileList.value = []
}

// 处理文件超出限制
const handleExceed = (files: any, fileList: any) => {
    ElMessage.warning('只能上传一个文件，请先删除已选择的文件')
}

// 文件变更处理函数
const handleChange = (file: any, fileList: any) => {
    // 在这里直接处理文件上传逻辑
    beforeUpload(file.raw) // 注意使用 file.raw 获取原始文件对象
}

// 处理上传前检查
const beforeUpload = (file: any) => {
    const isWord =
        file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
        file.type === 'application/msword' ||
        file.name.endsWith('.doc') ||
        file.name.endsWith('.docx')

    const isPDF = file.type === 'application/pdf' || file.name.endsWith('.pdf')

    const isValidType = isWord || isPDF
    const isLt10M = file.size / 1024 / 1024 < 10

    if (!isValidType) {
        ElMessage.error('上传文件只能是 Word 文档(.doc/.docx) 或 PDF 文件(.pdf)!')
        return false
    }
    if (!isLt10M) {
        ElMessage.error('上传文件大小不能超过 10MB!')
        return false
    }

    // 校验通过后允许上传，交由 http-request 处理
    return true
}

const handleUpload = async (options: any) => {
    const { file } = options
    const formData = new FormData()
    formData.append('file', file)
    formData.append('lineId', currentUploadRow.value?.lineId || currentUploadRow.value?.id || '')

    try {
        const result = await uploadReport(formData)
        ElMessage.success('上传成功')
        uploadDialogVisible.value = false
        tableStore.index()
        return Promise.resolve(result)
    } catch (error: any) {
        ElMessage.error('上传失败: ' + (error.message || '未知错误'))
        return Promise.reject(error)
    }
}

onMounted(() => {
    tableStore.index()
})
watch(
    () => prop.timeKey,
    val => {
        tableStore.index()
    }
)
watch(
    () => prop.timeValue,
    (newVal, oldVal) => {
        tableStore.index()
    },
    {
        deep: true
    }
)
</script>
<style lang="scss" scoped></style>
