<template>
  <div class="p-base full">
    <el-card shadow="never">
      <base-form
        ref="formRef"
        :label-width="useVW(120)"
        size="small"
        :groups="groups"
        :model="model"
        :items="items"
        :rules="rules"
        :disabled="adding || editing"
      >
        <template #form-item-expand>
          <el-button type="primary" link @click="expand = !expand">高级设置</el-button>
        </template>
        <template #form-item-operation>
          <confirm-button ok-text="保存" @confirm="onSubmit" @cancel="onCancel"></confirm-button>
        </template>
      </base-form>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="SubjectAddQuestion">
/** 添加大题 */
import { computed, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElCard, ElButton, ElMessage } from 'element-plus'
import { omit } from 'lodash-es'
import ConfirmButton from '@/components/common/ConfirmButton.vue'
import BaseForm from '@/components/element/BaseForm.vue'
import useFetch from '@/hooks/useFetch'
import useForm from '@/hooks/useForm'
import useVW from '@/hooks/useVW'

import type { ExtractApiParams } from 'api-type'
import type { EpFormItem, EpFormRules, FormGroup } from 'global-type'

const { back } = useRouter()

const props = defineProps<{ subjectCode: string; mainNumber?: number | string }>()

const isEdit = !!props.mainNumber

const { fetch: getMainQuestionInfo, result: MainQuestionInfo } = useFetch('getMainQuestionInfo')

const { fetch: addMainQuestion, loading: adding } = useFetch('addMainQuestion')
const { fetch: editMainQuestion, loading: editing } = useFetch('editMainQuestion')

const model = reactive<ExtractApiParams<'addMainQuestion'>>({
  subjectCode: props.subjectCode,
  groupNumber: void 0,
  category: void 0,
  intervalScore: void 0,
  mainNumber: void 0,
  mainTitle: '',
  minMarkTime: void 0,
  questionCount: void 0,
  questionScore: void 0,
  remarkNumber: void 0,
  remarkType: 'QUANTITY',
  levelRange: [],
  standardRate: void 0,
  selfRate: void 0,
  systemRate: void 0,
  startNumber: 1,
})

const { formRef, elFormRef, defineColumn, _ } = useForm()

const rules = computed<EpFormRules>(() => {
  return {
    groupNumber: [{ required: true, message: '请输入小组数量' }],
    category: [{ required: false, message: '请选择成绩表对应字段' }],
    intervalScore: [{ required: true, message: '请输入小题间隔分' }],
    mainNumber: [{ required: true, message: '请输入大题号' }],
    mainTitle: [{ required: true, message: '请输入大题名称' }],
    minMarkTime: [{ required: true, message: '请输入最小阅卷时长' }],
    questionCount: [{ required: true, message: '请输入小题数量' }],
    questionScore: [{ required: true, message: '请输入小题满分' }],
    remarkType: [{ required: true, message: '请选择回评设置' }],
    remarkNumber: [{ required: true, message: '请输入回评设置' }],
    startNumber: [{ required: true, message: '请输入小题起始号' }],
    systemRate: [{ required: !!model.levelRange?.length, message: '请设置系统抽查比例' }],
  }
})

const expand = ref<boolean>(false)

const groups = computed<FormGroup[]>(() => {
  return [
    {
      rowKeys: Array.from({ length: 10 }).map((_, i) => `row-${i + 1}`),
    },
    {
      rowKeys: ['row-11', 'row-12'],
      groupTitle: '高级设置',
      hidden: !expand.value,
    },
    {
      rowKeys: ['expand'],
      hidden: expand.value,
    },
  ]
})

const Span6 = defineColumn(_, _, { span: 6 })

const items = computed<EpFormItem[]>(() => [
  Span6(
    {
      label: '大题号',
      slotType: 'input',
      prop: 'mainNumber',
      slot: {
        placeholder: '大题号',
        disabled: isEdit,
      },
    },
    'row-1'
  ),
  Span6({ label: '大题名称', slotType: 'input', prop: 'mainTitle', slot: { placeholder: '大题名称' } }, 'row-2'),
  Span6(
    {
      label: '成绩表对应字段',
      slotType: 'select',
      prop: 'category',
      slot: {
        placeholder: '成绩表对应字段',
        clearable: true,
        options: [
          { label: '作文分', value: 'WRITING' },
          { label: '翻译分', value: 'TRANSLATE' },
        ],
      },
    },
    'row-2'
  ),
  Span6(
    {
      label: '小题起始号',
      slotType: 'input',
      prop: 'startNumber',
      slot: { placeholder: '小题起始号', disabled: isEdit },
    },
    'row-3'
  ),
  Span6({ label: '小题数量', slotType: 'input', prop: 'questionCount', slot: { placeholder: '小题数量' } }, 'row-4'),
  Span6({ label: '小题满分', slotType: 'input', prop: 'questionScore', slot: { placeholder: '小题满分' } }, 'row-5'),
  Span6({ label: '间隔分', slotType: 'input', prop: 'intervalScore', slot: { placeholder: '间隔分' } }, 'row-6'),
  Span6(
    {
      label: '最小阅卷时长(秒)',
      slotType: 'input',
      prop: 'minMarkTime',
      slot: { placeholder: '最小阅卷时长(秒)' },
    },
    'row-7'
  ),
  Span6(
    { label: '评卷小组数量', slotType: 'input', prop: 'groupNumber', slot: { placeholder: '评卷小组数量' } },
    'row-8'
  ),
  Span6(
    {
      label: '回评设置',
      slotType: 'select',
      prop: 'remarkType',
      slot: {
        placeholder: '回评设置',
        options: [
          { value: 'QUANTITY', label: '按数量' },
          { value: 'TIME', label: '按时间' },
        ],
      },
    },
    'row-9'
  ),
  Span6(
    { label: model.remarkType === 'QUANTITY' ? '数量' : '时间:(近N秒)', prop: 'remarkNumber', slotType: 'input' },
    'row-10'
  ),
  Span6(
    { label: '标准卷分发频度', slotType: 'input', prop: 'standardRate', slot: { placeholder: '标准卷分发频度' } },
    'row-11'
  ),
  Span6(
    { label: '自查卷分发频度', slotType: 'input', prop: 'selfRate', slot: { placeholder: '自查卷分发频度' } },
    'row-11'
  ),
  Span6(
    { label: '系统抽查卷比例', slotType: 'input', prop: 'systemRate', slot: { placeholder: '系统抽查卷比例' } },
    'row-12'
  ),
  Span6(
    { label: '档次抽查比例', slotType: 'input', prop: 'levelRange', slot: { placeholder: '档次抽查比例' } },
    'row-12'
  ),
  Span6({ slotName: 'expand' }, 'expand'),
  Span6({ slotName: 'operation' }, 'operation'),
])

if (isEdit) {
  getMainQuestionInfo({ subjectCode: props.subjectCode, mainNumber: +props.mainNumber }).then((result) => {
    Object.assign(model, omit(result, 'examId'))
  })
}

const onSubmit = async () => {
  try {
    const valid = await elFormRef?.value?.validate().catch((error: object) => {
      if (
        !expand.value &&
        Object.keys(error).some((k) => ['standardRate', 'selfRate', 'systemRate', 'levelRange'].includes(k))
      ) {
        expand.value = true
      }
    })
    if (valid) {
      const data = { ...model, levelRange: model.levelRange || [] }
      await (isEdit ? editMainQuestion(data) : addMainQuestion(data))
      ElMessage.success('保存成功')
    }
  } catch (error) {
    console.error(error)
  }
}
const onCancel = () => {
  back()
}
</script>

<style scoped lang="scss"></style>
