<template>
    <div class="app-container">
        <!-- 分组管理 -->
        <ComTable
            ref="comTableRef"
            :form-columns="formColumns"
            :table-columns="tableColumns"
            :load-data="listGroupAPI"
            :show-toolbar="true"
            :show-action="true"
            :action-columns="actionColumns"
        >
            <template #toolbar>
                <ComButton type="primary" icon="Plus" @click="onHandleAdd"> 新建分组 </ComButton>
            </template>
        </ComTable>

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

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

<script setup name="GroupManage">
import { ref, nextTick, getCurrentInstance, computed } from 'vue'
import {
    listGroupAPI,
    addGroupAPI,
    updateGroupAPI,
    delGroupAPI,
} from '@/api/basicManage/groupManage.js'
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)

// 根据配置构建搜索表单
const formColumns = computed(() => buildFormColumns())

// 定义初始表单数据函数（优雅重置）——字段与表单保持同步
const getInitFormData = () => ({
    groupName: '', // 分组名称
    workerList: [], // 组员ID列表
    remark: '', // 备注
})

const addAndEditForm = ref(getInitFormData())

// 操作列配置
const actionColumns = [
    {
        label: '编辑',
        type: 'primary',
        link: true,

        handler: (row) => {
            editId.value = row.id
            dialogConfig.outerTitle = '编辑分组'
            dialogConfig.outerVisible = true
            // 使用 nextTick 确保弹框和子组件挂载后再回显数据
            nextTick(() => {
                const { groupName, workerList, remark } = row
                // 从workerList中提取人员ID数组
                let workerIdList = []
                if (workerList && Array.isArray(workerList) && workerList.length > 0) {
                    workerIdList = workerList.map((worker) => worker.id).filter((id) => id != null)
                }
                Object.assign(addAndEditForm.value, {
                    groupName: groupName || '',
                    workerList: workerIdList,
                    remark: remark || '',
                })
            })
        },
    },
    {
        label: '删除',
        type: 'danger',
        link: true,

        handler: (row) => {
            proxy.$modal.confirm('是否确认删除该分组？').then(async () => {
                const result = await delGroupAPI({ id: row.id })
                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 {
        console.log(addAndEditForm.value)
        // 调用子组件暴露的 validate 方法

        await formRef.value.validate()
        const API = editId.value ? updateGroupAPI : addGroupAPI
        const params = JSON.parse(JSON.stringify(addAndEditForm.value))
        params.workerList = params.workerList.map((item) => {
            return { id: item }
        })
        if (editId.value) {
            params.id = editId.value
        }
        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 onCloseDialogOuter = (visible) => {
    dialogConfig.outerVisible = visible
    if (!visible) {
        formRef.value?.resetFields()
    }
}
</script>

<style lang="scss" scoped>
.common-btn-row {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 20px;
    padding: 0 20px 20px;
}
</style>

