<template>
	<div class="knowledge-hot-words-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<el-form :model="state.queryParams" ref="ruleFormRef" inline @submit.native.prevent>
				<el-form-item label="热词名称" prop="Name">
					<el-input v-model="state.queryParams.Name" placeholder="请填写热词名称" clearable @keyup.enter="handleQuery" class="keyword-input" />
				</el-form-item>
				<el-form-item label="类型" prop="Type">
					<el-select v-model="state.queryParams.Type" placeholder="请选择类型" clearable>
						<el-option v-for="items in typeOptions" :key="items.key" :label="items.value" :value="items.key" />
					</el-select>
				</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="onProjectAdd" v-auth="'knowledge:hotWords:add'">
						<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.loading"
					: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
					@sort-change="sortChange"
					:sort-config="{ remote: true }"
					:scrollY="{ enabled: true, gt: 100 }"
					id="knowledgeHotWords"
					:custom-config="{ storage: true }"
					showHeaderOverflow
				>
					<vxe-column field="keyWord" title="热词名称" min-width="150"></vxe-column>
					<vxe-column field="typeTxt" title="类型" width="100"></vxe-column>
					<vxe-column field="sort" title="排序" width="100" sortable></vxe-column>
					<vxe-column field="searchCount" title="搜索次数" width="100" sortable></vxe-column>
					<vxe-column field="isEnable" title="是否启用" width="100">
						<template #default="{ row }">
							<template v-if="auth('knowledge:hotWords:edit')">
								<el-switch v-model="row.isEnable" active-text="启用" inactive-text="禁用"  @change="changeIsEnable(row)" inline-prompt size="small" />
							</template>
							<span v-else>{{ row.isEnable ? '已启用' : '已禁用' }}</span>
						</template>
					</vxe-column>
					<vxe-column field="creationTime" title="创建时间" width="160" sortable>
						<template #default="{ row }">
							{{ formatDate(row.creationTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column title="操作" fixed="right" width="120" align="center">
						<template #default="{ row }">
							<el-button link type="primary" @click="onProjectEdit(row)" v-auth="'knowledge:hotWords:edit'" title="修改热词"> 修改 </el-button>
							<el-button link type="danger" @click="onProjectDelete(row)" v-auth="'knowledge:hotWords:delete'" title="删除热词"> 删除 </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.loading"
			/>
		</div>
		<!--  热词新增  -->
		<hot-words-add ref="hotWordsAddRef" @updateList="queryList" :typeOptions="typeOptions" />
		<!--  热词修改  -->
		<hot-word-edit ref="hotWordEditRef" @updateList="queryList" :typeOptions="typeOptions" />
	</div>
</template>

<script lang="tsx" setup name="knowledgeHotWords">
import { defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { formatDate } from '@/utils/formatTime';
import { auth } from '@/utils/authFunction';
import { delKnowledgeHotWords, getKnowledgeHotWordsBaseData, getKnowledgeHotWordsList, updateKnowledgeHotWords } from '@/api/knowledge/hotWords';
// 引入组件
const hotWordsAdd = defineAsyncComponent(() => import('@/views/knowledge/hotWords/components/Hot-words-add.vue')); // 热词新增
const HotWordEdit = defineAsyncComponent(() => import('@/views/knowledge/hotWords/components/Hot-words-edit.vue')); // 热词修改
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页
// 定义变量内容
const state = reactive<any>({
	loading: false, // 加载状态
	queryParams: {
		// 查询参数
		PageIndex: 1,
		PageSize: 20,
		GroupingName: null,
		Type: null,
		Name: null,
		SortField: null,
		OrderByType: null,
	},
	total: 0, // 总条数
	tableData: [], // 表格数据
});
const ruleFormRef = ref<RefType>(null); // 表单ref
// 手动查询，将页码设置为1
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
// 获取参数列表
const queryList = () => {
	state.loading = true;
	getKnowledgeHotWordsList(state.queryParams)
		.then((res) => {
			state.loading = false;
			state.tableData = res.result.items ?? [];
			state.total = res.result.total ?? 0;
		})
		.finally(() => {
			state.loading = false;
		});
};
// 排序
const sortChange = (val: any) => {
	state.queryParams.SortField = val.order ? val.field : null;
	// 0 升序 1 降序
	state.queryParams.SortRule = val.order ? (val.order == 'desc' ? 1 : 0) : null;
	handleQuery();
};
// 重置表单
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	queryList();
};
// 新增热词
const hotWordsAddRef = ref<RefType>();
const onProjectAdd = () => {
	hotWordsAddRef.value.openDialog();
};
// 编辑热词
const hotWordEditRef = ref<RefType>();
const onProjectEdit = (row: any) => {
	hotWordEditRef.value.openDialog(row);
};
// 删除热词
const onProjectDelete = (row: any) => {
	ElMessageBox.confirm(`您确定要删除【${row.keyWord}】热词，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			delKnowledgeHotWords(row.id).then(() => {
				ElMessage.success('操作成功');
				queryList();
			});
		})
		.catch(() => {});
};
//  修改是否启用
const changeIsEnable = (row: any) => {
	row.isEnable = !row.isEnable //保持switch点击前的状态
	ElMessageBox.confirm(`您确定要${row.isEnable ? '禁用' : '启用'}：【${row.keyWord}】热词，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			const request = {
				...row,
				isEnable: !row.isEnable,
			};
			updateKnowledgeHotWords(request)
				.then(() => {
					ElMessage.success('操作成功');
					queryList();
				})
				.catch(() => {
					queryList();
				});
		})
		.catch(() => {
			queryList();
		});
};
const typeOptions = ref<EmptyArrayType>([]);
// 获取基础数据
const getBaseData = () => {
	// 获取类型列表
	getKnowledgeHotWordsBaseData().then((res) => {
		typeOptions.value = res.result.knowledgeHotWordType;
	});
};
const toolbarRef = ref<RefType>();
const tableRef = ref<RefType>();
// 页面加载时
onMounted(() => {
	queryList();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
	getBaseData();
});
</script>
