<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { jsonClone } from '@sa/utils';
import {
  fetchCreateHistoryScoreControlLine,
  fetchUpdateHistoryScoreControlLine
} from '@/service/api/art/history-score-control-line';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';

defineOptions({
  name: 'HistoryScoreControlLineOperateDrawer'
});

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

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

function createDefaultModel(): Model {
  return {
    controlId: null,
    provinceCode: '',
    provinceName: '',
    year: null,
    majorCategory: '',
    batchName: '',
    subjectType: '',
    cultureScore: null,
    majorScore: null,
    cultureScoreExam: null,
    majorScoreExam: null,
    remark: ''
  };
}

type RuleKey = Extract<
  keyof Model,
  | 'controlId'
  | 'tenantId'
  | 'delFlag'
  | 'provinceCode'
  | 'provinceName'
  | 'year'
  | 'majorCategory'
  | 'batchName'
  | 'subjectType'
>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  controlId: createRequiredRule('省控线主键不能为空'),
  tenantId: createRequiredRule('租户编号不能为空'),
  delFlag: createRequiredRule('删除标志（0存在 1删除）不能为空'),
  provinceCode: createRequiredRule('省份行政区划代码不能为空'),
  provinceName: createRequiredRule('省份名称不能为空'),
  year: createRequiredRule('年份不能为空'),
  majorCategory: createRequiredRule('专业类别不能为空'),
  batchName: createRequiredRule('批次不能为空'),
  subjectType: 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 {
    controlId,
    provinceCode,
    provinceName,
    year,
    majorCategory,
    batchName,
    subjectType,
    cultureScore,
    majorScore,
    cultureScoreExam,
    majorScoreExam,
    remark
  } = model.value;

  // request
  if (props.operateType === 'add') {
    const { error } = await fetchCreateHistoryScoreControlLine({
      provinceCode,
      provinceName,
      year,
      majorCategory,
      batchName,
      subjectType,
      cultureScore,
      majorScore,
      cultureScoreExam,
      majorScoreExam,
      remark
    });
    if (error) return;
  }

  if (props.operateType === 'edit') {
    const { error } = await fetchUpdateHistoryScoreControlLine({
      controlId,
      provinceCode,
      provinceName,
      year,
      majorCategory,
      batchName,
      subjectType,
      cultureScore,
      majorScore,
      cultureScoreExam,
      majorScoreExam,
      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="provinceCode">
          <NInput v-model:value="model.provinceCode" placeholder="请输入省份行政区划代码" />
        </NFormItem>
        <NFormItem label="省份名称" path="provinceName">
          <NInput v-model:value="model.provinceName" placeholder="请输入省份名称" />
        </NFormItem>
        <NFormItem label="年份" path="year">
          <NInput v-model:value="model.year" placeholder="请输入年份" />
        </NFormItem>
        <NFormItem label="专业类别" path="majorCategory">
          <NInput v-model:value="model.majorCategory" placeholder="请输入专业类别" />
        </NFormItem>
        <NFormItem label="批次" path="batchName">
          <NInput v-model:value="model.batchName" placeholder="请输入批次" />
        </NFormItem>
        <NFormItem label="科类(文/理)" path="subjectType">
          <NSelect
            v-model:value="model.subjectType"
            placeholder="请选择科类(文/理)"
            :options="[{ value: '0', label: '请选择字典生成' }]"
            clearable
          />
        </NFormItem>
        <NFormItem label="文化成绩分数" path="cultureScore">
          <NInput v-model:value="model.cultureScore" placeholder="请输入文化成绩分数" />
        </NFormItem>
        <NFormItem label="专业成绩分数" path="majorScore">
          <NInput v-model:value="model.majorScore" placeholder="请输入专业成绩分数" />
        </NFormItem>
        <NFormItem label="文化成绩校考分数" path="cultureScoreExam">
          <NInput v-model:value="model.cultureScoreExam" placeholder="请输入文化成绩校考分数" />
        </NFormItem>
        <NFormItem label="专业成绩校考分数" path="majorScoreExam">
          <NInput v-model:value="model.majorScoreExam" 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>
