<template>
  <base-form
    ref="formRef"
    :label-width="useVW(88)"
    :groups="groups"
    :rules="rules"
    :items="items"
    :model="model"
    :disabled="loading"
  >
    <template #form-item-prefix>
      <span class="flex items-center">
        <el-input v-model="model.prefix"></el-input>
        <span class="m-l-mini">0000000</span>
      </span>
    </template>
    <template #form-item-address>
      <span class="flex items-center">
        {{ filePath }}
      </span>
    </template>
    <template #form-item-upload>
      <div class="flex items-center">
        <el-input v-model="fileName" disabled placeholder="导入文件"></el-input>
        <el-upload
          ref="upload"
          v-model:file-list="fileList"
          :limit="1"
          :show-file-list="false"
          :on-exceed="onExceed"
          :auto-upload="false"
        >
          <el-button class="m-l-base" type="primary">浏览</el-button>
        </el-upload>
      </div>
    </template>
    <template #form-item-progress>
      <el-progress v-show="showProgress" class="flex-1" :percentage="percentage" color="#00BA97" />
    </template>
    <el-form-item class="m-t-base form-footer">
      <el-button type="primary" :loading="loading" @click="onSubmit">确定导入</el-button>
    </el-form-item>
  </base-form>
</template>

<script setup lang="ts" name="ImportSample">
/** 导入培训卷 */
import { reactive, watch, computed, ref } from 'vue'
import { ElFormItem, ElButton, ElUpload, ElInput, ElMessage, ElProgress } from 'element-plus'
import BaseForm from '@/components/element/BaseForm.vue'
import useFetch from '@/hooks/useFetch'
import useForm from '@/hooks/useForm'
import useOptions from '@/hooks/useOptions'
import useUploadFile from '@/hooks/useUploadFile'
import useVW from '@/hooks/useVW'

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

const showProgress = ref(false)

const { fileList, upload, percentage, setPercentage, onExceed, onUploadProgress, reset } = useUploadFile()

const { fetch: getImportFilePath, result: filePath } = useFetch('getImportFilePath')

const { fetch, loading } = useFetch('importSamplePaper', { onUploadProgress })

const model = reactive<ExtractApiParams<'importSamplePaper'>>({
  file: void 0,
  mainNumber: void 0,
  paperType: 'SAMPLE_A',
  prefix: '',
  separator: '',
  subjectCode: '',
})

watch([() => model.subjectCode, () => model.mainNumber, () => model.paperType], () => {
  /** 获取导入文件路径 */
  model.subjectCode &&
    model.mainNumber &&
    model.paperType &&
    getImportFilePath({
      filePathType: model.paperType,
      subjectCode: model.subjectCode,
      mainNumber: model.mainNumber,
    })
})

const { subjectList, mainQuestionList, dataModel, changeModelValue } = useOptions(['subject', 'question'])

watch(dataModel, () => {
  model.subjectCode = dataModel.subject || ''
  model.mainNumber = dataModel.question
})

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

const fileName = computed(() => fileList.value?.[0]?.name)

watch(
  fileList,
  () => {
    model.file = fileList.value?.[0]?.raw
  },
  { deep: true }
)

const rules: EpFormRules = {
  subjectCode: [{ required: true, message: '请选择科目' }],
  mainNumber: [{ required: true, message: '请选择大题' }],
  paperType: [{ required: true, message: '请选择分组代码' }],
  prefix: [{ required: true, message: '请设置试卷密码前缀' }],
  separator: [{ required: true, message: '请设置分隔符' }],
  file: [{ required: true, message: '请选择导入文件' }],
}

const groups: FormGroup[] = [
  { groupTitle: '选择大题', rowKeys: ['row-1'] },
  { groupTitle: '试卷设置', rowKeys: ['row-2', 'row-3', 'row-4', 'row-5'] },
  { groupTitle: '选择文件', rowKeys: ['row-6'] },
]

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

const items = computed<EpFormItem[]>(() => {
  return [
    span6({
      rowKey: 'row-1',
      label: '科目',
      prop: 'subjectCode',
      slotType: 'select',
      slot: { placeholder: '选择科目', options: subjectList.value, onChange: changeModelValue('subject') },
    }),
    span6({
      rowKey: 'row-1',
      label: '大题',
      labelWidth: useVW(100),
      prop: 'mainNumber',
      slotType: 'select',
      slot: { placeholder: '选择大题', options: mainQuestionList.value, onChange: changeModelValue('question') },
    }),
    span6({
      rowKey: 'row-2',
      label: '分组代码',
      prop: 'paperType',
      slotType: 'select',
      slot: {
        options: [
          { label: 'Sample A', value: 'SAMPLE_A' },
          { label: 'Sample B', value: 'SAMPLE_B' },
        ],
      },
      itemDescription: { description: 'Sample A/B卷' },
    }),
    span6({
      rowKey: 'row-3',
      label: '试卷密码前缀',
      prop: 'prefix',
      slotName: 'prefix',
      itemDescription: { description: '导用区别正常考生说试卷，导入卷密号为8位，如10000000' },
    }),
    span6({
      rowKey: 'row-4',
      label: '分隔符',
      prop: 'separator',
      slotType: 'input',
      itemDescription: { description: '文件格式为:图象文件名|标准分数' },
    }),
    span6({
      rowKey: 'row-5',
      label: '图片路径',
      slotName: 'address',
      itemDescription: { description: '试卷图片请按路径存放' },
    }),
    span6({
      rowKey: 'row-6',
      label: '导入文件',
      prop: 'file',
      slotName: 'upload',
    }),
    span6({
      rowKey: 'row-7',
      slotName: 'progress',
    }),
  ]
})

async function onSubmit() {
  try {
    const valid = await elFormRef?.value?.validate()
    if (valid) {
      showProgress.value = true
      setPercentage(0)
      await fetch(model)
      setPercentage(100)
      ElMessage.success(`导入成功`)
      elFormRef?.value?.resetFields()
      reset()
    }
  } catch (error) {
    showProgress.value = false
    setPercentage(0)
    console.error(error)
  }
}
</script>

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