<template>
    <el-dialog v-model="visible" title="选择人员" width="650px" @before-close="handleClose">
        <div style="width:600px">
            <el-table ref="multipleUserRef" :data="tableData" height="600" @selection-change="handleSelectionChange"
                @row-click="changeChoose">
                <!-- 复选框列 -->
                <el-table-column type="selection" width="85" :reserve-selection="true" />
                <!-- 序号列 -->
                <el-table-column label="序号" type="index" width="85" align="center" />

                <el-table-column prop="cName" label="姓名" />

                <!-- <el-table-column prop="dept" label="部门" /> -->
            </el-table>
        </div>

        <template #footer>
            <el-button type="primary" @click="handleConfirm">确定</el-button>
            <el-button @click="handleClose">取消</el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, watch, nextTick, onMounted } from 'vue'

const props = defineProps({
    /** 列表可用驾驶员 id */
    allIds: {
        type: String,
    },
    /** 列表可用驾驶员 name */
    allNames: {
        type: String,
    },
    /** 已选用户ID */
    ids: {
        type: String,
        default: () => ''
    },
    /** 已选用户name */
    cName: {  // 已选用户名字
        type: String,
        default: () => ''
    }
})

const emits = defineEmits(['update:visible', 'update:ids', 'update:cName'])
/** 表格实例 */
const multipleUserRef = ref()
const visible = ref(true) // 默认显示
/** 表格数据 */
const tableData = ref([])

/**当前选中人员 */
const selectedUsers = ref([])

// 处理选中变化
const handleSelectionChange = (selection) => {
    selectedUsers.value = selection || []

}
const changeChoose = (row) => {
    multipleUserRef.value.toggleRowSelection(row);
}
// 确定选择
const handleConfirm = () => {
    const idsString = selectedUsers.value.map(user => user.id).toString()
    const cNameStr = selectedUsers.value.map(user => user.cName).toString()
    emits('update:ids', idsString)
    emits('update:cName', cNameStr)
    emits('ok', selectedUsers.value)
    emits('close', { from: 'ok' })
}

// 关闭弹窗
const handleClose = () => {
    emits('close', true)
}
/** 初始化表格 */
const initTableData = () => {
    let allIds = typeof props.allIds === 'string' ? props.allIds : ''
    allIds = allIds?.length ? allIds.split(',') : []
    let allNames = typeof props.allNames === 'string' ? props.allNames : ''
    allNames = allNames?.length ? props.allNames.split(',') : []
    const tableData = allIds.map((item, index) => {
        return { id: item, cName: allNames[index] }
    })
    return tableData
}
onMounted(() => {
    tableData.value = initTableData()
    nextTick(() => {
        // 回显
        tableData.value.forEach(item => {
            if (item.id && props.ids.includes(item.id) && multipleUserRef.value) {
                multipleUserRef.value.toggleRowSelection(item, true);
            }
        })
    })
});
</script>

<style lang="scss" scoped>
/* 你的样式代码 */
</style>