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

defineOptions({
  name: 'SchoolRecruitMajorHistoryOperateDrawer'
});

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

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

function createDefaultModel(): Model {
  return {
    historyId: null,
    recruitMajorId: null,
    schoolId: null,
    schoolCode: '',
    collegeCode: '',
    schoolName: '',
    majorId: null,
    majorCode: '',
    majorName: '',
    enrollCode: '',
    majorType: '',
    majorTypeSub: '',
    mainExamSubject: '',
    year: null,
    subjectType: '',
    batchName: '',
    admissionFormula: '',
    probabilityOperator: '',
    controlScore: null,
    admissionScore: null,
    planEnroll: null,
    filedAmount: null,
    admitAmount: null,
    firstChoiceAdmitAmount: null,
    minScoreDiff: null,
    tuitionFee: null,
    remark: ''
  };
}

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

const rules: Record<RuleKey, App.Global.FormRule> = {
  historyId: createRequiredRule('历年录取数据ID不能为空'),
  tenantId: createRequiredRule('租户编号不能为空'),
  delFlag: createRequiredRule('删除标志（0存在 1删除）不能为空'),
  recruitMajorId: createRequiredRule('对应招录专业ID不能为空'),
  schoolId: createRequiredRule('学校ID不能为空'),
  schoolCode: createRequiredRule('学校代码不能为空'),
  schoolName: createRequiredRule('学校名称不能为空'),
  majorCode: createRequiredRule('专业代码不能为空'),
  majorName: createRequiredRule('专业名称不能为空'),
  year: 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 {
    historyId,
    recruitMajorId,
    schoolId,
    schoolCode,
    collegeCode,
    schoolName,
    majorId,
    majorCode,
    majorName,
    enrollCode,
    majorType,
    majorTypeSub,
    mainExamSubject,
    year,
    subjectType,
    batchName,
    admissionFormula,
    probabilityOperator,
    controlScore,
    admissionScore,
    planEnroll,
    filedAmount,
    admitAmount,
    firstChoiceAdmitAmount,
    minScoreDiff,
    tuitionFee,
    remark
  } = model.value;

  // request
  if (props.operateType === 'add') {
    const { error } = await fetchCreateSchoolRecruitMajorHistory({
      recruitMajorId,
      schoolId,
      schoolCode,
      collegeCode,
      schoolName,
      majorId,
      majorCode,
      majorName,
      enrollCode,
      majorType,
      majorTypeSub,
      mainExamSubject,
      year,
      subjectType,
      batchName,
      admissionFormula,
      probabilityOperator,
      controlScore,
      admissionScore,
      planEnroll,
      filedAmount,
      admitAmount,
      firstChoiceAdmitAmount,
      minScoreDiff,
      tuitionFee,
      remark
    });
    if (error) return;
  }

  if (props.operateType === 'edit') {
    const { error } = await fetchUpdateSchoolRecruitMajorHistory({
      historyId,
      recruitMajorId,
      schoolId,
      schoolCode,
      collegeCode,
      schoolName,
      majorId,
      majorCode,
      majorName,
      enrollCode,
      majorType,
      majorTypeSub,
      mainExamSubject,
      year,
      subjectType,
      batchName,
      admissionFormula,
      probabilityOperator,
      controlScore,
      admissionScore,
      planEnroll,
      filedAmount,
      admitAmount,
      firstChoiceAdmitAmount,
      minScoreDiff,
      tuitionFee,
      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="recruitMajorId">
          <NInput v-model:value="model.recruitMajorId" placeholder="请输入对应招录专业ID" />
        </NFormItem>
        <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="collegeCode">
          <NInput v-model:value="model.collegeCode" placeholder="请输入院校代码" />
        </NFormItem>
        <NFormItem label="学校名称" path="schoolName">
          <NInput v-model:value="model.schoolName" 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="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="mainExamSubject">
          <NInput v-model:value="model.mainExamSubject" placeholder="请输入主考科目" />
        </NFormItem>
        <NFormItem label="年份" path="year">
          <NInput v-model:value="model.year" placeholder="请输入年份" />
        </NFormItem>
        <NFormItem label="科类(文/理)" path="subjectType">
          <NSelect
            v-model:value="model.subjectType"
            placeholder="请选择科类(文/理)"
            :options="[{ value: '0', label: '请选择字典生成' }]"
            clearable
          />
        </NFormItem>
        <NFormItem label="批次" path="batchName">
          <NInput v-model:value="model.batchName" placeholder="请输入批次" />
        </NFormItem>
        <NFormItem label="录取方式(文*x+专*y)" path="admissionFormula">
          <NInput v-model:value="model.admissionFormula" placeholder="请输入录取方式(文*x+专*y)" />
        </NFormItem>
        <NFormItem label="录取概率规则运算符" path="probabilityOperator">
          <NInput v-model:value="model.probabilityOperator" placeholder="请输入录取概率规则运算符" />
        </NFormItem>
        <NFormItem label="省控线" path="controlScore">
          <NInput v-model:value="model.controlScore" placeholder="请输入省控线" />
        </NFormItem>
        <NFormItem label="录取线" path="admissionScore">
          <NInput v-model:value="model.admissionScore" placeholder="请输入录取线" />
        </NFormItem>
        <NFormItem label="招生人数" path="planEnroll">
          <NInput v-model:value="model.planEnroll" placeholder="请输入招生人数" />
        </NFormItem>
        <NFormItem label="实际投档人数" path="filedAmount">
          <NInput v-model:value="model.filedAmount" placeholder="请输入实际投档人数" />
        </NFormItem>
        <NFormItem label="录取数" path="admitAmount">
          <NInput v-model:value="model.admitAmount" placeholder="请输入录取数" />
        </NFormItem>
        <NFormItem label="一志愿录取数" path="firstChoiceAdmitAmount">
          <NInput v-model:value="model.firstChoiceAdmitAmount" placeholder="请输入一志愿录取数" />
        </NFormItem>
        <NFormItem label="最低分数差" path="minScoreDiff">
          <NInput v-model:value="model.minScoreDiff" placeholder="请输入最低分数差" />
        </NFormItem>
        <NFormItem label="学费(元/年)" path="tuitionFee">
          <NInput v-model:value="model.tuitionFee" 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>
