<template>
  <div class="p-base full">
    <el-card shadow="never">
      <base-form
        ref="formRef"
        :label-width="useVW(150)"
        size="small"
        :groups="groups"
        :model="model"
        :items="items"
        :rules="rules"
        :disabled="adding || editing"
      >
        <template #form-item-setLevelRange>
          <div class="flex items-center">
            <el-input :model-value="levelRangeView" :disabled="true"></el-input>
            <el-button class="m-l-base" type="primary" @click="setLevelRangeVisible = true">设置</el-button>
          </div>
        </template>
        <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>
  <base-dialog v-model="setLevelRangeVisible" title="档次设置" destroy-on-close>
    <div class="level-list">
      <div v-for="([start, end], index) in levelRanges" :key="index" class="flex items-center level-row">
        <div class="m-r-base level-label">档次一({{ start }}~{{ end }})</div>
        <div class="flex items-center level-input">
          <el-input-number
            v-model="levelRangValues[index]"
            class="m-r-mini"
            size="small"
            :controls="false"
          ></el-input-number>
          %
        </div>
      </div>
    </div>
    <template #footer>
      <div class="flex justify-center">
        <confirm-button @confirm="onSetLevelRangeSubmit" @cancel="setLevelRangeVisible = false"></confirm-button>
      </div>
    </template>
  </base-dialog>
</template>

<script setup lang="ts" name="SubjectAddQuestion">
/** 添加大题 */
import { computed, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElCard, ElButton, ElMessage, ElInput, ElInputNumber } from 'element-plus'
import { omit } from 'lodash-es'
import ConfirmButton from '@/components/common/ConfirmButton.vue'
import BaseDialog from '@/components/element/BaseDialog.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/api'
import type { EpFormItem, EpFormRules, FormGroup } from 'global-type'

const { back } = useRouter()

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

const isEdit = !!props.mainNumber

const levelRanges = [
  [0, 2],
  [3, 5],
  [6, 8],
  [9, 11],
  [12, 14],
]

const setLevelRangeVisible = ref<boolean>(false)

const levelRangValues = ref<number[]>(Array.from<number>({ length: 5 }).fill(0))

const { fetch: getMainQuestionInfo } = 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: 1,
  mainNumber: void 0,
  mainTitle: '',
  minMarkTime: void 0,
  questionCount: void 0,
  questionScore: void 0,
  remarkNumber: void 0,
  remarkType: 'QUANTITY',
  levelRange: Array.from<number>({ length: 5 }).fill(0),
  standardRate: void 0,
  selfRate: void 0,
  systemRate: void 0,
  startNumber: 1,
})

const levelRangeView = computed(() => {
  return model.levelRange.map((n) => `${n || 0}%`).join(',')
})

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?.filter(Boolean)?.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 Span8 = defineColumn(_, _, { span: 8 })

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

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

const onSetLevelRangeSubmit = () => {
  model.levelRange = levelRangValues.value
  setLevelRangeVisible.value = false
}

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 || [], category: model.category || void 0 }
      await (isEdit ? editMainQuestion(data) : addMainQuestion(data))
      ElMessage.success('保存成功')
      back()
    }
  } catch (error) {
    console.error(error)
  }
}
const onCancel = () => {
  back()
}
</script>

<style scoped lang="scss">
.level-list {
  .level-row {
    margin-bottom: 8px;
    .level-label {
      width: 100px;
      text-align: right;
    }
  }
}
</style>
