<template>
    <el-dialog
      :title="isEditing ? '编辑字典类型' : '添加字典类型'"
      v-model="visible"
      width="600px"
      :close-on-click-modal="false"
      @close="handleClose"
    >
      <el-form
        :model="dictTypeForm"
        :rules="formRules"
        ref="dictTypeFormRef"
        label-width="100px"
      >
        <el-form-item label="字典编码" prop="dict_code">
          <el-input
            v-model="dictTypeForm.dict_code"
            placeholder="请输入字典编码（如：user_status）"
            :disabled="isEditing"
          />
          <div class="form-tip">只能包含字母、数字或下划线，且必须唯一</div>
        </el-form-item>
        <el-form-item label="字典名称" prop="dict_name">
          <el-input
            v-model="dictTypeForm.dict_name"
            placeholder="请输入字典名称"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="dictTypeForm.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="shouldShowGlobalOption" label="全局展示" prop="is_global">
          <el-radio-group v-model="dictTypeForm.is_global">
            <el-radio :value="1">是</el-radio>
            <el-radio :value="0">否</el-radio>
          </el-radio-group>
          <div class="form-tip">是：所有租户可见；否：仅租户内部可见</div>
        </el-form-item>
        <el-form-item label="排序序号" prop="sort">
          <el-input-number
            v-model="dictTypeForm.sort"
            :min="0"
            style="width: 100%"
            placeholder="数字越小越靠前"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="dictTypeForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          保存
        </el-button>
      </template>
    </el-dialog>
  </template>
  
  <script setup lang="ts">
  import { ref, reactive, watch, computed, onMounted } from 'vue';
  import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
  import { addDictType, updateDictType, getDictTypes } from '@/api/dict';
  import { useAuthStore } from '@/stores/auth';
  
  interface Props {
    modelValue: boolean;
    dictType?: any;
  }
  
  const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    dictType: null,
  });
  
  const emit = defineEmits<{
    'update:modelValue': [value: boolean];
    success: [];
  }>();
  
  const visible = computed({
    get: () => props.modelValue,
    set: (val) => emit('update:modelValue', val),
  });
  
  const submitting = ref(false);
  const dictTypeFormRef = ref<FormInstance>();
  const authStore = useAuthStore();
  // 已移除父级选择
  
  // 判断是否为编辑模式
  const isEditing = computed(() => {
    return !!(props.dictType && props.dictType.id);
  });
  
  // 判断是否应该显示全局展示选项（只有 system_admin 和 admin 角色才能看到）
  const shouldShowGlobalOption = computed(() => {
    const roleCode = authStore.user.role_code;
    return roleCode === 'system_admin' || roleCode === 'admin';
  });
  
  // 表单数据
  const dictTypeForm = reactive({
    id: null as number | null,
    dict_code: '',
    dict_name: '',
    status: 1,
    is_global: 0,
    sort: 0,
    remark: '',
  });
  
  // 表单验证规则
  const formRules: FormRules = {
    dict_code: [
      { required: true, message: '请输入字典编码', trigger: 'blur' },
      {
        pattern: /^[a-zA-Z0-9_]+$/,
        message: '只能包含字母、数字或下划线',
        trigger: 'blur',
      },
      { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
    ],
    dict_name: [
      { required: true, message: '请输入字典名称', trigger: 'blur' },
      { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' },
    ],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }],
    sort: [
      { required: true, message: '请输入排序序号', trigger: 'blur' },
      { type: 'number', min: 0, message: '排序序号必须大于等于 0', trigger: 'blur' },
    ],
    remark: [
      { max: 500, message: '备注长度不能超过 500 个字符', trigger: 'blur' },
    ],
  };
  
  // 已移除父级选择相关数据获取
  
  // 监听 dictType 变化，填充表单数据
  watch(
    () => props.dictType,
    (newDictType) => {
      if (newDictType) {
        dictTypeForm.id = newDictType.id || null;
        dictTypeForm.dict_code = newDictType.dict_code || '';
        dictTypeForm.dict_name = newDictType.dict_name || '';
        dictTypeForm.status = newDictType.status !== undefined ? newDictType.status : 1;
        dictTypeForm.is_global = newDictType.is_global !== undefined ? newDictType.is_global : 0;
        dictTypeForm.sort = newDictType.sort || 0;
        dictTypeForm.remark = newDictType.remark || '';
      } else {
        resetForm();
      }
    },
    { immediate: true }
  );
  
  // 已移除父级选择监听
  
  // 重置表单
  function resetForm() {
    dictTypeForm.id = null;
    dictTypeForm.dict_code = '';
    dictTypeForm.dict_name = '';
    dictTypeForm.status = 1;
    dictTypeForm.is_global = 0;
    dictTypeForm.sort = 0;
    dictTypeForm.remark = '';
    dictTypeFormRef.value?.clearValidate();
  }
  
  // 关闭对话框
  function handleClose() {
    visible.value = false;
    resetForm();
  }
  
  // 提交表单
  async function handleSubmit() {
    if (!dictTypeFormRef.value) return;
  
    try {
      await dictTypeFormRef.value.validate();
    } catch (error) {
      return;
    }
  
    submitting.value = true;
    try {
      const submitData: any = {
        dict_code: dictTypeForm.dict_code,
        dict_name: dictTypeForm.dict_name,
        status: dictTypeForm.status,
        is_global: dictTypeForm.is_global,
        sort: dictTypeForm.sort,
        remark: dictTypeForm.remark || '',
      };
  
      if (isEditing.value) {
        await updateDictType(dictTypeForm.id!, submitData);
        ElMessage.success('字典类型更新成功');
      } else {
        await addDictType(submitData);
        ElMessage.success('字典类型添加成功');
      }
  
      emit('success');
      handleClose();
    } catch (error: any) {
      ElMessage.error(error.message || '操作失败，请重试');
    } finally {
      submitting.value = false;
    }
  }
  
  onMounted(() => {
    // 无需加载父级数据
  });
  </script>
  
  <style scoped lang="less">
  .form-tip {
    font-size: 12px;
    color: var(--el-text-color-secondary);
    margin-top: 4px;
    line-height: 1.4;
  }
  </style>
  
  