<template>
  <div class="p-base full">
    <el-card shadow="never" class="form-card">
      <base-form
        ref="formRef"
        :label-width="useVW(120)"
        :disabled="loading"
        :groups="groups"
        :model="model"
        :items="items"
        :rules="rules"
      >
        <template #form-item-address>
          <span class="flex items-center">
            {{ filePath }}
          </span>
        </template>
        <template #form-item-import>
          <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">
          <confirm-button
            ok-text="确定导入"
            cancel-text="创建评卷分配表"
            :loading="loading"
            @confirm="onSubmit"
          ></confirm-button>
        </el-form-item>
      </base-form>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="DataMarking">
/** 导入评卷数据 */
import { computed, reactive, ref, watch } from 'vue'
import { ElButton, ElInput, ElCard, ElFormItem, ElUpload, ElMessage, ElProgress } from 'element-plus'
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 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 { subjectList, mainQuestionList, dataModel, changeModelValue } = useOptions(['subject', 'question'])

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

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

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

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

const showProgress = ref(false)

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

const model = reactive<ExtractApiParams<'importMarkingData'>>({
  subjectCode: dataModel.subject || '',
  separator: '',
  mainNumber: dataModel.question,
  dayNumber: void 0,
  file: void 0,
})

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

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

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

const rules: EpFormRules = {
  subjectCode: [{ required: true, message: '请选择科目' }],
  mainNumber: [{ required: true, message: '请选择大题' }],
  dayNumber: [{ 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'] },
  { groupTitle: '选择文件', rowKeys: ['row-5'] },
]

const span8 = defineColumn(_, '', { span: 8 })

const items = computed<EpFormItem[]>(() => {
  return [
    span8({
      rowKey: 'row-1',
      label: '科目',
      prop: 'subjectCode',
      slotType: 'select',
      slot: { placeholder: '选择科目', options: subjectList.value, onChange: changeModelValue('subject') },
    }),
    span8({
      rowKey: 'row-1',
      label: '大题',
      labelWidth: useVW(90),
      prop: 'mainNumber',
      slotType: 'select',
      slot: { placeholder: '选择大题', options: mainQuestionList.value, onChange: changeModelValue('question') },
    }),
    span8({
      rowKey: 'row-2',
      label: '分隔符',
      prop: 'separator',
      slotType: 'input',
      slot: { placeholder: '分隔符' },
    }),
    span8({
      rowKey: 'row-3',
      label: '计划评卷天数',
      prop: 'dayNumber',
      slotType: 'input',
      slot: { placeholder: '计划评卷天数' },
      itemDescription: { description: '系统将按各省考生平均分配到计划评卷天数中，确保各天的评卷进度一致' },
    }),
    span8({
      rowKey: 'row-4',
      label: '图片路径',
      slotName: 'address',
      itemDescription: { description: '试卷图片请按路径存放' },
    }),
    span8({
      rowKey: 'row-5',
      label: '导入文件',
      prop: 'file',
      slotName: 'import',
    }),
    span8({
      rowKey: 'row-6',
      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>
