<template>
    <div class="app-container">
        <!-- 计划管理 -->
        <ComTable
            ref="comTableRef"
            :form-columns="formColumns"
            :table-columns="tableColumns"
            :load-data="listPlanAPI"
            :show-toolbar="true"
            :show-action="true"
            :action-columns="actionColumns"
        >
            <template #toolbar>
                <ComButton
                    type="primary"
                    icon="Plus"
                    @click="onHandleAdd"
                    v-hasPermi="['plan:plan:add']"
                >
                    新建计划
                </ComButton>
                <ComButton
                    pain
                    type="info"
                    icon="Upload"
                    @click="onHandleImport"
                    v-hasPermi="['plan:plan:import']"
                >
                    导入计划
                </ComButton>
            </template>
        </ComTable>

        <ComDialog :dialog-config="dialogConfig" @closeDialogOuter="onCloseDialogOuter">
            <template #outerContent>
                <!-- 将表单抽离到独立组件中，保持 index.vue 简洁 -->
                <AddAndEditForm
                    ref="formRef"
                    :form-data="addAndEditForm"
                    :inspection-station-options="inspectionStationOptions"
                />

                <el-row class="common-btn-row">
                    <ComButton plain type="info" @click="onHandleCancel">取消</ComButton>
                    <ComButton @click="onHandleSave">保存</ComButton>
                </el-row>
            </template>
        </ComDialog>

        <!-- 计划导入对话框 -->
        <ComDialog :dialog-config="uploadDialogConfig" @closeDialogOuter="onCloseUploadDialog">
            <template #outerContent>
                <el-upload
                    ref="uploadRef"
                    :limit="1"
                    accept=".xlsx, .xls"
                    :headers="upload.headers"
                    :action="upload.url + '?updateSupport=' + upload.updateSupport"
                    :disabled="upload.isUploading"
                    :on-progress="handleFileUploadProgress"
                    :on-success="handleFileSuccess"
                    :on-change="handleFileChange"
                    :on-remove="handleFileRemove"
                    :auto-upload="false"
                    drag
                >
                    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <template #tip>
                        <div class="el-upload__tip text-center">
                            <span>仅允许导入xls、xlsx格式文件。</span>
                            <el-link
                                type="primary"
                                :underline="false"
                                style="font-size: 12px; vertical-align: baseline"
                                @click="onHandleDownloadTemplate"
                            >
                                下载模板
                            </el-link>
                        </div>
                    </template>
                </el-upload>

                <el-row class="common-btn-row">
                    <ComButton plain type="info" @click="onCloseUploadDialog">取消</ComButton>
                    <ComButton type="primary" @click="submitFileForm">确定</ComButton>
                </el-row>
            </template>
        </ComDialog>
    </div>
</template>

<script setup name="Plan">
import { ref, nextTick, getCurrentInstance, computed, reactive } from 'vue'
import { listPlanAPI, addPlanAPI, updatePlanAPI, delPlanAPI } from '@/api/planMange/plan.js'
import { getInspectionStationSelectAPI } from '@/api/common.js'
import { useOptions } from '@/hooks/useOptions'
import useDictStore from '@/store/modules/dict'
import { selectDictLabel } from '@/utils/ruoyi'
import { getToken } from '@/utils/auth'
import dayjs from 'dayjs'
import config from './config'
import ComTable from '@/components/ComTable/index.vue'
import ComButton from '@/components/ComButton/index.vue'
import ComDialog from '@/components/ComDialog/index.vue'
import AddAndEditForm from './addAndEditForm.vue'

const { tableColumns: baseTableColumns, dialogConfig, buildFormColumns } = config
const { proxy } = getCurrentInstance()
const dictStore = useDictStore()

const formRef = ref(null)
const comTableRef = ref(null)
const editId = ref(null)
const uploadRef = ref(null)

// 计划导入弹框配置
const uploadDialogConfig = reactive({
    outerVisible: false,
    outerTitle: '计划导入',
    outerWidth: '400px',
    minHeight: '300px',
    maxHeight: '70vh',
})

// 计划导入参数
const upload = reactive({
    // 是否禁用上传
    isUploading: false,
    // 是否更新已经存在的计划数据
    updateSupport: 0,
    // 设置上传的请求头部
    headers: { Authorization: 'Bearer ' + getToken() },
    // 上传的地址（接口稍后提供）
    url: import.meta.env.VITE_APP_BASE_API + '/planManagement/importPlanManagement',
    selectedFile: null,
})

// 获取字典数据
const { plan_risk_level } = proxy.useDict('plan_risk_level')

// 根据实时下拉数据构建搜索表单配置
const formColumns = computed(() =>
    buildFormColumns(inspectionStationOptions.value, plan_risk_level.value),
)

// 创建动态 formatter 函数，每次执行时从 store 获取最新的字典数据
const createDynamicDictFormatter = (dictType, fieldName = null) => {
    return (row, column, cellValue) => {
        const value = fieldName ? row[fieldName] : cellValue
        // 每次执行时都从 store 获取最新的字典数据
        const dictData = dictStore.getDict(dictType) || []
        return selectDictLabel(dictData, value)
    }
}

// 构建表格列配置，添加字典映射的 formatter
const tableColumns = computed(() => {
    return baseTableColumns.map((column) => {
        if (column.prop === 'riskLevel') {
            return {
                ...column,
                // 使用动态 formatter，每次执行时都会获取最新的字典数据
                formatter: createDynamicDictFormatter('plan_risk_level', 'riskLevel'),
            }
        }
        return column
    })
})

// 使用通用 Hook 获取下拉数据（带缓存和自动刷新）
const { options: inspectionStationOptions } = useOptions(
    'inspectionStationOptions',
    getInspectionStationSelectAPI,
    {},
)

console.log(inspectionStationOptions, 'inspectionStationOptions')

// 1. 定义初始表单数据函数（优雅重置）——字段与表单保持同步
const getInitFormData = () => ({
    planManagementMonth: dayjs().format('YYYY-MM'), // 月份  默认当月
    projectName: '', // 项目名称
    workContent: '', // 作业内容
    inspectionStationId: null, // 实施部门
    stareDate: '', // 计划开始时间
    endDate: '', // 计划结束时间
    riskLevel: null, // 风险等级
    remark: '', // 备注
})

const addAndEditForm = ref(getInitFormData())

const actionColumns = [
    // {
    //     label: '编辑',
    //     type: 'primary',
    //     link: true,
    //     handler: (row) => {
    //         editId.value = row.planManagementId
    //         dialogConfig.outerTitle = '编辑计划'
    //         dialogConfig.outerVisible = true
    //         // 2. 使用 nextTick 确保弹框和子组件挂载后再回显数据
    //         nextTick(() => {
    //             const {
    //                 planManagementMonth,
    //                 projectName,
    //                 workContent,
    //                 inspectionStationId,
    //                 stareDate,
    //                 endDate,
    //                 riskLevel,
    //                 remark,
    //             } = row

    //             Object.assign(addAndEditForm.value, {
    //                 planManagementMonth,
    //                 projectName,
    //                 workContent,
    //                 inspectionStationId: inspectionStationId + '',
    //                 stareDate,
    //                 endDate,
    //                 riskLevel,
    //                 remark,
    //             })
    //         })
    //     },
    // },
    {
        label: '删除',
        type: 'danger',
        link: true,
        permission: ['plan:plan:remove'], // 权限控制：使用 v-hasPermi 指令控制按钮显示
        handler: (row) => {
            proxy.$modal.confirm('是否确认删除该计划？').then(async () => {
                const result = await delPlanAPI({
                    planManagementId: row.planManagementId,
                })
                if (result.code === 200) {
                    proxy.$modal.msgSuccess('删除成功')
                    comTableRef.value?.refresh()
                }
            })
        },
    },
]

// 新增
const onHandleAdd = () => {
    editId.value = null
    dialogConfig.outerTitle = '新增计划'
    dialogConfig.outerVisible = true
    addAndEditForm.value = getInitFormData()
    nextTick(() => {
        formRef.value?.clearValidate()
    })
}

// 取消
const onHandleCancel = () => {
    dialogConfig.outerVisible = false
}

// 保存
const onHandleSave = async () => {
    try {
        // 3. 调用子组件暴露的 validate 方法
        await formRef.value.validate()

        const API = editId.value ? updatePlanAPI : addPlanAPI
        const params = JSON.parse(JSON.stringify(addAndEditForm.value))
        editId.value ? (params.planManagementId = editId.value) : null
        const result = await API(params)
        if (result.code === 200) {
            proxy.$modal.msgSuccess(editId.value ? '编辑成功' : '新增成功')
            dialogConfig.outerVisible = false
            comTableRef.value?.refresh()
        }
    } catch (error) {
        return Promise.reject(error)
    }
}

// 导入计划
const onHandleImport = () => {
    uploadDialogConfig.outerTitle = '计划导入'
    uploadDialogConfig.outerVisible = true
    upload.selectedFile = null
    upload.updateSupport = 0
}

// 关闭导入弹框
const onCloseUploadDialog = () => {
    uploadDialogConfig.outerVisible = false
    upload.selectedFile = null
    upload.isUploading = false
    if (uploadRef.value) {
        uploadRef.value.clearFiles()
    }
}

// 文件上传中处理
const handleFileUploadProgress = (event, file, fileList) => {
    upload.isUploading = true
}

// 文件选择处理
const handleFileChange = (file, fileList) => {
    upload.selectedFile = file
}

// 文件删除处理
const handleFileRemove = (file, fileList) => {
    upload.selectedFile = null
}

// 文件上传成功处理
const handleFileSuccess = (response, file, fileList) => {
    uploadDialogConfig.outerVisible = false
    upload.isUploading = false
    uploadRef.value?.handleRemove(file)
    proxy.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
            response.msg +
            '</div>',
        '导入结果',
        { dangerouslyUseHTMLString: true },
    )
    comTableRef.value?.refresh()
}

// 提交上传文件
const submitFileForm = () => {
    const file = upload.selectedFile
    if (
        !file ||
        file.length === 0 ||
        (!file.name.toLowerCase().endsWith('.xls') && !file.name.toLowerCase().endsWith('.xlsx'))
    ) {
        proxy.$modal.msgError('请选择后缀为 "xls"或"xlsx"的文件。')
        return
    }
    uploadRef.value?.submit()
}

// 模板下载
const onHandleDownloadTemplate = () => {
    proxy.download('/planManagement/downloadTeamExcel', {}, `计划模板.xlsx`)
}

// 关闭弹框统一处理
const onCloseDialogOuter = (visible) => {
    dialogConfig.outerVisible = visible
    if (!visible) {
        formRef.value?.resetFields()
    }
}
</script>
