<template>
	<div class="auxiliary-clear-cache-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="缓存key" prop="keyword">
					<el-input v-model="state.queryParams.keyword" placeholder="缓存key名称" 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"> <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="danger" @click="cacheKeysRemove" v-auth="'auxiliary:eventClass:delete'" :loading="state.loading" :disabled="isChecked">
						<SvgIcon name="ele-Delete" class="mr5" />删除
					</el-button>
				</template>
			</vxe-toolbar>
			<div style="overflow: hidden; width: 100%; height: 100%; flex: 1">
				<vxe-table
					border
					: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: 100 }"
					id="auxiliaryClearCache"
					:custom-config="{ storage: true }"
					@checkbox-all="selectAllChangeEvent"
					@checkbox-change="selectChangeEvent"
					:checkbox-config="{ highlight: true }"
				>
					<vxe-column type="checkbox" width="60" align="center"></vxe-column>
					<vxe-column field="id" title="缓存key">
						<template #default="{ row }">
							<span v-html="row.id"></span>
						</template>
					</vxe-column>
					<vxe-column title="操作" fixed="right" width="80" align="center">
						<template #default="{ row }">
							<el-button link type="danger" @click="onDelete(row)" title="删除" v-auth="'auxiliary:eventClass:delete'"> 删除 </el-button>
						</template>
					</vxe-column>
				</vxe-table>
			</div>
		</div>
	</div>
</template>

<script lang="tsx" setup name="auxiliaryClearCache">
import { computed, onMounted, reactive, ref, unref } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { clearCache, getAllCacheKey } from '@/api/auxiliary/clearCache';
import XEUtils from 'xe-utils';

// 定义变量内容
const state = reactive<any>({
	loading: false, // 加载状态
	queryParams: {
		keyword: null, // 参数名称
	},
	total: 0, // 总条数
	tableData: [], // 表格数据
	staticArr: [],
});
const ruleFormRef = ref<any>(null); // 表单ref
/** 搜索按钮操作 */
const handleQuery = () => {
	queryList();
};
// 获取列表
const tableData = ref<EmptyArrayType>([]);
const list = ref<any[]>([]);
const queryList = () => {
	state.loading = true;
	getAllCacheKey(state.queryParams)
		.then((res) => {
			state.loading = false;
			tableData.value = res.result.map((item: any) => {
				return {
					id: item,
				};
			});
			const filterVal = String(state.queryParams.keyword).trim().toLowerCase();
			if (state.queryParams.keyword && filterVal) {
				const filterRE = new RegExp(filterVal, 'gi');
				const searchProps = ['id'];
				const rest = tableData.value.filter((item) => searchProps.some((key) => String(item[key]).toLowerCase().indexOf(filterVal) > -1));
				list.value = rest.map((row) => {
					// 搜索为克隆数据，不会污染源数据
					const item = XEUtils.clone(row);
					searchProps.forEach((key) => {
						item[key] = String(item[key]).replace(filterRE, (match) => `<span class="keyword-highlight">${match}</span>`);
					});
					return item;
				});
			} else {
				list.value = tableData.value;
			}
			tableRef.value.clearCheckboxRow();
			checkTable.value = [];
		})
		.catch((err: any) => {
			console.log(err, '111');
			state.loading = false;
			tableRef.value.clearCheckboxRow();
			checkTable.value = [];
		});
};
// 重置表单
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	queryList();
};
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 cacheKeysRemove = () => {
	const ids = checkTable.value.map((item: any) => item.id);
	ElMessageBox.confirm(`您确定要删除选中的缓存key，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			clearCache({ keys: ids }).then(() => {
				ElMessage.success('操作成功');
				queryList();
			});
		})
		.catch(() => {});
};
// 删除缓存
const onDelete = (row: any) => {
	ElMessageBox.confirm(`您确定要删除缓存 ${row.id}?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			clearCache({ keys: [row.id] }).then(() => {
				ElMessage.success('操作成功');
				queryList();
			});
		})
		.catch(() => {});
};
const toolbarRef = ref<RefType>();
const tableRef = ref<RefType>();
// 页面加载时
onMounted(() => {
	queryList();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
});
</script>
