<template>
    <div class="system-edit-user-container">
        <el-dialog v-model="state.isShowDialog" 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">
                                <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"
                                ref="cascaderRef">
                                <template #default="{ node, data }">
                                    <span>{{ data.dicDataName }}</span>
                                    <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                                </template>
                            </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-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>
    </div>
</template>

<script setup lang="ts" name="systemEditDict">
import { reactive, ref } from 'vue';
import type { FormInstance } from 'element-plus';
import { storeToRefs } from 'pinia';
import { useUserInfo } from '/@/stores/userInfo';
import { ElMessage } from 'element-plus';
import { throttle } from '/@/utils/tools';
import { editDic, getDetail, dictypeList } from "/@/api/system/dict";
// 定义子组件向父组件传值/事件
const emit = defineEmits(['updateList']);

// 定义变量内容
const state = reactive<any>({
    isShowDialog: false,
    ruleForm: {
        dicTypeId: '', // 分类id
        dicDataName: '', // 名称
        dicDataValue: '', // 值
        parentId: '',
    },
    dictypeList: [],
    parentData: [],
});
const ruleFormRef = ref<FormInstance>()
let loading = ref<boolean>(false);
const storesUserInfo = useUserInfo();
const { userInfos } = storeToRefs(storesUserInfo);
// 格式化数据  剔除自己
const formatDta = (arr: Array<any>,id:string) => {
    if (!arr) return [];
	arr.forEach((v: any,i: number) => {
        if(v.id === id) arr.splice(i, 1);
		if (v.children?.length) {
			formatDta(v.children,id)
		}
	});
	return arr;
}
// 打开弹窗
const openDialog = (row: any, tableData: any) => {
    // 获取详情
    if (userInfos?.value.authBtnList.includes('100602')) { // 判断有获取字段对象权限
        ruleFormRef.value?.clearValidate();
        getDetail(row.id).then((res: any) => {
            state.parentData = formatDta(JSON.parse(JSON.stringify(tableData)),row.id);
            getDictypeList();
            state.ruleForm = res.result;
            state.isShowDialog = true;
        })
    } else {
        ElMessage.warning('您没有获取字典对象权限');
    }

};
// 关闭弹窗
const closeDialog = () => {
    state.isShowDialog = false;
};
// 获取字典类型列表
const getDictypeList = () => {
    dictypeList().then((res: any) => {
        state.dictypeList = res?.result ?? [];
    })
}
// 取消
const onCancel = () => {
    closeDialog();
};
// 保存
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();
            })
        } else {
            // console.log('error submit!', fields)
        }
    })
}, 1000);
// 暴露变量
defineExpose({
    openDialog,
    closeDialog
});
</script>
