<template>
    <el-dialog
        v-model="visible"
        title="选择用户"
        width="800px"
        :close-on-click-modal="false"
        @close="visible = false"
        style="--el-dialog-padding-primary: 0"
    >
        <div class="flex items-start">
            <div class="flex-1">
                <div class="mb-4 text-center font-bold">组织架构</div>
                <div class="h-[400px] overflow-auto">
					<el-scrollbar>
						<query-tree :placeholder="$t('common.queryDeptTip')" :query="deptData.queryList" @node-click="handleNodeClick">
							<!-- 没有数据权限提示 -->
							<template #default="{ node, data }">
								<el-tooltip v-if="data.isLock" class="item" effect="dark" :content="$t('sysuser.noDataScopeTip')" placement="right-start">
									<span
										>{{ node.label }}
										<SvgIcon name="ele-Lock" />
									</span>
								</el-tooltip>
								<span v-if="!data.isLock">{{ node.label }}</span>
							</template>
						</query-tree>
					</el-scrollbar>
                </div>
            </div>
            <div class="flex-1 ml-4">
                <div class="mb-4 text-center font-bold">请选择用户</div>
                <div class="h-[400px] overflow-auto">
                    <el-checkbox
                        v-for="user of userList"
                        :key="user.userId"
                        class="block"
                        :label="user.name"
                        :model-value="checkedUserList.some(item => item.userId === user.userId)"
                        @change="handleCheck(user)"
                    />
                    <div class="text-center" v-loading="userLoading">
                        <el-button type="primary" link @click="loadNextPage">
                            {{ hasMore ? '加载更多' : '没有更多了' }}
                        </el-button>
                    </div>
                </div>
            </div>
            <div class="flex-1 ml-4">
                <div class="mb-4 text-center font-bold">已选用户</div>
                <div class="h-[400px] overflow-auto">
                    <el-checkbox
                        v-for="user of checkedUserList"
                        :key="user.userId"
                        class="block"
                        :label="user.name"
                        :model-value="checkedUserList.some(item => item.userId === user.userId)"
                        @change="handleCheck(user)"
                    />
                </div>
            </div>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="visible = false">取消</el-button>
                <el-button type="primary" @click="handleOk">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { deptTree } from '/@/api/admin/dept'
import { pageList } from '/@/api/admin/user'

const emit = defineEmits(['ok'])
const visible = defineModel<boolean>('visible')
const props = defineProps({
    multiple: {
        type: Boolean,
        default: false
    }
})


// 动态加载组件
const QueryTree = defineAsyncComponent(() => import('/@/components/QueryTree/index.vue'));

// 部门树使用的数据
const deptData = reactive({
	queryList: async (name: String) => {
		const res = await deptTree({
			deptName: name,
		});
        return res.data
	},
});

const selectedDept = ref<any>(null)
const handleNodeClick = (e: any) => {
    selectedDept.value = e
    pagination.current = 1
    fetchUserList()
}

// 获取部门用户
const pagination = reactive({
    current: 1,
    size: 10,
    total: 0
})
const userList = ref<any[]>([])
const userLoading = ref<boolean>(false)
const fetchUserList = async () => {
    // if (!selectedDept.value || userLoading.value) return
    userLoading.value = true
    try {
        const params = {
            current: pagination.current,
            size: pagination.size,
            deptId: selectedDept.value?.id,
            // username: '',
            // phone: ''
        }
        const res = await pageList(params)
        const records = res.data?.records || []
        pagination.total = res.data?.total || 0
        if (pagination.current === 1) {
            userList.value = records
        } else {
            userList.value = userList.value.concat(records)
        }
    } finally {
        userLoading.value = false
    }
}

const hasMore = computed(() => {
    return userList.value.length < pagination.total
})

const loadNextPage = () => {
    if (!hasMore.value) return
    pagination.current += 1
    fetchUserList()
}

// 选择用户
const checkedUserList = ref<any[]>([])
const handleCheck = (user: any) => {
    if (checkedUserList.value.some(item => item.userId === user.userId)) {
        checkedUserList.value = checkedUserList.value.filter(item => item.userId !== user.userId)
    } else {
        // 单选多选逻辑判断
        if (props.multiple) {
            checkedUserList.value.push(user)
        } else {
            checkedUserList.value = [user]
        }
    }
}

// 确定选择
const handleOk = () => {
    emit('ok', props.multiple ? checkedUserList.value : checkedUserList.value[0])
    visible.value = false
}

onMounted(() => {
    fetchUserList()
})
</script>
