<template>
	<div class="system-dict-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<el-row :gutter="20" class="h100">
				<!-- 左侧组织树 -->
				<el-col :xs="6" :sm="6" :md="6" :lg="4" :xl="4" class="orgTree">
					<el-scrollbar height="100%" class="pr10">
						<template v-if="state.dicTypeList.length">
							<el-tree
								v-loading="state.loading"
								:data="state.dicTypeList"
								highlight-current
								:expand-on-click-node="false"
								node-key="id"
								:props="{ children: 'children', label: 'dicTypeName' }"
								@node-click="handleNodeClick"
								:current-node-key="state.dicTypeList[0].id"
								ref="treRef"
								style="min-width: 100%; display: inline-block"
							>
							</el-tree>
						</template>
						<template v-else>
							<Empty description="暂无字典类型" />
						</template>
					</el-scrollbar>
				</el-col>
				<!-- 右侧表格 -->
				<el-col :xs="18" :sm="18" :md="18" :lg="20" :xl="20" class="rightContent">
					<el-scrollbar class="pr10">
						<div class="flex-column">
							<div class="flex-between mb10">
								<el-form :model="state.queryParams" ref="ruleFormRef" :inline="true" @submit.native.prevent>
									<el-form-item label="关键字" prop="keyword" class="mb0">
										<el-input v-model="state.queryParams.keyword" placeholder="字典值名称/字典值" clearable @keyup.enter="handleQuery" />
									</el-form-item>
									<el-form-item class="mb0">
										<el-button type="primary" @click="handleQuery" :loading="state.tableLoading" v-waves>
											<SvgIcon name="ele-Search" class="mr5" />查询
										</el-button>
										<el-button @click="resetQuery(ruleFormRef)" v-waves class="default-button" :loading="state.tableLoading">
											<SvgIcon name="ele-Refresh" class="mr5" />重置
										</el-button>
									</el-form-item>
								</el-form>
								<div>
									<el-button type="primary" @click="expand"
										><SvgIcon
											name="ele-ArrowDownBold"
											style="transition: transform var(--el-transition-duration)"
											:style="state.isExpand ? 'transform: none' : 'transform: rotateZ(180deg)'"
											class="mr5"
										/>
										{{ state.isExpand ? '收起' : '展开' }}</el-button
									>
									<el-button type="primary" @click="onOpenAddUser" v-auth="'system:dict:add'">
										<SvgIcon name="ele-Plus" class="mr5" />新增
									</el-button>
									<!-- <el-button type="primary" @click="onRowDel" v-waves v-auth="'100104'">
                                    <SvgIcon name="ele-Delete" class="mr5" />注销
                                </el-button> -->
									<!-- <el-button type="primary" v-waves @click="onExportTable">
										<SvgIcon name="iconfont icon-daochu" class="mr5" />导出
									</el-button> -->
								</div>
							</div>
							<!-- 表格 -->
							<el-auto-resizer class="table" v-loading="state.tableLoading">
								<template #default="{ height, width }">
									<el-table-v2
										v-model:expanded-row-keys="state.expandedRowKeys"
										:columns="state.columns"
										:data="state.tableData"
										expand-column-key="dicDataName"
										fixed
										:width="width"
										:height="height"
									>
										<template #empty>
											<Empty />
										</template>
									</el-table-v2>
								</template>
							</el-auto-resizer>
						</div>
					</el-scrollbar>
				</el-col>
			</el-row>
		</div>

		<dict-add ref="dictAddRef" @updateList="handleQuery" />
		<dict-edit ref="dickEditRef" @updateList="handleQuery" />
	</div>
</template>
<script lang="ts" setup name="systemDict">
import { defineAsyncComponent, ref, reactive, onMounted, h, watch } from 'vue';
import { ElButton } from 'element-plus';
import type { FormInstance } from 'element-plus';
import { ElMessage } from 'element-plus';
import { formatDate } from '/@/utils/formatTime';
import { auth } from '/@/utils/authFunction';
import other from '/@/utils/other';
import { throttle } from '/@/utils/tools';
import { dicTypeList, getDataByTypeId } from '/@/api/system/dict';

// 引入组件
const DictAdd = defineAsyncComponent(() => import('/@/views/system/config/dict/component/Dict-add.vue'));
const DictEdit = defineAsyncComponent(() => import('/@/views/system/config/dict/component/Dict-edit.vue'));

// 定义变量内容
const state = reactive<any>({
	queryParams: {
		keyword: '',
		typeid: '',
		loading: false,
	},
	tableData: [],
	staticArr: [],
	total: 0,
	loading: false,
	tableLoading: false,
	dicTypeList: [],
	options: [],
	columns: [
		{
			key: 'dicDataName',
			dataKey: 'dicDataName',
			title: '字典名称',
			width: 600,
		},
		{
			key: 'dicDataValue',
			dataKey: 'dicDataValue',
			title: '字典值',
			width: 150,
		},
		{
			key: 'dicTypeCode',
			dataKey: 'dicTypeCode',
			title: '字典code',
			width: 170,
		},
		{
			key: 'creationTime',
			dataKey: 'creationTime',
			title: '更新时间',
			width: 170,
			cellRenderer: (data: any) => h('span', {}, { default: () => formatDate(new Date(data.rowData.creationTime), 'YYYY-mm-dd HH-MM') }),
		},
		{
			key: 'handle',
			title: '操作',
			width: 70,
			fixed: 'right',
			align: 'center',
			cellRenderer: (data: any) => {
				if (auth('system:dict:query')) {
					// 权限判断
					return h(
						ElButton,
						{
							onClick: () => onOpenEditUser(data),
							type: 'primary',
							link: true,
							title: '修改字典信息',
						},
						{ default: () => '修改' }
					);
				}
			},
		},
	],
	expandedRowKeys: [],
	isExpand: false,
});
const dictAddRef = ref<RefType>(); //新增字典
const dickEditRef = ref<RefType>(); //修改字典
const treRef = ref<RefType>();
const ruleFormRef = ref<RefType>();
/** 搜索按钮操作 节流操作 */
const handleQuery = throttle(() => {
	if (state.queryParams.keyword) {
		state.tableLoading = true;
		state.expandedRowKeys = [];
		emptyArr = [];
		state.tableData = formatTable(other.deepClone(state.staticArr), state.queryParams.keyword);
		state.expandedRowKeys = getExpand(state.tableData);
		state.tableLoading = false;
	} else {
		getList();
	}
}, 1000);
const expand = () => {
	state.isExpand = !state.isExpand;
};
watch(
	() => state.isExpand,
	(old: Boolean) => {
		if (old) getAllIds(state.tableData);
		else state.expandedRowKeys = [];
	}
);
const getAllIds = (arr: any) => {
	if (!arr) return [];
	arr.forEach((v: any) => {
		if (v.children?.length) {
			getAllIds(v.children);
			state.expandedRowKeys.push(v.id);
		}
	});
};
// 获取字典类型列表
const getDictTypeList = () => {
	if (!auth('system:dict:type')) ElMessage.error('抱歉，您没有权限获取字典类型！');
	else {
		state.loading = true;
		dicTypeList()
			.then((res: any) => {
				state.dicTypeList = res?.result ?? [];
				state.queryParams.typeid = res?.result[0].id ?? '';
				getList();
				state.loading = false;
			})
			.catch(() => {
				state.loading = false;
			});
	}
};
/* 获取字典列表 */
const getList = () => {
	if (!auth('system:dict:query')) ElMessage.error('抱歉，您没有权限获取字典列表！');
	else {
		state.tableLoading = true;
		getDataByTypeId(state.queryParams)
			.then((response: any) => {
				state.tableData = response?.result ?? [];
				state.staticArr = response?.result ?? [];
				state.tableLoading = false;
			})
			.catch(() => {
				state.loading = false;
			});
	}
};
// 搜索
const formatTable = (list: any[], keyword: string) => {
	if (!list.length || !Array.isArray(list)) return [];
	let emptyArr: any[] = [];
	list.map((item) => {
		if (item.dicDataName.includes(keyword) || item.dicDataValue.includes(keyword)) {
			if (item.children && Array.isArray(item.children) && item.children.length > 0) {
				item.children = formatTable(item.children, keyword);
			}
			emptyArr.push(item);
		} else if (item.children && Array.isArray(item.children) && item.children.length > 0) {
			item.children = formatTable(item.children, keyword);
			if (item.children.length) {
				emptyArr.push(item);
			}
		}
	});
	return emptyArr;
};
let emptyArr: any[] = [];
const getExpand = (list: any[]) => {
	if (!list.length || !Array.isArray(list)) return [];
	list.map((item) => {
		if (item.children && Array.isArray(item.children) && item.children.length > 0) {
			getExpand(item.children);
		}
		emptyArr.push(item.id);
	});
	return emptyArr;
};
// 点击节点
const handleNodeClick = (data: any) => {
	state.queryParams.typeid = data.id;
	state.isExpand = false;
	state.expandedRowKeys = [];
	resetQuery(ruleFormRef.value);
};
// 打开新增字典弹窗
const onOpenAddUser = () => {
	dictAddRef.value.openDialog(state.queryParams.typeid);
};
// 打开修改字典弹窗
const onOpenEditUser = (row: any) => {
	dickEditRef.value.openDialog(row.rowData, state.tableData);
};
/** 重置按钮操作 */
const resetQuery = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	getList();
	state.expandedRowKeys = [];
	emptyArr = [];
}, 500);

// 删除字典
// const onRowDel = (row: any) => {
//     ElMessageBox.confirm(`此操作将永久删除账户名称：“${row.name}”，是否继续?`, '提示', {
//         confirmButtonText: '确认',
//         cancelButtonText: '取消',
//         draggable: true,
//         cancelButtonClass: 'default-button',
//         type: 'warning'
//     }).then(() => {
//         delUser(row.id).then(() => {
//             ElMessage.success('删除成功');
//             handleQuery();
//         });
//     }).catch(() => { });
// };
// 导出表格
// const onExportTable = () => {};
onMounted(() => {
	getDictTypeList();
});
</script>
<style lang="scss" scoped>
.system-dict-container {
	.orgTree {
		border-right: 1px solid var(--el-border-color);
		height: 100%;
	}

	.rightContent {
		height: 100%;
		.flex-column {
			display: flex;
			flex-direction: column;
			height: 100%;
			.table {
				flex: 1;
			}
		}
	}

	:deep(.el-tree-node__content) {
		height: 40px;
	}
}
</style>
