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

defineOptions({
  name: 'SchoolEnrollPlanOperateDrawer'
});

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

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

function createDefaultModel(): Model {
  return {
    planId: null,
    schoolId: null,
    year: null,
    province: '',
    subjectType: '',
    majorId: null,
    majorName: '',
    educationLevel: '',
    planNum: null,
    remark: ''
  };
}

type RuleKey = Extract<keyof Model, 'planId' | 'schoolId' | 'year' | 'province' | 'majorName' | 'planNum'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  planId: createRequiredRule('主键ID不能为空'),
  schoolId: createRequiredRule('学校ID不能为空'),
  year: createRequiredRule('年份不能为空'),
  province: createRequiredRule('招生省份不能为空'),
  majorName: createRequiredRule('专业名称(冗余，没专业ID也能落库)不能为空'),
  planNum: createRequiredRule('计划数不能为空')
};

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 { planId, schoolId, year, province, subjectType, majorId, majorName, educationLevel, planNum, remark } =
    model.value;

  // request
  if (props.operateType === 'add') {
    const { error } = await fetchCreateSchoolEnrollPlan({
      schoolId,
      year,
      province,
      subjectType,
      majorId,
      majorName,
      educationLevel,
      planNum,
      remark
    });
    if (error) return;
  }

  if (props.operateType === 'edit') {
    const { error } = await fetchUpdateSchoolEnrollPlan({
      planId,
      schoolId,
      year,
      province,
      subjectType,
      majorId,
      majorName,
      educationLevel,
      planNum,
      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="year">
          <NInput v-model:value="model.year" placeholder="请输入年份" />
        </NFormItem>
        <NFormItem label="招生省份" path="province">
          <NInput v-model:value="model.province" placeholder="请输入招生省份" />
        </NFormItem>
        <NFormItem label="分科：文/理/综(或物理/历史...)" path="subjectType">
          <NSelect
            v-model:value="model.subjectType"
            placeholder="请选择分科：文/理/综(或物理/历史...)"
            :options="[{ value: '0', label: '请选择字典生成' }]"
            clearable
          />
        </NFormItem>
        <NFormItem label="专业ID(可选，有则填)" path="majorId">
          <NInput v-model:value="model.majorId" placeholder="请输入专业ID(可选，有则填)" />
        </NFormItem>
        <NFormItem label="专业名称(冗余，没专业ID也能落库)" path="majorName">
          <NInput v-model:value="model.majorName" placeholder="请输入专业名称(冗余，没专业ID也能落库)" />
        </NFormItem>
        <NFormItem label="学历层次：本科/专科" path="educationLevel">
          <NInput v-model:value="model.educationLevel" placeholder="请输入学历层次：本科/专科" />
        </NFormItem>
        <NFormItem label="计划数" path="planNum">
          <NInput v-model:value="model.planNum" 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>
