<template>
	<el-dialog title="选择人员" v-model="dialogVisible" draggable append-to-body destroy-on-close width="800px">
		<el-form :model="state.queryParams" ref="ruleDialogFormRef" inline @submit.native.prevent :disabled="state.loading" class="ruleDialogForm">
			<!-- <el-form-item label="部门" prop="OrgCode">
                <el-tree-select
                    v-model="state.queryParams.OrgCode"
                    :data="state.orgData"
                    node-key="id"
                    :props="{ label: 'name' }"
                    collapse-tags
                    collapse-tags-tooltip
                    :render-after-expand="false"
                    style="width: 200px;"
                    @change="handleQuery"
                />
            </el-form-item> -->
            <el-form-item label="关键词" prop="Keyword">
                <el-input v-model="state.queryParams.Keyword" placeholder="姓名/电话/账号" clearable style="width: 150px"></el-input>
            </el-form-item>
			<el-form-item>
				<el-button type="primary" @click="handleQuery" :loading="state.loading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
				<el-button @click="resetQuery(ruleDialogFormRef)" class="default-button"> <SvgIcon name="ele-Refresh" class="mr5" />重置 </el-button>
			</el-form-item>
		</el-form>
		<vxe-table
			border
			:loading="state.loading"
			:data="state.tableData"
			:sort-config="{ remote: true }"
			:column-config="{ resizable: true }"
			:row-config="{ isHover: true, height: 30, keyField: 'id' }"
			ref="tableRef"
			height="300px"
			show-overflow
			:scrollY="{ enabled: true, gt: 100 }"
			@checkbox-change="checkboxChangeEvent"
			:checkbox-config="{ highlight: true, showHeader: false }"
		>
			>
			<vxe-column type="checkbox" fixed="left" width="70" align="center"></vxe-column>
			<vxe-column field="name" title="姓名" width="120"></vxe-column>
			<vxe-column field="userName" title="账号" width="120"></vxe-column>
			<vxe-column field="phoneNo" title="电话号码" width="120"></vxe-column>
            <vxe-column field="fullOrgName" title="部门" min-width="100"></vxe-column>
		</vxe-table>
		<pagination
			@pagination="queryList"
			:total="state.total"
			v-model:current-page="state.queryParams.PageIndex"
			v-model:page-size="state.queryParams.PageSize"
			:disabled="state.loading"
		/>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="dialogVisible = false" class="default-button">取 消</el-button>
				<el-button type="primary" @click="onSubmit" :disabled="!state.tableCheckbox">保 存</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup>
import { defineAsyncComponent, reactive, ref } from 'vue';
import { FormInstance } from 'element-plus';
import { formatDate } from '@/utils/formatTime';
import other from '@/utils/other';
import { getCanUseOrgByUser, getUserListPaged } from '@/api/system/user';

const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页

// 定义子组件向父组件传值/事件
const emit = defineEmits(['choose']);

// 定义变量内容
const state = reactive({
	tableData: [] as any[], // 表格数据
	total: 0, // 总条数
	loading: false, // 加载
	queryParams: {
		PageIndex: 1, // 当前页
		PageSize: 20, // 每页条数
		OrgCode: null, // 部门id
        Keyword: null, // 关键词
	},
	tableCheckbox: [] as any[], // 已选择的人员
	orgData: [], // 部门数据
});
const ruleDialogFormRef = ref<FormInstance>(); // 表单
const dialogVisible = ref(false); // 弹窗

// 获取部门数据
const getOrgData = async () => {
	try {
		const { result } = await getCanUseOrgByUser();
		state.orgData = result ?? [];
	} catch (error) {
	}
};
// 打开弹窗
const openDialog = async (selData: any[]) => {
	dialogVisible.value = true;
	try {
        if (selData) {
			state.tableCheckbox = other.deepClone(selData);
		} else {
			state.tableCheckbox = [];
		}
	    // getOrgData();
		queryList();
	} catch (error) {
		console.log(error);
		state.loading = false;
	}
};
/** 搜索按钮操作 */
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
const tableRef = ref<RefType>();
const queryList = () => {
	state.loading = true;
	getUserListPaged(state.queryParams)
		.then((res: any) => {
			state.tableData = res.result?.items ?? [];
			state.total = res.result?.pagination.totalCount ?? 0;
            const rows = [] as any[];
            state.tableCheckbox.forEach(item => {
                rows.push(state.tableData.find(it => it.id === item.userId));
            })
            tableRef.value.setCheckboxRow(rows, true);
			state.loading = false;
		})
		.catch(() => {
			state.loading = false;
		});
};
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	handleQuery();
};
// 单个复选框点击
const checkboxChangeEvent = ({row}) => {
    let blog = 'add';
    state.tableCheckbox.forEach(item => {
        if(item.userId == row.id){
            blog = 'delete'
        }
    });
    if (blog == 'add'){
        const rowObj = other.deepClone(row);
        rowObj.userId = rowObj.id;
        Reflect.deleteProperty(rowObj, 'id');
        state.tableCheckbox.push(rowObj)
    }else {
        state.tableCheckbox = state.tableCheckbox.filter(it => it.userId !== row.id )
    }
}
// 关闭弹窗
const closeDialog = () => {
	dialogVisible.value = false;
};
// 选择试题
const onSubmit = () => {
	emit('choose', state.tableCheckbox);
	closeDialog();
};
//暴漏变量和方法
defineExpose({ closeDialog, openDialog });
</script>
<style>
.el-form--inline.ruleDialogForm .el-form-item .el-select {
    min-width: 100px;
}
</style>
