<template>
  <base-form
    ref="formRef"
    :label-width="'120px'"
    :groups="groups"
    :rules="rules"
    :items="items"
    :model="model"
    :disabled="loading"
  >
    <template #form-item-prefix>
      <span class="full-w flex items-center">
        <el-input v-model="model.prefix" class="flex-1"></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>
  <import-method
    v-model:visible="importMethodVisible"
    v-model:clear="clear"
    :check-status="curCheckStatus"
    @sure="sureImport"
  ></import-method>
</template>

<script setup lang="ts" name="ImportSample">
/** 导入培训卷 */
import { reactive, watch, computed, ref } from 'vue'
import { ElFormItem, ElButton, ElUpload, ElInput, ElMessage, ElProgress, ElRadioGroup, ElRadio } 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 ImportMethod from './importMethod.vue'

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 { fetch: checkFetch, loading: checkLoading } = useFetch('importCheck')

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 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: '100px',
      prop: 'mainNumber',
      slotType: 'select',
      slot: { placeholder: '选择大题', options: mainQuestionList.value, onChange: changeModelValue('question') },
    }),
    span8({
      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卷' },
    }),
    span8({
      rowKey: 'row-3',
      label: '试卷密号前缀',
      prop: 'prefix',
      slotName: 'prefix',
      itemDescription: { description: '导用区别正常考生说试卷，导入卷密号为8位，如10000000' },
    }),
    span8({
      rowKey: 'row-4',
      label: '分隔符',
      prop: 'separator',
      slotType: 'input',
      itemDescription: { description: '文件格式为:图象文件名|标准分数' },
    }),
    span8({
      rowKey: 'row-5',
      label: '图片路径',
      slotName: 'address',
      itemDescription: { description: '试卷图片请按路径存放' },
    }),
    span8({
      rowKey: 'row-6',
      label: '导入文件',
      prop: 'file',
      slotName: 'upload',
    }),
    span8({
      rowKey: 'row-7',
      slotName: 'progress',
    }),
  ]
})

// const clearMethod = ref('追加导入')
const importMethodVisible = ref(false)
const curCheckStatus = ref('')
const clear = ref(false)
const sureImport = () => {
  // clear.value = clearMethod.value === '清空导入'
  submitHandler()
}
// const cancelImport = () => {
//   importMethodVisible.value = false
// }
const submitHandler = async () => {
  showProgress.value = true
  setPercentage(0)
  await fetch({ ...model, clear: clear.value })
  setPercentage(100)
  ElMessage.success(`导入成功`)
  elFormRef?.value?.resetFields()
  reset()
  importMethodVisible.value = false
}
async function onSubmit() {
  try {
    const valid = await elFormRef?.value?.validate()
    if (valid) {
      let checkRes: any = await checkFetch({
        mainNumber: model.mainNumber,
        subjectCode: model.subjectCode,
        paperType: model.paperType,
      })
      console.log('checkRes:', checkRes)
      curCheckStatus.value = checkRes
      // clearMethod.value = '追加导入'
      clear.value = false
      if (checkRes === 'CHOOSE' || checkRes === 'APPEND') {
        importMethodVisible.value = true
      } else {
        submitHandler()
      }

      // 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>
