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

defineOptions({
  name: 'SchoolMajorTagOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.Art.SchoolMajorTag | 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 } = useNaiveForm();
const { createRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增专业标签',
    edit: '编辑专业标签'
  };
  return titles[props.operateType];
});

type Model = Api.Art.SchoolMajorTagOperateParams;

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

function createDefaultModel(): Model {
  return {
    majorTagId: null,
    majorId: null,
    tagName: '',
    remark: ''
  };
}

type RuleKey = Extract<keyof Model, 'majorTagId' | 'majorId' | 'tagName'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  majorTagId: createRequiredRule('主键ID不能为空'),
  majorId: createRequiredRule('专业ID不能为空'),
  tagName: createRequiredRule('标签名称(如：双一流学科/国家级特色专业/艺术类重点专业...)不能为空')
};

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

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

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

async function handleSubmit() {
  await validate();

  const { majorTagId, majorId, tagName, remark } = model.value;

  // request
  if (props.operateType === 'add') {
    const { error } = await fetchCreateSchoolMajorTag({ majorId, tagName, remark });
    if (error) return;
  }

  if (props.operateType === 'edit') {
    const { error } = await fetchUpdateSchoolMajorTag({ majorTagId, majorId, tagName, 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="majorId">
          <NInput v-model:value="model.majorId" placeholder="请输入专业ID" />
        </NFormItem>
        <NFormItem label="标签名称(如：双一流学科/国家级特色专业/艺术类重点专业...)" path="tagName">
          <NInput
            v-model:value="model.tagName"
            placeholder="请输入标签名称(如：双一流学科/国家级特色专业/艺术类重点专业...)"
          />
        </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>
