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

defineOptions({
  name: 'SchoolRecruitMajorOperateDrawer'
});

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

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

function createDefaultModel(): Model {
  return {
    recruitMajorId: null,
    schoolId: null,
    schoolCode: '',
    schoolName: '',
    year: null,
    majorId: null,
    majorCode: '',
    majorName: '',
    enrollCode: '',
    dataStatus: '',
    batchName: '',
    majorType: '',
    majorTypeSub: '',
    subjectType: '',
    admissionWayShort: '',
    admissionWayExternal: '',
    admissionWayExternalOp: '',
    admissionWayInternal: '',
    admissionWayInternalOp: '',
    planEnroll: null,
    mainExamSubject: '',
    schoolingYears: null,
    enrollLimitDesc: '',
    tuitionFee: null,
    cultureScoreLimit: null,
    majorScoreLimit: null,
    chineseScoreLimit: null,
    englishScoreLimit: null,
    remark: ''
  };
}

type RuleKey = Extract<
  keyof Model,
  | 'recruitMajorId'
  | 'tenantId'
  | 'delFlag'
  | 'schoolId'
  | 'schoolCode'
  | 'schoolName'
  | 'year'
  | 'majorCode'
  | 'majorName'
  | 'enrollCode'
  | 'dataStatus'
>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  recruitMajorId: createRequiredRule('院校招录专业ID不能为空'),
  tenantId: createRequiredRule('租户编号不能为空'),
  delFlag: createRequiredRule('删除标志（0存在 1删除）不能为空'),
  schoolId: createRequiredRule('学校ID不能为空'),
  schoolCode: createRequiredRule('学校代码不能为空'),
  schoolName: createRequiredRule('学校名称(冗余)不能为空'),
  year: createRequiredRule('年份不能为空'),
  majorCode: createRequiredRule('专业代码不能为空'),
  majorName: createRequiredRule('专业名称不能为空'),
  enrollCode: createRequiredRule('招生代码(为空则存空串)不能为空'),
  dataStatus: 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 {
    recruitMajorId,
    schoolId,
    schoolCode,
    schoolName,
    year,
    majorId,
    majorCode,
    majorName,
    enrollCode,
    dataStatus,
    batchName,
    majorType,
    majorTypeSub,
    subjectType,
    admissionWayShort,
    admissionWayExternal,
    admissionWayExternalOp,
    admissionWayInternal,
    admissionWayInternalOp,
    planEnroll,
    mainExamSubject,
    schoolingYears,
    enrollLimitDesc,
    tuitionFee,
    cultureScoreLimit,
    majorScoreLimit,
    chineseScoreLimit,
    englishScoreLimit,
    remark
  } = model.value;

  // request
  if (props.operateType === 'add') {
    const { error } = await fetchCreateSchoolRecruitMajor({
      schoolId,
      schoolCode,
      schoolName,
      year,
      majorId,
      majorCode,
      majorName,
      enrollCode,
      dataStatus,
      batchName,
      majorType,
      majorTypeSub,
      subjectType,
      admissionWayShort,
      admissionWayExternal,
      admissionWayExternalOp,
      admissionWayInternal,
      admissionWayInternalOp,
      planEnroll,
      mainExamSubject,
      schoolingYears,
      enrollLimitDesc,
      tuitionFee,
      cultureScoreLimit,
      majorScoreLimit,
      chineseScoreLimit,
      englishScoreLimit,
      remark
    });
    if (error) return;
  }

  if (props.operateType === 'edit') {
    const { error } = await fetchUpdateSchoolRecruitMajor({
      recruitMajorId,
      schoolId,
      schoolCode,
      schoolName,
      year,
      majorId,
      majorCode,
      majorName,
      enrollCode,
      dataStatus,
      batchName,
      majorType,
      majorTypeSub,
      subjectType,
      admissionWayShort,
      admissionWayExternal,
      admissionWayExternalOp,
      admissionWayInternal,
      admissionWayInternalOp,
      planEnroll,
      mainExamSubject,
      schoolingYears,
      enrollLimitDesc,
      tuitionFee,
      cultureScoreLimit,
      majorScoreLimit,
      chineseScoreLimit,
      englishScoreLimit,
      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="学校ID" path="schoolId">
          <NInput v-model:value="model.schoolId" placeholder="请输入学校ID" />
        </NFormItem>
        <NFormItem label="学校代码" path="schoolCode">
          <NInput v-model:value="model.schoolCode" placeholder="请输入学校代码" />
        </NFormItem>
        <NFormItem label="学校名称(冗余)" path="schoolName">
          <NInput v-model:value="model.schoolName" placeholder="请输入学校名称(冗余)" />
        </NFormItem>
        <NFormItem label="年份" path="year">
          <NInput v-model:value="model.year" placeholder="请输入年份" />
        </NFormItem>
        <NFormItem label="专业ID" path="majorId">
          <NInput v-model:value="model.majorId" placeholder="请输入专业ID" />
        </NFormItem>
        <NFormItem label="专业代码" path="majorCode">
          <NInput v-model:value="model.majorCode" placeholder="请输入专业代码" />
        </NFormItem>
        <NFormItem label="专业名称" path="majorName">
          <NInput v-model:value="model.majorName" placeholder="请输入专业名称" />
        </NFormItem>
        <NFormItem label="招生代码(为空则存空串)" path="enrollCode">
          <NInput v-model:value="model.enrollCode" placeholder="请输入招生代码(为空则存空串)" />
        </NFormItem>
        <NFormItem label="数据状态(停招/新招/新增)" path="dataStatus">
          <NRadioGroup v-model:value="model.dataStatus">
            <NSpace>
              <NRadio value="0" label="请选择字典生成" />
            </NSpace>
          </NRadioGroup>
        </NFormItem>
        <NFormItem label="批次" path="batchName">
          <NInput v-model:value="model.batchName" placeholder="请输入批次" />
        </NFormItem>
        <NFormItem label="专业类型" path="majorType">
          <NSelect
            v-model:value="model.majorType"
            placeholder="请选择专业类型"
            :options="[{ value: '0', label: '请选择字典生成' }]"
            clearable
          />
        </NFormItem>
        <NFormItem label="二级专业类型" path="majorTypeSub">
          <NInput v-model:value="model.majorTypeSub" placeholder="请输入二级专业类型" />
        </NFormItem>
        <NFormItem label="科类(文/理)" path="subjectType">
          <NSelect
            v-model:value="model.subjectType"
            placeholder="请选择科类(文/理)"
            :options="[{ value: '0', label: '请选择字典生成' }]"
            clearable
          />
        </NFormItem>
        <NFormItem label="录取方式缩写" path="admissionWayShort">
          <NInput v-model:value="model.admissionWayShort" placeholder="请输入录取方式缩写" />
        </NFormItem>
        <NFormItem label="对外录取方式" path="admissionWayExternal">
          <NInput v-model:value="model.admissionWayExternal" placeholder="请输入对外录取方式" />
        </NFormItem>
        <NFormItem label="对外录取方式运算符" path="admissionWayExternalOp">
          <NInput v-model:value="model.admissionWayExternalOp" placeholder="请输入对外录取方式运算符" />
        </NFormItem>
        <NFormItem label="内部录取方式" path="admissionWayInternal">
          <NInput v-model:value="model.admissionWayInternal" placeholder="请输入内部录取方式" />
        </NFormItem>
        <NFormItem label="内部录取方式运算符" path="admissionWayInternalOp">
          <NInput v-model:value="model.admissionWayInternalOp" placeholder="请输入内部录取方式运算符" />
        </NFormItem>
        <NFormItem label="计划招生人数" path="planEnroll">
          <NInput v-model:value="model.planEnroll" placeholder="请输入计划招生人数" />
        </NFormItem>
        <NFormItem label="主考科目" path="mainExamSubject">
          <NInput v-model:value="model.mainExamSubject" placeholder="请输入主考科目" />
        </NFormItem>
        <NFormItem label="学制(年)" path="schoolingYears">
          <NInput v-model:value="model.schoolingYears" placeholder="请输入学制(年)" />
        </NFormItem>
        <NFormItem label="院校限制说明" path="enrollLimitDesc">
          <NInput v-model:value="model.enrollLimitDesc" :rows="3" type="textarea" placeholder="请输入院校限制说明" />
        </NFormItem>
        <NFormItem label="学费(元/年)" path="tuitionFee">
          <NInput v-model:value="model.tuitionFee" placeholder="请输入学费(元/年)" />
        </NFormItem>
        <NFormItem label="文化分数限制" path="cultureScoreLimit">
          <NInput v-model:value="model.cultureScoreLimit" placeholder="请输入文化分数限制" />
        </NFormItem>
        <NFormItem label="专业分数限制" path="majorScoreLimit">
          <NInput v-model:value="model.majorScoreLimit" placeholder="请输入专业分数限制" />
        </NFormItem>
        <NFormItem label="语文成绩限制" path="chineseScoreLimit">
          <NInput v-model:value="model.chineseScoreLimit" placeholder="请输入语文成绩限制" />
        </NFormItem>
        <NFormItem label="英语成绩限制" path="englishScoreLimit">
          <NInput v-model:value="model.englishScoreLimit" 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>
