<template>
	<div class="system-enterprises-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<el-form :model="state.queryParams" ref="ruleFormRef" inline @submit.native.prevent :disabled="state.loading">
				<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>
					<el-button type="primary" @click="handleQuery" :loading="state.loading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
					<el-button @click="resetQuery(ruleFormRef)" class="default-button" :loading="state.loading">
						<SvgIcon name="ele-Refresh" class="mr5" />重置
					</el-button>
				</el-form-item>
			</el-form>
			<vxe-toolbar
				ref="toolbarRef"
				:loading="state.loading"
				custom
				:refresh="{
					queryMethod: handleQuery,
				}"
			>
				<template #buttons>
					<el-button type="primary" @click="onAdd('')" v-auth="'system:enterprises:add'">
						<SvgIcon name="ele-Plus" class="mr5" /> 新增企业专员
					</el-button>
					<el-button type="danger" @click="onDelete" v-auth="'system:enterprises:delete'" :loading="state.loading" :disabled="disabled">
						<SvgIcon name="ele-Delete" class="mr5" />删除
					</el-button>
				</template>
			</vxe-toolbar>
			<div style="overflow: hidden; width: 100%; height: 100%; flex: 1">
				<vxe-table
					:loading="state.loading"
					:data="list"
					:column-config="{ resizable: true, useKey: true }"
					:row-config="{ isCurrent: true, isHover: true, useKey: true, height: 36 }"
					ref="tableRef"
					height="auto"
					auto-resize
					show-overflow
					:scrollY="{ enabled: true, gt: 0 }"
					id="systemEnterprises"
					:custom-config="{ storage: true }"
					showHeaderOverflow
					:tree-config="{
						childrenField: 'children',
						transform: true,
						rowField: 'id',
						parentField: 'parentId',
					}"
					@checkbox-change="selectChangeEvent"
					@checkbox-all="selectAllChangeEvent"
				>
					<vxe-column type="checkbox" tree-node width="100"> </vxe-column>
					<vxe-column field="name" title="用户名">
						<template #default="{ row }">
							<span v-html="row.name"></span>
						</template>
					</vxe-column>
					<vxe-column field="userName" title="账号">
						<template #default="{ row }">
							<span v-html="row.userName"></span>
						</template>
					</vxe-column>
					<vxe-column field="phoneNo" title="手机号">
						<template #default="{ row }">
							<span v-html="row.phoneNo"></span>
						</template>
					</vxe-column>
					<vxe-column title="操作" fixed="right" width="90" align="center">
						<template #default="{ row }">
							<el-button link type="primary" @click="onAdd(row)" title="新增" v-auth="'system:enterprises:add'"> 新增 </el-button>
						</template>
					</vxe-column>
				</vxe-table>
			</div>
		</div>
		<enterprise-add ref="enterpriseAddRef" @updateList="queryList" />
	</div>
</template>
<script lang="tsx" setup name="systemEnterprises">
import { computed, defineAsyncComponent, nextTick, onMounted, reactive, ref } from 'vue';
import type { FormInstance } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import { baseData } from '@/api/system/organize';
import { throttle } from '@/utils/tools';
import XEUtils from 'xe-utils';
import { batchDeleteEnterprises, getEnterprisesList } from '@/api/system/enterprises';

// 引入组件
const EnterpriseAdd = defineAsyncComponent(() => import('@/views/system/enterprises/components/Enterprises-add.vue')); // 新增企业专员

// 定义变量内容
const state = reactive<any>({
	loading: false, // 加载状态
	queryParams: {
		keyword: null, // 关键字
	},
	orgType: [], // 部门类别
	areas: [], // 区域
});
const ruleFormRef = ref<RefType>(); // 搜索表单ref

/** 搜索按钮操作 节流操作 */
const handleQuery = throttle(() => {
	queryList();
}, 300);
/** 重置按钮操作 */
const resetQuery = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	queryList();
}, 300);
// 打开新增
const enterpriseAddRef = ref<RefType>(); // 新增
const onAdd = (row?: any) => {
	enterpriseAddRef.value.openDialog(row.id);
};
// 删除选中的
const onDelete = () => {
	const ids = checkedTable.value.map((item) => item.id);
	ElMessageBox.confirm(`此操作将永久删除选择中的企业专员, 是否继续?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			batchDeleteEnterprises(ids).then(() => {
				ElMessage.success('删除成功');
				queryList();
			});
		})
		.catch(() => {});
};
// 获取所有部门结构
const tableData = ref<EmptyArrayType>([]);
const list = ref<any[]>([]);
const queryList = async () => {
	state.loading = true;
	try {
		const { result } = await getEnterprisesList();
		tableData.value = result ?? [];
		tableRef.value?.clearCheckboxRow();
		checkedTable.value = [];
		const filterVal = XEUtils.toValueString(state.queryParams.keyword)?.trim().toLowerCase();
		if (filterVal) {
			const filterRE = new RegExp(filterVal, 'gi');
			const options = { children: 'children' };
			const searchProps = ['account', 'phoneNo', 'name'];
			// 搜索为克隆数据，不会污染源数据
			const rest = XEUtils.searchTree(
				tableData.value,
				(item) => searchProps.some((key) => String(item[key]).toLowerCase().indexOf(filterVal) > -1),
				options
			);
			XEUtils.eachTree(
				rest,
				(item) => {
					searchProps.forEach((key) => {
						item[key] = String(item[key]).replace(filterRE, (match) => `<span class="keyword-highlight">${match}</span>`);
					});
				},
				options
			);
			list.value = rest;
			list.value = XEUtils.toTreeArray(list.value);
			await nextTick(() => {
				// 搜索之后默认展开所有子节点
				if (tableRef.value) {
					tableRef.value.setAllTreeExpand(true);
				}
			});
		} else {
			list.value = tableData.value;
			list.value = XEUtils.toTreeArray(list.value);
		}
		state.loading = false;
	} catch (error) {
		console.log(error);
		state.loading = false;
	}
};
const getBaseData = async () => {
	try {
		const { result } = await baseData();
		state.orgType = result.orgTypeOptions; // 部门类别
		state.areas = result.areas; // 区域
	} catch (error) {
		console.log(error);
	}
};
const checkedTable = ref<EmptyArrayType>([]);
const selectChangeEvent = () => {
	if (tableRef.value) {
		checkedTable.value = tableRef.value.getCheckboxRecords();
	}
};
const selectAllChangeEvent = () => {
	if (tableRef.value) {
		checkedTable.value = tableRef.value.getCheckboxRecords();
	}
};
const disabled = computed(() => {
	return !Boolean(checkedTable.value.length);
});
const toolbarRef = ref<RefType>();
const tableRef = ref<RefType>();
// 页面加载时
onMounted(() => {
	queryList();
	getBaseData();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
});
</script>
