<template>
    <div>
        <!-- 监测点列表 -->
        <TableHeader
            ref="TableHeaderRef"
            :showReset="false"
            showExport
            @selectChange="selectChange"
            v-if="fullscreen"
            :timeKeyList="prop.timeKey"
        >
            <template #select>
                <el-form-item label="关键字筛选">
                    <el-input
                        maxlength="32"
                        show-word-limit
                        style="width: 240px"
                        v-model.trim="tableStore.table.params.searchValue"
                        clearable
                        placeholder="请输入监测点名称"
                    />
                </el-form-item>
            </template>
        </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="上传报告"
            append-to-body
            width="500px"
            @closed="handleDialogClosed"
        >
            <el-upload
                ref="uploadRef"
                class="upload-demo"
                action=""
                accept=".doc,.docx,.PDF"
                :on-change="handleChange"
                :before-upload="beforeUpload"
                :limit="1"
                :auto-upload="false"
                :on-exceed="handleExceed"
                :on-remove="handleRemove"
                :file-list="fileList"
            >
                <el-button type="primary">点击上传</el-button>
                <template #tip>
                    <div class="el-upload__tip">请上传Word或PDF文件</div>
                </template>
            </el-upload>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="uploadDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleUpload" :loading="loading">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, provide, watch, computed } 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 { downLoadFile } from '@/api/cs-system-boot/manage'
const prop = defineProps({
    w: { type: [String, Number] },
    h: { type: [String, Number] },
    width: { type: [String, Number] },
    height: { type: [String, Number] },
    timeKey: { type: Array as () => string[] },
    timeValue: { type: Object },
    interval: { type: Number },
    flag: { type: Boolean }
})

const headerHeight = ref(57)

const TableHeaderRef = ref()

// 上传相关
const uploadDialogVisible = ref(false)
const currentUploadRow = ref<any>(null)
const uploadRef = ref()
const fileList = ref([])
const loading = ref(false)
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: 'lineName',
            minWidth: 150,
            render: 'customTemplate',
            customTemplate: (row: any) => {
                return `<span style='cursor: pointer;text-decoration: underline;'>${row?.lineName || '/'}</span>`
            }
        },
        { title: '设备名称', field: 'devName', minWidth: 150, align: 'center' },
        { title: '项目名称', field: 'projectName', minWidth: 150, align: 'center' },
        { title: '工程名称', field: 'engineeringName', minWidth: 150, align: 'center' },
        // {
        //     title: '监测类型',
        //     field: 'position',
        //     minWidth: '100',
        //     formatter: (row: any) => {
        //         return row.cellValue || '/'
        //     }
        // },
        // {
        //     title: '监测点状态',
        //     field: 'runStatus',
        //     minWidth: '90',
        //     render: 'customTemplate',
        //     customTemplate: (row: any) => {
        //         return `<span style='color: ${row.runStatus === '中断' ? '#FF0000' : ''}'>${row.runStatus==null?'/':row.runStatus}</span>`
        //     }
        // },
        {
            title: '监测点状态',
            field: 'runStatus',
            render: 'tag',
            width: 90,
            custom: {
                0: 'success',
                2: 'danger',
                null: 'info'
            },
            replaceValue: {
                0: '在线',
                2: '离线',
                null: '/'
            }
        },
        {
            title: '电压等级(kV)',
            field: 'volGrade',
            minWidth: '100',
            formatter: (row: any) => {
                return row.cellValue == 0 ? '/' : row.cellValue || '/'
            }
        },
        {
            title: '治理对象',
            field: 'sensitiveUser',
            minWidth: '100',
            formatter: (row: any) => {
                return row.cellValue || '/'
            }
        },

        {
            title: '治理方案',
            field: 'govern',
            minWidth: '80',
            formatter: (row: any) => {
                return row.cellValue || '/'
            }
        },

        {
            title: '最新数据时间',
            field: 'latestTime',
            minWidth: '140',
            render: 'customTemplate',
            customTemplate: (row: any) => {
                if (row.latestTime) {
                    return `<span>${row.latestTime}</span>`
                } else {
                    return `<span>/</span>`
                }
            }
        },
        // {
        //     title: '报告',
        //     field: 'reportFilePath',
        //     minWidth: '120',
        //     render: 'customTemplate',
        //     customTemplate: (row: any) => {
        //         return row.reportFilePath == null
        //             ? '/'
        //             : `<span style='cursor: pointer;text-decoration: underline;'>${row.reportFilePath
        //                   .split('/')
        //                   .pop()}</span>`
        //     }
        // },
        {
            title: '治理前报告',
            field: 'reportFilePath',
            minWidth: '150',
            formatter: (row: any) => {
                return row.cellValue == null ? '/' : row.cellValue.split('/').pop()
            }
        },
        {
            title: '操作',
            fixed: 'right',
            width: 150,
            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.reportFilePath)
                    },
                    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 = ''
tableStore.table.params.searchValue = ''
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]
        )
    }
}

// 下载报告（支持 doc/docx/pdf）
const downloadTheReport = async (reportFilePath: string) => {
    if (!reportFilePath) {
        ElMessage.warning('暂无报告可下载')
        return
    }
    ElMessage.info('下载中......')
    try {
        const resp = (await downLoadFile(reportFilePath)) as unknown as Blob
        if (resp?.type === 'application/json') {
            ElMessage.error('下载失败')
            return
        }
        const fileName = reportFilePath.split('/').pop() || '报告'
        const blob = new Blob([resp], { type: resp.type || 'application/octet-stream' })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = fileName
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
        ElMessage.success('下载成功')
    } catch (error: any) {
        ElMessage.error('下载失败: ' + (error.message || '未知错误'))
    }
}

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

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

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

// 文件变更处理函数
const handleChange = (file: any) => {
    // 在这里直接处理文件上传逻辑
    // beforeUpload(file.raw) // 注意使用 file.raw 获取原始文件对象
    fileList.value = [file] // 只保留最新选择的文件
}

// 处理上传前检查
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('请上传(.doc/.docx/.pdf)格式文件!')
        return false
    }

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

const handleUpload = async () => {
    // return
    loading.value = true
    const formData = new FormData()
    formData.append('file', fileList.value[0]?.raw)
    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)
    } finally {
        loading.value = false
    }
}

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