<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { jsonClone } from '@sa/utils';
import { fetchCreateSchoolName, fetchUpdateSchoolName } from '@/service/api/art/school-name';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';

defineOptions({
  name: 'SchoolNameOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.Art.SchoolName | null;
  /** the default school id when opened from school list */
  defaultSchoolId?: CommonType.IdType | null;
}

const props = withDefaults(defineProps<Props>(), {
  rowData: null,
  defaultSchoolId: null
});

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

const emit = defineEmits<Emits>();

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

const { formRef, validate, restoreValidation } = useNaiveForm();
const { createRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增学校多名称',
    edit: '编辑学校多名称'
  };
  return titles[props.operateType];
});

type Model = Api.Art.SchoolNameOperateParams;

const model = ref<Model>(createDefaultModel());

function createDefaultModel(): Model {
  return {
    schoolNameId: null,
    schoolId: null,
    name: '',
    nameType: null,
    remark: ''
  };
}

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

const rules: Record<RuleKey, App.Global.FormRule> = {
  schoolNameId: createRequiredRule('主键ID不能为空'),
  schoolId: createRequiredRule('关联学校主表ID不能为空'),
  name: createRequiredRule('学校名称（曾用名/别名）不能为空')
  // nameType: createRequiredRule('名称类型：1-官方全称 2-曾用名 3-别名 4-英文名称不能为空')
};

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

  if (props.operateType === 'add' && props.defaultSchoolId !== null) {
    model.value.schoolId = props.defaultSchoolId;
  }

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model.value, jsonClone(props.rowData));
  }
}

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

async function handleSubmit() {
  await validate();

  const { schoolNameId, schoolId, name, nameType, remark } = model.value;

  // request
  if (props.operateType === 'add') {
    const { error } = await fetchCreateSchoolName({ schoolId, name, nameType, remark });
    if (error) return;
  }

  if (props.operateType === 'edit') {
    const { error } = await fetchUpdateSchoolName({ schoolNameId, schoolId, name, nameType, remark });
    if (error) return;
  }

  window.$message?.success($t('common.updateSuccess'));
  closeDrawer();
  emit('submitted');
}

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

<template>
  <NDrawer v-model:show="visible" :title="title" display-directive="show" :width="800" class="max-w-90%">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NFormItem label="关联学校主表ID" path="schoolId">
          <NInput
            v-model:value="model.schoolId"
            :disabled="props.defaultSchoolId !== null"
            placeholder="请输入关联学校主表ID"
          />
        </NFormItem>
        <NFormItem label="学校名称（曾用名/别名）" path="name">
          <NInput v-model:value="model.name" placeholder="请输入学校名称（曾用名/别名）" />
        </NFormItem>
        <NFormItem label="名称类型：1-官方全称 2-曾用名 3-别名 4-英文名称" path="nameType">
          <NInput v-model:value="model.nameType" placeholder="请输入名称类型" />
          <!--
 <NSelect
            v-model:value="model.nameType"
            placeholder="请选择名称类型：1-官方全称 2-曾用名 3-别名 4-英文名称"
            :options="[{ value: '0', label: '请选择字典生成' }]"
            clearable
          /> 
-->
        </NFormItem>
        <NFormItem label="备注" path="remark">
          <NInput v-model:value="model.remark" :rows="3" type="textarea" placeholder="请输入备注" />
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
