<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { dictStatusOptions } from '@/constants/business';
import { fetchCreateDictType, fetchUpdateDictType } from '@/service/api';
import { useForm, useFormRules } from '@/hooks/common/form';
import BusinessFormDialog from '@/components/custom/business-form-dialog.vue';
import { $t } from '@/locales';

defineOptions({ name: 'DictTypeOperateModal' });

interface Props {
  operateType: UI.TableOperateType;
  rowData?: Api.Dict.DictType | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useForm();
const { defaultRequiredRule } = useFormRules();

const isEdit = computed(() => props.operateType === 'edit');
const submitting = ref(false);

const title = computed(() => {
  const titleMap: Record<UI.TableOperateType, string> = {
    add: $t('page.system.dict.addType'),
    edit: $t('page.system.dict.editType')
  };

  return titleMap[props.operateType];
});

type Model = Api.Dict.SaveDictTypeParams;

const model = ref(createDefaultModel());

function createDefaultModel(): Model {
  return {
    name: '',
    type: '',
    status: 0,
    remark: ''
  };
}

type RuleKey = Extract<keyof Model, 'name' | 'type' | 'status'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  name: defaultRequiredRule,
  type: defaultRequiredRule,
  status: defaultRequiredRule
};

function handleInitModel() {
  model.value = createDefaultModel();

  if (isEdit.value && props.rowData) {
    // 当前页列表数据已经包含编辑所需字段，直接回填，避免额外详情请求。
    Object.assign(model.value, {
      name: props.rowData.name,
      type: props.rowData.type,
      status: props.rowData.status,
      remark: props.rowData.remark ?? ''
    });
  }
}

function closeModal() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  submitting.value = true;

  // 按接口文档先保守处理：编辑时仍带 type，但输入框禁用，避免误改编码引发子表联动问题。
  const request =
    isEdit.value && props.rowData
      ? fetchUpdateDictType({ id: props.rowData.id, ...model.value })
      : fetchCreateDictType(model.value);

  const { error } = await request;

  submitting.value = false;

  if (error) {
    return;
  }

  window.$message?.success($t(isEdit.value ? 'common.updateSuccess' : 'common.addSuccess'));

  closeModal();
  emit('submitted');
}

watch(visible, value => {
  if (value) {
    handleInitModel();
    restoreValidation();
  }
});
</script>

<template>
  <BusinessFormDialog
    v-model="visible"
    :title="title"
    preset="sm"
    :confirm-loading="submitting"
    :scrollbar="false"
    @confirm="handleSubmit"
  >
    <ElForm ref="formRef" :model="model" :rules="rules" label-position="top">
      <ElFormItem :label="$t('page.system.dict.dictName')" prop="name">
        <ElInput v-model="model.name" :placeholder="$t('page.system.dict.form.dictName')" />
      </ElFormItem>
      <ElFormItem :label="$t('page.system.dict.dictCode')" prop="type">
        <ElInput v-model="model.type" :disabled="isEdit" :placeholder="$t('page.system.dict.form.dictCode')" />
      </ElFormItem>
      <ElFormItem :label="$t('page.system.dict.dictStatus')" prop="status">
        <ElRadioGroup v-model="model.status" class="business-form-radio-group">
          <ElRadio v-for="{ label, value } in dictStatusOptions" :key="value" :value="value" :label="$t(label)" />
        </ElRadioGroup>
      </ElFormItem>
      <ElFormItem :label="$t('page.system.dict.remark')" prop="remark">
        <ElInput v-model="model.remark" type="textarea" :rows="4" :placeholder="$t('page.system.dict.form.remark')" />
      </ElFormItem>
    </ElForm>
  </BusinessFormDialog>
</template>

<style scoped></style>
