<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">新建人员</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="inspectionStationOptions"
                    :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>
    </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 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, dialogConfig, buildFormColumns } = config
const { proxy } = getCurrentInstance()

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

// 使用通用 Hook 获取下拉数据（带缓存和自动刷新）
const { options: inspectionStationOptions } = useOptions(
    'inspectionStationOptions',
    getInspectionStationSelectAPI,
    { category: 0 },
)
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,
        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,
                    sex: sex * 1,
                    positionId: positionId + '',
                    personnelNatureId: personnelNatureId + '',
                    personnelClassificationId: personnelClassificationId + '',
                    longTermSecondment,
                })
            })
        },
    },
    {
        label: '删除',
        type: 'danger',
        link: true,
        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()
        }
    })
}
</script>
