<template>
	<div class="system-user-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<splitpanes class="h100" Vertical>
				<pane min-size="16" max-size="25" size="16">
					<el-scrollbar ref="scrollBarRef" class="h100">
						<el-skeleton :loading="state.loading" animated :rows="10">
							<template #default>
								<v-tree-search
									:data="state.orgData"
									titleField="name"
									keyField="id"
									selectable
									searchPlaceholder="部门名称"
									@select="selectOrg"
									@unselect="unSelectOrg"
									ref="treeSearchRef"
								>
									<template #node="{ node }">
										<span>{{ node.name }}</span>
									</template>
								</v-tree-search>
							</template>
						</el-skeleton>
					</el-scrollbar>
				</pane>
				<pane class="h100" style="display: flex; flex-direction: column; flex: 1">
					<el-form :model="state.queryParams" ref="ruleFormRef" inline @submit.native.prevent>
						<el-form-item label="关键字" prop="Keyword">
							<el-input
								v-model="state.queryParams.Keyword"
								placeholder="姓名/电话号码/账号"
								clearable
								@keyup.enter="handleQuery"
								class="keyword-input"
							/>
						</el-form-item>
						<el-form-item label="角色" prop="Role">
							<el-select-v2
								v-model="state.queryParams.Role"
								filterable
								:options="state.roleOptions"
								:props="{
									label: 'displayName',
									value: 'id',
								}"
								placeholder="请选择角色"
								clearable
								@change="handleQuery"
							/>
						</el-form-item>
						<el-form-item>
							<el-button type="primary" @click="handleQuery" :loading="state.tableLoading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
							<el-button @click="resetQuery(ruleFormRef)" class="default-button" :loading="state.tableLoading">
								<SvgIcon name="ele-Refresh" class="mr5" />重置
							</el-button>
						</el-form-item>
					</el-form>
					<vxe-toolbar
						ref="toolbarRef"
						:loading="state.tableLoading"
						custom
						:refresh="{
							queryMethod: handleQuery,
						}"
					>
						<template #buttons>
							<el-button type="primary" @click="onOpenAddUser" v-auth="'system:user:add'" v-if="showAdd" :loading="state.tableLoading">
								<SvgIcon name="ele-Plus" class="mr5" />新增用户
							</el-button>
						</template>
					</vxe-toolbar>
					<div style="overflow: hidden; width: 100%; height: 100%; flex: 1">
						<vxe-table
							border
							:loading="state.tableLoading"
							:data="state.tableData"
							:column-config="{ resizable: true }"
							:row-config="{ isCurrent: true, isHover: true, height: 30, useKey: true }"
							ref="tableRef"
							height="auto"
							auto-resize
							show-overflow
							:print-config="{}"
							:scrollY="{ enabled: true, gt: 100 }"
							id="systemUser"
							:custom-config="{ storage: true }"
							showHeaderOverflow
						>
							<vxe-column field="name" title="姓名" width="120"></vxe-column>
							<vxe-column field="userName" title="账号" width="120"></vxe-column>
							<vxe-column field="fullOrgName" title="所属部门" width="140"></vxe-column>
							<vxe-column field="organization.orgTypeText" title="部门类别" width="110"></vxe-column>
							<vxe-column field="roleNames" title="角色" width="120"></vxe-column>
							<vxe-column field="phoneNo" title="电话号码" width="130"></vxe-column>
							<vxe-column field="staffNo" title="工号" width="120"></vxe-column>
							<vxe-column field="userTypeText" title="用户类型" width="120"></vxe-column>
							<vxe-column field="genderText" title="性别" width="120"></vxe-column>
							<vxe-column field="creationTime" title="创建时间" width="160">
								<template #default="{ row }">
									{{ formatDate(row.creationTime, 'YYYY-mm-dd HH:MM:SS') }}
								</template>
							</vxe-column>
							<vxe-column field="state" title="状态" width="140"></vxe-column>
							<vxe-column title="操作" fixed="right" width="230" align="center">
								<template #default="{ row }">
									<el-button link type="primary" @click="onOpenEditUser(row)" v-auth="'system:user:edit'" title="修改" v-if="!row.isDeleted">
										修改
									</el-button>
									<el-button link type="primary" @click="onUnlock(row)" v-auth="'system:user:unlock'" title="解锁" v-if="!row.isDeleted">
										解锁
									</el-button>
									<el-button link type="warning" @click="onRestPwd(row)" title="重置密码" v-auth="'system:user:resetPwd'" v-if="!row.isDeleted">
										重置密码
									</el-button>
									<el-button link type="danger" @click="onRowDel(row)" v-auth="'system:user:delete'" title="删除" v-if="!row.isDeleted">
										删除
									</el-button>
								</template>
							</vxe-column>
						</vxe-table>
					</div>
					<pagination
						@pagination="queryList"
						:total="state.total"
						v-model:current-page="state.queryParams.PageIndex"
						v-model:page-size="state.queryParams.PageSize"
						:disabled="state.tableLoading"
					/>
				</pane>
			</splitpanes>
		</div>
		<user-add
			ref="userAddRef"
			@updateList="queryList"
			:roles="state.roleOptions"
			:baseOrg="state.orgData"
			:baseData="state.baseData"
			:telsList="state.telsList"
			:telsListGroup="state.telsListGroup"
		/>
		<user-edit
			ref="userEditRef"
			@updateList="queryList"
			:roles="state.roleOptions"
			:baseOrg="state.orgData"
			:baseData="state.baseData"
			:telsList="state.telsList"
			:telsListGroup="state.telsListGroup"
		/>
	</div>
</template>

<script lang="tsx" setup name="systemUser">
import { computed, defineAsyncComponent, onActivated, onMounted, reactive, ref } from 'vue';
import type { FormInstance } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import { formatDate } from '@/utils/formatTime';
import { delUser, getBaseData, getCanUseOrgByUser, getRoles, getUserListPaged, restPwd, unlockUser } from '@/api/system/user';
import { Splitpanes, Pane } from 'splitpanes';
import 'splitpanes/dist/splitpanes.css';
import { getCallCenterGroupList, getCallCenterList } from '@/api/callCenter';
import { useThemeConfig } from '@/stores/themeConfig';
import { storeToRefs } from 'pinia';
import { extensionList } from '@/api/tels/extension';
import { VTreeSearch } from '@wsfe/vue-tree';

// 引入组件
const UserAdd = defineAsyncComponent(() => import('@/views/system/user/components/User-add.vue')); // 新增用户组件
const UserEdit = defineAsyncComponent(() => import('@/views/system/user/components/User-edit.vue')); // 修改用户组件
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页

// 定义变量内容
const state = reactive<any>({
	queryParams: {
		PageIndex: 1, // 当前页
		PageSize: 20, // 每页条数
		Keyword: null, // 关键字
		Role: null, // 角色id
		OrgCode: null, // 组织code
	},
	tableData: [], // 表格数据
	total: 0, // 总条数
	loading: false, // 加载状态
	tableLoading: false, // 表格加载状态
	orgData: [], // 组织结构数据
	roleOptions: [], // 角色数据
	baseData: [], // 基础数据
	telsList: [], // 分机数据
	telsListGroup: [], //分机组
});
const ruleFormRef = ref<FormInstance>(); //表单ref
//  在正式上线前 先隐藏用户和部门的新增
const showAdd = computed(() => {
	return !['ZiGong', 'LuZhou'].includes(import.meta.env.VITE_MODE_NAME);
});
/** 搜索按钮操作 节流操作 */
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
// 获取所有组织结构
const getOrgListApi = () => {
	state.loading = true;
	getCanUseOrgByUser()
		.then((res: any) => {
			state.orgData = res?.result ?? [];
			state.loading = false;
		})
		.catch(() => {
			state.loading = false;
		});
};
/** 获取用户列表 */
const queryList = () => {
	state.tableLoading = true;
	getUserListPaged(state.queryParams)
		.then((response: any) => {
			state.tableData = response?.result.items ?? [];
			state.total = response?.result.total;
			state.tableLoading = false;
		})
		.catch(() => {
			state.tableLoading = false;
		});
};
// 获取角色
const getRolesFn = () => {
	getRoles({ PageIndex: 1, PageSize: 999, IsDeleted: false }).then((res: any) => {
		state.roleOptions = res?.result.items ?? [];
	});
};
// 查询页面基础信息
const getBaseDataFn = () => {
	getBaseData().then((res: any) => {
		state.baseData = res?.result ?? [];
	});
};
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
// 获取分机列表
const getTelsListFn = async () => {
	let tels, telGroup;
	if (['ZiGong', 'LuZhou'].includes(themeConfig.value.appScope)) {
		[tels, telGroup] = await Promise.all([getCallCenterList(), getCallCenterGroupList()]);
	} else if (['YiBin'].includes(themeConfig.value.appScope)) {
		[tels] = await Promise.all([extensionList({ hasListen: false })]);
		tels.result = tels.result.map((item: any) => {
			return {
				...item,
				no: item.telNo,
			};
		});
	} else {
		[tels, telGroup] = await Promise.all([getCallCenterList(), getCallCenterGroupList()]);
	}
	state.telsList = tels?.result ?? [];
	state.telsListGroup = telGroup?.result ?? [];
};
// 点击部门
const selectOrg = (data: any) => {
	state.queryParams.OrgCode = data.id;
	queryList();
};
// 取消单选
const unSelectOrg = () => {
	state.queryParams.OrgCode = null;
	queryList();
};
// 打开新增用户弹窗
const userAddRef = ref<RefType>(); //新增用户
const onOpenAddUser = () => {
	userAddRef.value.openDialog();
};
/** 重置按钮操作 */
const treeSearchRef = ref<RefType>();
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	treeSearchRef.value.setSelected(state.queryParams.OrgCode, false); // 清空选择
	treeSearchRef.value.clearKeyword(); // 清空搜索关键词
	treeSearchRef.value.search(); // 搜索
	formEl.resetFields();
	state.queryParams.OrgCode = null;
	handleQuery();
	setTimeout(() => {
		treeSearchRef.value.setExpandAll(false); // 默认全部收起
	}, 300);
};
// 打开修改用户弹窗
const userEditRef = ref<RefType>(); //修改用户信息
const onOpenEditUser = (row: any) => {
	userEditRef.value.openDialog(row);
};
// 重置密码
const onRestPwd = (row: any) => {
	ElMessageBox.confirm(`此操作将：“${row.name}的密码重置为默认密码”，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			restPwd(row.id).then(() => {
				ElMessage.success('操作成功');
				queryList();
				state.queryParams.OrgCode = null;
				getOrgListApi();
			});
		})
		.catch(() => {});
};
// 删除用户
const onRowDel = (row: any) => {
	ElMessageBox.confirm(`此操作将永久删除账户名称：“${row.name}”，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		draggable: true,
		cancelButtonClass: 'default-button',
		type: 'warning',
	})
		.then(() => {
			delUser(row.id).then(() => {
				ElMessage.success('删除成功');
				queryList();
				state.queryParams.OrgCode = null;
				getOrgListApi();
			});
		})
		.catch(() => {});
};
// 解锁
const onUnlock = (row: any) => {
	ElMessageBox.confirm(`您确定要解锁：“${row.userName}”，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		draggable: true,
		cancelButtonClass: 'default-button',
		type: 'warning',
	})
		.then(() => {
			unlockUser(row.id).then(() => {
				ElMessage.success('解锁成功！');
				queryList();
				state.queryParams.OrgCode = null;
				getOrgListApi();
			});
		})
		.catch(() => {});
};
const tableRef = ref<RefType>();
const toolbarRef = ref<RefType>();
onMounted(() => {
	getRolesFn();
	getBaseDataFn();
	getTelsListFn();
	getOrgListApi();
	queryList();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
});
onActivated(()=>{
	treeSearchRef.value.scrollTo(state.queryParams.OrgCode); // 滚动
})
</script>