<template>
		<el-dialog v-model="state.dialogVisible" width="769px" draggable title="修改字典">
			<el-form :model="state.ruleForm" label-width="90px" ref="ruleFormRef">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="分类" prop="dicTypeId" :rules="[{ required: true, message: '请选择分类', trigger: 'change' }]">
							<el-select v-model="state.ruleForm.dicTypeId" placeholder="请选择分类" class="w100" @change="changeDicType">
								<el-option v-for="item in state.dicTypeList" :key="item.dicTypeName" :label="item.dicTypeName" :value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="父级" prop="parentId" :rules="[{ required: false, message: '请选择父级', trigger: 'change' }]">
							<el-cascader
								:options="state.parentData"
								filterable
								:props="{ checkStrictly: true, value: 'id', label: 'dicDataName', emitPath: false }"
								placeholder="请选择父级"
								clearable
								class="w100"
								v-model="state.ruleForm.parentId"
							>
							</el-cascader>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="字典名称" prop="dicDataName" :rules="[{ required: true, message: '请输入字典名称', trigger: 'blur' }]">
							<el-input v-model="state.ruleForm.dicDataName" placeholder="请输入字典名称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="字典值" prop="dicDataValue" :rules="[{ required: true, message: '请输入字典值', trigger: 'blur' }]">
							<el-input v-model="state.ruleForm.dicDataValue" disabled placeholder="请输入字典值" clearable></el-input>
						</el-form-item>
					</el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="排序" prop="dicDataValue" :rules="[{ required: true, message: '请输入排序', trigger: 'blur' }]">
              <el-input-number v-model="state.ruleForm.sort" :min="1" :precision="0" class="w100"/>
            </el-form-item>
          </el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" class="default-button">取 消</el-button>
					<el-button type="primary" @click="onSubmit(ruleFormRef)" :loading="loading">确 定</el-button>
				</span>
			</template>
		</el-dialog>
</template>

<script setup lang="ts" name="systemDictEdit">
import { reactive, ref } from 'vue';
import type { FormInstance } from 'element-plus';
import { ElMessage } from 'element-plus';
import { throttle, excludeSelfById } from '/@/utils/tools';
import { auth } from '/@/utils/authFunction';
import other from '/@/utils/other';
import { editDic, getDetail, dicTypeList, getDataByTypeId } from '/@/api/system/dict';
// 定义子组件向父组件传值/事件
const emit = defineEmits(['updateList']);

// 定义变量内容
const state = reactive<any>({
	dialogVisible: false,
	ruleForm: {
		dicTypeId: '', // 分类id
		dicDataName: '', // 名称
		dicDataValue: '', // 值
		parentId: '', // 父级id
    sort:1,// 排序
	},
	dicTypeList: [],  // 分类列表
	parentData: [], // 父级列表
	currentId: '',  // 当前id
});
const ruleFormRef = ref<FormInstance>();  // 表单ref
let loading = ref<boolean>(false);  // 加载状态
// 打开弹窗
const openDialog = async (row: any, tableData: any) => {
	state.currentId = row.id ?? '';
	// 获取详情
	if (!auth('system:dict:detail')) ElMessage.warning('抱歉，您没有权限获取字典详情！');
	else {
		ruleFormRef.value?.clearValidate();
		try {
			const res: any = await Promise.all([getDetail(row.id), dicTypeList()]);
			state.parentData = excludeSelfById(other.deepClone(tableData), row.id);
			state.ruleForm = res[0].result;
			state.dicTypeList = res[1].result ?? [];
			state.dialogVisible = true;
		} catch (error) {
			console.log(error);
		}
	}
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};
// 选择分类
const changeDicType = (val: string) => {
	getDataByTypeId({ typeid: val }).then((response: any) => {
		state.parentData = response?.result ?? [];
		state.parentData = excludeSelfById(other.deepClone(state.parentData), state.currentId);
	});
};
// 保存
const onSubmit = throttle(async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid) => {
		if (valid) {
			loading.value = true;
			editDic(state.ruleForm)
				.then(() => {
					ElMessage({
						message: '修改成功',
						type: 'success',
					});
					loading.value = false;
					closeDialog();
					emit('updateList');
				})
				.catch(() => {
					// 新增失败
					loading.value = false;
					closeDialog();
				});
		}
	});
}, 1000);
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
