<template>
	<div class="app-container">
		<div class="card-header" style="margin-bottom: 20px">
			<span class="card-header-text"></span>
			<div>
				<el-button type="primary" @click="onAddRow"> <SvgIcon name="elementPlus" />新增 </el-button>
				<el-button type="danger" plain :disabled="state.multiple" @click="onTabelRowDel">
					<SvgIcon name="elementDelete" />
					删除
				</el-button>
			</div>
		</div>
		<!--数据表格-->
		<el-table :border="false" v-loading="state.loading" :data="state.tableData" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" align="center" />
			<el-table-column label="受众" align="center" prop="accessId" :show-overflow-tooltip="true" />
			<el-table-column label="权限等级" align="center" prop="level" :show-overflow-tooltip="true" />
			<el-table-column label="创建用户" align="center" prop="proprietorName" :show-overflow-tooltip="true" />
			<el-table-column label="创建时间" align="center" prop="createTime" />

			<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
				<template #default="scope">
					<div style="display: flex; align-items: center; justify-content: center; gap: 10px">
						<div>
							<el-tooltip class="box-item" effect="dark" content="编辑" placement="top-start">
								<el-button type="primary" size="small" circlesize="small" circle @click="onOpenEditModule(scope.row)">
									<SvgIcon :size="12" name="elementEdit" />
								</el-button>
							</el-tooltip>
						</div>
						<div>
							<el-tooltip class="box-item" effect="dark" content="删除" placement="top-start">
								<el-button type="danger" size="small" circlesize="small" circle @click="onTabelRowDel(scope.row)">
									<SvgIcon :size="12" name="elementDelete" />
								</el-button>
							</el-tooltip>
						</div>
					</div>
				</template>
			</el-table-column>
		</el-table>

		<!-- 分页设置-->
		<div v-show="state.count > 0">
			<el-divider></el-divider>
			<el-pagination
				background
				:total="state.count"
				:current-page="state.queryParams.pageNum"
				:page-size="state.queryParams.pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
			/>
		</div>
		<!-- 新增/修改弹窗-->
		<el-dialog v-model="state.isShowDialog" :title="state.title" width="80%" center>
			<el-form ref="ruleFormRef" :model="state.info" :rules="state.ruleRules" label-width="150px">
				<el-row>
					<el-col :span="12">
						<el-form-item label="权限等级" prop="level">
							<el-select v-model="state.info.level" placeholder="请选择" clearable>
								<el-option v-for="dict in state.levelOption" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="受众" prop="accessId">
							<el-tree-select
								v-model="state.info.accessId"
								lazy
								:load="load"
								:props="{
									label: 'label',
									children: 'children',
									isLeaf: 'isLeaf',
								}"
								style="width: 240px"
							/>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submit">保 存</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup name="JobLog">
import { reactive, onMounted, onUnmounted, ref, unref, getCurrentInstance, watch } from 'vue';

import { ElMessageBox, ElMessage } from 'element-plus';
import { gatherId } from '@/utils/dataGather';
import { get, update, add, del } from '@/api/public/basic';
const ruleFormRef = ref<HTMLElement | null>(null);
const { proxy } = getCurrentInstance() as any;
const props = defineProps({
	curApiId: {
		type: String,
		default: '',
	},
});

const state = reactive({
	// 参数
	// 总条数
	total: 0,
	// 列表表格数据
	tableData: [],
	// 遮罩层
	loading: true,
	// 选中数组
	ids: [],
	// 非单个禁用
	single: true,
	// 非多个禁用
	multiple: true,
	// 弹出层标题
	title: '',
	// 是否显示弹出层
	isShowDialog: false,
	levelOption: [],
	accessOption: [],
	// 查询参数
	queryParams: {
		pageNum: 1,
		pageSize: 10,
		apiId: '',
	},
	hookId: '',
	info: {
		status: 1,
	},
	ruleRules: {
		level: [{ required: true, message: '请选择', trigger: 'change' }],
	},
});

watch(
	() => props.curApiId,
	() => {
		if (!props.curApiId) return;
		state.queryParams.apiId = props.curApiId;
		handleQuery();
	}
	// { immediate: true }
);
const load = (node, resolve) => {
	if (node.isLeaf) return resolve([]);

	setTimeout(() => {
		resolve([
			{
				value: ++id,
				label: `lazy load node${id}`,
			},
			{
				value: ++id,
				label: `lazy load node${id}`,
				isLeaf: true,
			},
		]);
	}, 400);
};

const handleQuery = () => {
	state.loading = true;
	get(state.queryParams, gatherId.ACL_TABLE_LIST_ID).then((response: any) => {
		state.tableData = response.data.result;
		state.count = response.data.count;
		state.loading = false;
	});
};

const onOpenEditModule = (row: any) => {
	get(row.aclTableId, gatherId.ACL_TABLE_LIST_ID).then((response: any) => {
		if (response.status == 0) {
			state.info = response.data[0];
			state.isShowDialog = true;
		}
	});
};

const onAddRow = () => {
	state.isShowDialog = true;
};
const submit = () => {
	const formWrap = unref(ruleFormRef) as any;
	if (!formWrap) return;
	formWrap.validate((valid: boolean) => {
		if (!valid) return;
		const params = {
			apiId: props.curApiId,
			...state.info,
		};

		if (state.aclTableId) {
			// 修改
			update(params, state.aclTableId, gatherId.ACL_TABLE_LIST_ID).then((response: any) => {
				if (response.status == 0) {
					ElMessage({
						type: 'success',
						plain: true,
					});
					state.isShowDialog = false;
					handleQuery();
				}
			});
		} else {
			add(params, gatherId.ACL_TABLE_LIST_ID).then((response: any) => {
				if (response.status == 0) {
					ElMessage({
						type: 'success',
						message: '保存成功',
						plain: true,
					});
					state.hookId = response.data;
					state.isShowDialog = false;
					handleQuery();
				}
			});
		}
	});
};

/** 删除按钮操作 */
const onTabelRowDel = (row: any) => {
	const ids = row.aclTableId ? [row.aclTableId] : state.ids;
	ElMessageBox({
		message: '是否确认删除?',
		title: '警告',
		showCancelButton: true,
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(function () {
		return del({ aclTableId: ids }, gatherId.ACL_TABLE_LIST_ID).then((response: any) => {
			if (response.status == 0) {
				handleQuery();
				ElMessage({
					type: 'success',
					message: '删除成功',
					plain: true,
				});
			}
		});
	});
};

// 多选框选中数据
const handleSelectionChange = (selection: any) => {
	state.ids = selection.map((item: any) => item.aclTableId);
	state.single = selection.length != 1;
	state.multiple = !selection.length;
};

//分页页面大小发生变化
const handleSizeChange = (val: any) => {
	state.queryParams.pageSize = val;
	handleQuery();
};
//当前页码发生变化
const handleCurrentChange = (val: any) => {
	state.queryParams.pageNum = val;
	handleQuery();
};

// 页面加载时调用
onMounted(() => {
	if (!props.curApiId) return;
	state.queryParams.apiId = props.curApiId;
	handleQuery();
	proxy.getDicts('acl_level').then((response: any) => {
		state.levelOption = response.data;
	});
});

// 页面卸载时
onUnmounted(() => {
	//   proxy.mittBus.off("onEditPostModule");
});
</script>
