<template>
	<div class="dictionarie-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="4" :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"
							>
							</el-tree>
						</template>
						<template v-else>
							<Empty description="暂无字典类型" />
						</template>
					</el-scrollbar>
				</el-col>
				<!-- 右侧表格 -->

				<el-col :xs="18" :sm="18" :md="20" :lg="20" :xl="20" class="rightContent">
					<el-scrollbar class="pr10">
						<div class="flex-column">
							<div class="flex-between mb20">
								<el-form :model="state.queryParams" ref="ruleFormRef" :inline="true" @submit.native.prevent>
									<el-form-item label="关键字" prop="keyword">
										<el-input v-model="state.queryParams.keyword" placeholder="字典值名称/字典值" clearable @keyup.enter="handleQuery" />
									</el-form-item>
									<el-form-item>
										<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">
											<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="'100603'"> <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="onImportTable">
										<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"
									>
									</el-table-v2>
								</template>
							</el-auto-resizer>
						</div>
					</el-scrollbar>
				</el-col>
			</el-row>
		</div>

		<Add ref="addRef" @updateList="handleQuery" />
		<Edit ref="editRef" @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 { storeToRefs } from 'pinia';
import { useUserInfo } from '/@/stores/userInfo';
import { ElMessage } from 'element-plus';
import { formatDate } from '/@/utils/formatTime';
import { throttle } from '/@/utils/tools';
import { dictypeList, getDataByTypeid } from '/@/api/system/dict';
import SvgIcon from '/@/views/system/menu/component/SvgIcon.vue';

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

// 定义变量内容
const state = reactive<any>({
	queryParams: {
		keyword: '',
		typeid: '',
		loading: false,
	},
	tableData: [],
	total: 0,
	loading: false,
	tableLoading: false,
	dictypeList: [],
	options: [],
	columns: [
		{
			key: 'dicDataName',
			dataKey: 'dicDataName', //需要渲染当前列的数据字段，如{id:9527,name:'Mike'}，则填name
			title: '字典名称',
			width: 600,
		},
		{
			key: 'dicDataValue',
			dataKey: 'dicDataValue', //需要渲染当前列的数据字段，如{id:9527,name:'Mike'}，则填name
			title: '字典值',
			width: 150,
		},
		{
			key: 'dicTypeCode',
			dataKey: 'dicTypeCode', //需要渲染当前列的数据字段，如{id:9527,name:'Mike'}，则填name
			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: 80,
			fixed: 'right',
			align: 'center',
			cellRenderer: (data: any) => {
				if (userInfos.value.authBtnList.includes('100604')) {
					// 权限判断
					return h(
						ElButton,
						{
							onClick: () => onOpenEditUser(data),
							type: 'primary',
							icon: h(SvgIcon, { name: 'ele-Edit', size: '16px' }, {}),
							link: true,
							title: '修改',
						},
						{ default: () => '修改' }
					);
				}
			},
		},
	],
	expandedRowKeys: [],
	isExpand: false,
});
const addRef = ref(); //新增字典
const editRef = ref(); //修改字典
const treRef = ref();
const ruleFormRef = ref();
const storesUserInfo = useUserInfo();
const { userInfos } = storeToRefs(storesUserInfo);
/** 搜索按钮操作 节流操作 */
const handleQuery = throttle(() => {
	if (state.queryParams.keyword) {
		state.tableLoading = true;
		state.expandedRowKeys = [];
		emptyArr = [];
		state.tableData = formatTable(state.tableData, 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 getDictypeList = () => {
	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 (userInfos?.value.authBtnList.includes('100601')) {
		// 判断是否有查询字典列表权限
		state.tableLoading = true;
		getDataByTypeid(state.queryParams)
			.then((response: any) => {
				state.tableData = response?.result ?? [];
				state.tableLoading = false;
			})
			.catch(() => {
				state.loading = false;
			});
	} else {
		ElMessage.warning('您没有字典列表权限');
	}
};
// 搜索
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 = () => {
	addRef.value.openDialog(state.tableData);
};
// 打开修改字典弹窗
const onOpenEditUser = (row: any) => {
	editRef.value.openDialog(row.rowData, state.tableData);
};
/** 重置按钮操作 */
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	getList();
	state.expandedRowKeys = [];
	emptyArr = [];
};

// 删除字典
// 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 onImportTable = () => {};
onMounted(() => {
	getDictypeList();
});
</script>
<style lang="scss" scoped>
.dictionarie-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>
