<template>
  <div class="p-base full">
    <el-card shadow="never" class="form-card">
      <base-form
        ref="formRef"
        :label-width="'120px'"
        :disabled="loading"
        :groups="groups"
        :model="model"
        :items="items"
        :rules="rules"
      >
        <template #form-item-dayWeight>
          <el-input-number
            v-for="(v, i) in model.dayWeight"
            :key="i"
            v-model="model.dayWeight[i]"
            class="day-dispatch-num"
            :step="0.1"
            :max="1"
            step-strictly
            :controls="false"
          />
        </template>
        <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"
            :ok-props="{ disabled: !allowImport }"
            @confirm="onSubmit"
            @cancel="exportMarkTasks"
          ></confirm-button>
        </el-form-item>
      </base-form>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="DataMarking">
/** 导入评卷数据 */
import { computed, nextTick, reactive, ref, watch } from 'vue'
import { ElButton, ElInput, ElCard, ElFormItem, ElUpload, ElProgress, ElMessage, ElInputNumber } from 'element-plus'
import { useTimeoutFn } from '@vueuse/core'
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'
import { omit } from 'lodash-es'
// const allowImport = ref<boolean>(false)
const allowImport = ref<boolean>(true)

// const { start, stop } = useTimeoutFn(checkImportStatus, 1000)

// const { fetch: getStudentImportStatus, result: importStatus } = useFetch('getStudentImportStatus')

// watch(importStatus, () => {
//   allowImport.value = importStatus.value && !importStatus.value.importing

//   if (allowImport.value) {
//     stop()
//   }
// })

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

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

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

// watch(
//   () => importStatus.value?.progress,
//   () => {
//     if (importStatus.value?.progress) {
//       setPercentage(importStatus.value.progress)
//     }
//   }
// )

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

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

const showProgress = ref(false)

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

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

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: '请选择大题' }],
  packageTaskCount: [
    { required: true, message: '请设置每包打包人数' },
    { type: 'number', min: 0, max: 999999, message: '每包打包人数限制0-999999之间' },
  ],
  dayNumber: [
    { required: true, message: '请设置计划评卷天数' },
    { type: 'number', min: 0, max: 999999, message: '计划评卷天数限制0-999999之间' },
  ],
  separator: [{ required: true, message: '请设置分隔符' }],
  file: [{ required: true, message: '请选择导入文件' }],
  dayWeight: [
    { required: true, message: '请完善按天分配值' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (!model.dayWeight.every((v: any) => !!v)) {
          callback(new Error('每日分配的数值不能为空或者0'))
        } else if (
          Number(
            model.dayWeight.reduce((total: number, v: number) => {
              return (total * 100 + v * 100) / 100
            }, 0) !== Number(model.dayNumber)
          )
        ) {
          callback(new Error('相加总和必须等于计划评卷天数'))
        } else {
          callback()
        }
      },
    },
  ],
}

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

const span7 = defineColumn(_, '', { span: 7 })
const span24 = defineColumn(_, '', { span: 24 })
const showDayWeight = ref(false)
const checkDays = (val: any) => {
  console.log(val, typeof val)
  const isFloat = String(val).indexOf('.') > -1
  showDayWeight.value = isFloat
  if (!isFloat) {
    model.dayWeight = new Array(val).fill(1)
  } else {
    let arr = String(val).split('.')
    let left = Number(arr[0])
    let right = Number('0.' + arr[1])
    model.dayWeight = new Array(left).fill(1)
    model.dayWeight.unshift(right)
  }
  elFormRef?.value?.validateField('dayWeight')
}
const items = computed<EpFormItem[]>(() => {
  return [
    span7({
      rowKey: 'row-1',
      label: '科目',
      prop: 'subjectCode',
      slotType: 'select',
      slot: { placeholder: '选择科目', options: subjectList.value, onChange: changeModelValue('subject') },
    }),
    span7({
      rowKey: 'row-1',
      label: '大题',
      prop: 'mainNumber',
      slotType: 'select',
      slot: { placeholder: '选择大题', options: mainQuestionList.value, onChange: changeModelValue('question') },
    }),
    span7({
      rowKey: 'row-2',
      label: '分隔符',
      prop: 'separator',
      slotType: 'input',
      slot: { placeholder: '分隔符' },
    }),
    span7({
      rowKey: 'row-3',
      label: '每包打包人数',
      prop: 'packageTaskCount',
      slotType: 'inputNumber',
      slot: { placeholder: '每包打包人数', step: 1, stepStrictly: true },
    }),
    span7({
      rowKey: 'row-4',
      label: '计划评卷天数',
      prop: 'dayNumber',
      slotType: 'inputNumber',
      slot: {
        placeholder: '计划评卷天数',
        step: 0.1,
        stepStrictly: true,
        onChange: checkDays,
      },
      itemDescription: { description: '系统将按各省考生平均分配到计划评卷天数中，确保各天的评卷进度一致' },
    }),
    showDayWeight.value
      ? span24({
          rowKey: 'row-5',
          label: '按天分配',
          slotName: 'dayWeight',
          prop: 'dayWeight',
        })
      : {},
    span7({
      rowKey: 'row-6',
      label: '图片路径',
      slotName: 'address',
      itemDescription: { description: '试卷图片请按路径存放' },
    }),
    span7({
      rowKey: 'row-7',
      label: '导入文件',
      prop: 'file',
      slotName: 'import',
    }),
    span7({
      rowKey: 'row-8',
      slotName: 'progress',
    }),
  ]
})

function checkImportStatus() {
  // getStudentImportStatus().finally(() => {
  //   nextTick(() => {
  //     if (!allowImport.value) {
  //       start()
  //     }
  //   })
  // })
}

async function onSubmit() {
  try {
    const valid = await elFormRef?.value?.validate()
    if (valid) {
      showProgress.value = true
      setPercentage(0)
      await importMarkingData({ ...omit(model, 'dayNumber'), dayWeight: model.dayWeight.join(',') })
      ElMessage.success(`导入成功，您可以稍后去“任务信息报告”页面进行查询`)
      // checkImportStatus()
    }
  } catch (error) {
    showProgress.value = false
    setPercentage(0)
    console.error(error)
  }
}

async function exportMarkTasks() {
  try {
    const subjectCodeValid = await elFormRef?.value?.validateField('subjectCode')
    const mainNumberValid = await elFormRef?.value?.validateField('mainNumber')
    const dayNumberValid = await elFormRef?.value?.validateField('dayNumber')
    subjectCodeValid &&
      mainNumberValid &&
      dayNumberValid &&
      (await useFetch('exportStudentTask').fetch({
        subjectCode: model.subjectCode,
        // dayNumber: model.dayNumber!,
        mainNumber: model.mainNumber!,
      }))
  } catch (error) {
    console.error(error)
  }
}

// getStudentImportStatus()
</script>

<style scoped lang="scss">
.day-dispatch-num {
  width: 50px;
  margin-right: 5px;
  margin-bottom: 5px;
  :deep(.el-input__wrapper) {
    padding-left: 10px;
    padding-right: 10px;
  }
}
</style>
