<template>
	<el-drawer title="知识关键词" v-model="drawerVisible" size="40%" @opened="opened">
		<el-form :model="state.queryParams" ref="ruleFormRef" inline @submit.native.prevent>
			<el-form-item label="关键词" prop="Tag">
				<el-input v-model="state.queryParams.Tag" placeholder="请填写关键词" clearable @keyup.enter="handleQuery" />
			</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"> <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="addParameter"> <SvgIcon name="ele-Plus" class="mr5" />新增 </el-button>
				<el-button type="danger" @click="businessTagRemove" :disabled="isChecked">
					<SvgIcon name="ele-Delete" class="mr5" />删除
				</el-button>
			</template>
		</vxe-toolbar>
			<vxe-table
				border
				:loading="state.loading"
				:data="state.tableData"
				:column-config="{ resizable: true }"
				:row-config="{ isCurrent: true, isHover: true, height: 30, useKey: true }"
				ref="tableRef"
				@checkbox-all="selectAllChangeEvent"
				@checkbox-change="selectChangeEvent"
				max-height="600px"
				show-overflow
				:scrollY="{ enabled: true, gt: 100 }"
			>
				<vxe-column type="checkbox" width="60" align="center"></vxe-column>
				<vxe-column field="tag" title="关键词"></vxe-column>
				<vxe-column field="synonym" title="同义词"></vxe-column>
				<vxe-column title="操作" fixed="right" width="130" align="center">
					<template #default="{ row }">
						<el-button link type="primary" @click="updateLexicon(row)" title="编辑知识库词库"> 编辑 </el-button>
					</template>
				</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="drawerVisible = false" class="default-button">取 消</el-button>
				<el-button type="primary" @click="onConfirm" :loading="state.loading">提 交</el-button>
			</span>
		</template>
	</el-drawer>
	<!--  新增知识库词库  -->
	<knowledge-lexicon-add ref="knowledgeLexiconAddRef" @updateList="queryList" :knowledgeWordClassify="knowledgeWordClassify" />
	<!--  编辑知识库词库  -->
	<knowledge-lexicon-edit ref="knowledgeLexiconEditRef" @updateList="queryList" :knowledgeWordClassify="knowledgeWordClassify" />
</template>
<script setup lang="tsx">
import { computed, defineAsyncComponent, reactive, ref } from 'vue';
import { knowledgeLexiconDelete, knowledgeLexiconList, orderKnowledgeBaseData } from '@/api/auxiliary/knowledgeLexicon';
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";

// 引入组件
const KnowledgeLexiconAdd = defineAsyncComponent(() => import('@/views/auxiliary/knowledgeLexicon/components/Knowledge-lexicon-add.vue')); // 新增知识库词库
const KnowledgeLexiconEdit = defineAsyncComponent(() => import('@/views/auxiliary/knowledgeLexicon/components/Knowledge-lexicon-edit.vue')); // 编辑知识库词库
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页

const emit = defineEmits(['selectKeyword']);

const drawerVisible = ref<boolean>(false);

const state = reactive({
	queryParams: {
		// 查询参数
		PageIndex: 1,
		PageSize: 20,
		Tag: null, // 标签
		Classify: null, // 标签类型
		Synonym: null, // 近义词
		IsEnable:0, // 0启用 1禁用
	},
	total: 0, // 总条数
	tableData: [], // 表格数据
  loading:false,
});
const ruleFormRef = ref<any>(null); // 表单ref
const knowledgeWordClassify = ref<EmptyArrayType>(); // 标签类型
const keywordIds = ref<EmptyArrayType>(); // 关键词ID
// 获取基础数据
const getBaseData = async () => {
	try {
		const res = await orderKnowledgeBaseData();
		knowledgeWordClassify.value = res.result?.knowledgeWordClassify ?? [];
	} catch (error) {
		console.log(error);
	}
};
/** 搜索按钮操作 */
const handleQuery = () => {
  state.queryParams.PageIndex = 1;
  queryList();
};
// 获取参数列表
const queryList = () => {
	state.loading = true;
	knowledgeLexiconList(state.queryParams)
		.then((res) => {
			state.loading = false;
			state.tableData = res.result.items ?? [];
			state.total = res.result.total ?? 0;
			tableRef.value.clearCheckboxRow();
			checkTable.value = [];
			if (keywordIds.value && keywordIds.value.length) {
				for (let i of keywordIds.value) {
					for (let j of state.tableData) {
						if (i === j.id) {
							setTimeout(() => {
								tableRef.value.setCheckboxRow(j, true);
								checkTable.value = tableRef.value.getCheckboxRecords();
							}, 100);
						}
					}
				}
			} else {
				tableRef.value.clearCheckboxRow();
				checkTable.value = [];
			}
		})
		.finally(() => {
			state.loading = false;
		});
};
// 重置表单
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	queryList();
};
// 新增词库
const knowledgeLexiconAddRef = ref<RefType>();
const addParameter = () => {
	knowledgeLexiconAddRef.value.openDialog();
};
// 编辑知识库词库
const knowledgeLexiconEditRef = ref<RefType>();
const updateLexicon = (row: any) => {
	knowledgeLexiconEditRef.value.openDialog(row.id);
};
// 删除词库
const businessTagRemove = () => {
	const ids = checkTable.value.map((item: any) => item.id);
	const name = checkTable.value.map((item: any) => item.tag);
	ElMessageBox.confirm(`您确定要删除：【${name}】，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			knowledgeLexiconDelete({ ids }).then(() => {
				ElMessage.success('操作成功');
				queryList();
			});
		})
		.catch(() => {});
};
// 确定选择关键词
const onConfirm = () => {
	const ids = checkTable.value.map((item: any) => item.id);
	const name = checkTable.value.map((item: any) => item.tag);
	emit('selectKeyword', { ids, name });
	drawerVisible.value = false;
};
// 打开弹窗
const openDialog = (keywords: any[]) => {
	keywordIds.value = keywords;
	getBaseData();
	queryList();
	drawerVisible.value = true;
};
// 关闭弹窗
const closeDialog = () => {
	drawerVisible.value = false;
};
const tableRef = ref<RefType>();
const checkTable = ref<EmptyArrayType>([]);
const selectAllChangeEvent = ({ checked }) => {
	if (tableRef.value) {
		const records = tableRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '所有勾选事件' : '所有取消事件', records);
	}
};

const selectChangeEvent = ({ checked }) => {
	if (tableRef.value) {
		const records = tableRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '勾选事件' : '取消事件', records);
	}
};
const isChecked = computed(() => {
	return !Boolean(checkTable.value.length);
});
const toolbarRef = ref<RefType>();
const opened = ()=>{
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
}
defineExpose({
	openDialog,
	closeDialog,
});
</script>
