<template>
    <div class="app-container">
        <!-- 人员管理 -->
        <ComTable
            ref="comTableRef"
            :form-columns="formColumns"
            :table-columns="tableColumns"
            :load-data="listPersonAPI"
            :show-toolbar="true"
            :show-action="true"
            :action-columns="actionColumns"
        >
            <template #toolbar>
                <ComButton
                    type="primary"
                    icon="Plus"
                    @click="onHandleAdd"
                    v-hasPermi="['person:person:add']"
                >
                    新建人员
                </ComButton>

                <ComButton
                    pain
                    type="info"
                    icon="Upload"
                    @click="onHandleImport"
                    v-hasPermi="['person:person:import']"
                >
                    导入人员
                </ComButton>
            </template>
            <template #longTermSecondment="{ row }">
                <el-switch
                    active-value="1"
                    inactive-value="0"
                    :model-value="getLongTermSecondmentValue(row)"
                    @change="onHandleLongTermSecondmentChange($event, row)"
                />
            </template>
        </ComTable>

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

                <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="Person">
import { ref, nextTick, getCurrentInstance, computed } from 'vue'
import {
    listPersonAPI,
    addPersonAPI,
    updatePersonAPI,
    delPersonAPI,
} from '@/api/personManage/person.js'
import {
    getInspectionStationSelectAPI,
    getPersonNatureAndCategoryAndPositionSelectAPI,
} from '@/api/common.js'
import { useOptions } from '@/hooks/useOptions'
import { bus, BUS_EVENTS } from '@/utils/bus'
import { getToken } from '@/utils/auth'
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'
import CryptoUtil from '../../../api/crypto.js'

const { tableColumns, dialogConfig, buildFormColumns } = config
const { proxy } = getCurrentInstance()

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

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

// 人员导入弹框配置
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 + '/personnel/importPersonnel',
    selectedFile: null,
})

const { options: allPositionAndInspectionStationOptions } = useOptions(
    'allPositionAndInspectionStationOptions',
    getInspectionStationSelectAPI,
    {},
)

const { options: positionOptions } = useOptions(
    'positionOptions',
    getPersonNatureAndCategoryAndPositionSelectAPI,
    { category: 2 },
)
const { options: natureOptions } = useOptions(
    'personNatureOptions',
    getPersonNatureAndCategoryAndPositionSelectAPI,
    { category: 1 },
)
const { options: categoryOptions } = useOptions(
    'personCategoryOptions',
    getPersonNatureAndCategoryAndPositionSelectAPI,
    { category: 0 },
)

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

// 1. 定义初始表单数据函数（优雅重置）——字段与表单保持同步
const getInitFormData = () => ({
    inspectionStationId: null, // 人员所属
    name: '', // 姓名
    sex: 1, // 性别：1 男，0 女（与表单单选保持一致）
    phone: '', // 电话
    positionId: null, // 岗位
    personnelNatureId: null, // 人员性质
    personnelClassificationId: null, // 人员分类
    longTermSecondment: 0, // 是否长期借调
})

const addAndEditForm = ref(getInitFormData())

const actionColumns = [
    {
        label: '编辑',
        type: 'primary',
        link: true,
        permission: ['person:person:edit'], // 权限控制：使用 v-hasPermi 指令控制按钮显示
        handler: (row) => {
            editId.value = row.id
            dialogConfig.outerTitle = '编辑人员'
            dialogConfig.outerVisible = true
            // 2. 使用 nextTick 确保弹框和子组件挂载后再回显数据
            nextTick(() => {
                const {
                    inspectionStationId,
                    name,
                    phone,
                    sex,
                    positionId,
                    personnelNatureId,
                    personnelClassificationId,
                    longTermSecondment,
                } = row
                Object.assign(addAndEditForm.value, {
                    inspectionStationId: inspectionStationId + '',
                    name,
                    phone: CryptoUtil.decrypt(phone),
                    sex: sex * 1,
                    positionId: positionId + '',
                    personnelNatureId: personnelNatureId + '',
                    personnelClassificationId: personnelClassificationId + '',
                    longTermSecondment,
                })
            })
        },
    },
    {
        label: '删除',
        type: 'danger',
        link: true,
        permission: ['person:person:remove'], // 权限控制：使用 v-hasPermi 指令控制按钮显示
        handler: (row) => {
            proxy.$modal.confirm('是否确认删除该人员？').then(async () => {
                const result = await delPersonAPI({ id: row.id })
                if (result.code === 200) {
                    proxy.$modal.msgSuccess('删除成功')
                    comTableRef.value?.refresh()
                    bus.emit(BUS_EVENTS.REFRESH_OPTIONS, 'personnelCommonOptions')
                }
            })
        },
    },
]

// 新增
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 ? updatePersonAPI : addPersonAPI
        const params = JSON.parse(JSON.stringify(addAndEditForm.value))
        editId.value ? (params.id = editId.value) : null
        const result = await API(params)
        if (result.code === 200) {
            proxy.$modal.msgSuccess(editId.value ? '编辑成功' : '新增成功')
            dialogConfig.outerVisible = false
            comTableRef.value?.refresh()
            bus.emit(BUS_EVENTS.REFRESH_OPTIONS, 'personnelCommonOptions')
        }
    } catch (error) {
        return Promise.reject(error)
    }
}

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

// 获取 longTermSecondment 的值，统一转换为字符串格式
const getLongTermSecondmentValue = (row) => {
    const value = row.longTermSecondment
    if (value === null || value === undefined) {
        return '0'
    }
    // 如果是数字，转换为字符串；如果已经是字符串，直接返回
    return String(value)
}

// 是否长期借调
const onHandleLongTermSecondmentChange = (value, row) => {
    // 更新 row 数据，保持与 switch 组件的值同步
    row.longTermSecondment = value

    // 组装参数：将字符串转换为数字（'1' -> 1, '0' -> 0）
    const params = {
        id: row.id,
        longTermSecondment: value === '1' ? 1 : 0,
    }

    updatePersonAPI(params).then((res) => {
        if (res.code === 200) {
            proxy.$modal.msgSuccess('更新成功')
            comTableRef.value?.refresh()
        }
    })
}

// 导入人员
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('/personnel/downloadPersonnelExcel', {}, `人员模板.xlsx`)
}
</script>
