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

defineOptions({
  name: 'MajorOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.Art.Major | 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.MajorOperateParams;

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

function createDefaultModel(): Model {
  return {
    majorId: null,
    majorName: '',
    educationLevel: '',
    majorIcon: '',
    schoolingYears: null,
    disciplinePrimary: '',
    disciplineSecondary: '',
    degreeAwarded: '',
    summary: '',
    trainingDirection: '',
    coreCourses: '',
    remark: ''
  };
}

type RuleKey = Extract<keyof Model, 'majorId' | 'tenantId' | 'delFlag' | 'majorName' | 'educationLevel'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  majorId: createRequiredRule('专业主键ID不能为空'),
  tenantId: createRequiredRule('租户编号不能为空'),
  delFlag: createRequiredRule('删除标志（0存在 1删除）不能为空'),
  majorName: createRequiredRule('专业名称不能为空'),
  educationLevel: 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 {
    majorId,
    majorName,
    educationLevel,
    majorIcon,
    schoolingYears,
    disciplinePrimary,
    disciplineSecondary,
    degreeAwarded,
    summary,
    trainingDirection,
    coreCourses,
    remark
  } = model.value;

  // request
  if (props.operateType === 'add') {
    const { error } = await fetchCreateMajor({
      majorName,
      educationLevel,
      majorIcon,
      schoolingYears,
      disciplinePrimary,
      disciplineSecondary,
      degreeAwarded,
      summary,
      trainingDirection,
      coreCourses,
      remark
    });
    if (error) return;
  }

  if (props.operateType === 'edit') {
    const { error } = await fetchUpdateMajor({
      majorId,
      majorName,
      educationLevel,
      majorIcon,
      schoolingYears,
      disciplinePrimary,
      disciplineSecondary,
      degreeAwarded,
      summary,
      trainingDirection,
      coreCourses,
      remark
    });
    if (error) return;
  }

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

watch(visible, () => {
  if (visible.value) {
    handleUpdateModelWhenEdit();
    restoreValidation();
    getTreeList();
  }
});
</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="专业名称" path="majorName">
          <NInput v-model:value="model.majorName" placeholder="请输入专业名称" />
        </NFormItem>
        <NFormItem label="学历层次" path="educationLevel">
          <NInput v-model:value="model.educationLevel" placeholder="请输入学历层次" />
        </NFormItem>
        <NFormItem label="专业图标" path="majorIcon">
          <NInput v-model:value="model.majorIcon" placeholder="请输入专业图标" />
        </NFormItem>
        <NFormItem label="学制(年)" path="schoolingYears">
          <NInput v-model:value="model.schoolingYears" placeholder="请输入学制(年)" />
        </NFormItem>
        <NFormItem label="所属一级学科" path="disciplinePrimary">
          <NInput v-model:value="model.disciplinePrimary" placeholder="请输入所属一级学科" />
        </NFormItem>
        <NFormItem label="所属二级学科" path="disciplineSecondary">
          <NInput v-model:value="model.disciplineSecondary" placeholder="请输入所属二级学科" />
        </NFormItem>
        <NFormItem label="授予学士学位" path="degreeAwarded">
          <NInput v-model:value="model.degreeAwarded" placeholder="请输入授予学士学位" />
        </NFormItem>
        <NFormItem label="专业概括" path="summary">
          <NInput v-model:value="model.summary" :rows="3" type="textarea" placeholder="请输入专业概括" />
        </NFormItem>
        <NFormItem label="培养方向" path="trainingDirection">
          <NInput v-model:value="model.trainingDirection" :rows="3" type="textarea" placeholder="请输入培养方向" />
        </NFormItem>
        <NFormItem label="主要课程" path="coreCourses">
          <NInput v-model:value="model.coreCourses" :rows="3" type="textarea" 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>
