<template>
  <base-form ref="formRef" :label-width="useVW(88)" :groups="groups" :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="ImportRF">
/** 导入RF卷 */
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 } from 'global-type'
import type { ExtractApiParams } from 'api-type'

const showProgress = ref(false)

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

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

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

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

watch([() => model.subjectCode, () => model.mainNumber], () => {
  /** 获取导入文件路径 */
  model.subjectCode &&
    model.mainNumber &&
    getImportFilePath({
      filePathType: 'RF',
      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 groups: FormGroup[] = [
  { groupTitle: '选择大题', rowKeys: ['row-1'] },
  { groupTitle: '试卷设置', rowKeys: ['row-2', 'row-3', 'row-4'] },
  { groupTitle: '选择文件', rowKeys: ['row-5'] },
]

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: 'prefix',
      slotName: 'prefix',
      itemDescription: { description: '导用区别正常考生说试卷，导入卷密号为8位，如20000000' },
    }),
    span6({
      rowKey: 'row-3',
      label: '分隔符',
      prop: 'separator',
      slotType: 'input',
      itemDescription: { description: '文件格式为:图象文件名|标准分数' },
    }),
    span6({
      rowKey: 'row-4',
      label: '图片路径',
      slotName: 'address',
      itemDescription: { description: '试卷图片请按路径存放' },
    }),
    span6({
      rowKey: 'row-5',
      label: '导入文件',
      prop: 'file',
      slotName: 'upload',
    }),
    span6({
      rowKey: 'row-6',
      slotName: 'progress',
    }),
  ]
})

async function onSubmit() {
  try {
    const valid = await elFormRef?.value?.validate()
    if (valid) {
      showProgress.value = true
      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>
