<template>
  <Dialog   loading="loading"  v-model="dialogVisible" title="标本信息导入" width="600">
    <el-alert title="需确保图片命名规范，不与系统中旧图片命名重复，否则将会覆盖原图片。" type="warning" style="margin-bottom: 10px"/>
    <el-upload
      ref="uploadRef"
      v-model:file-list="fileList"
      :action="  importUrl + '?updateSupport=' + updateSupport"
      :auto-upload="false"
      :disabled="formLoading"
      :headers="uploadHeaders"
      :limit="1"
      :on-error="submitFormError"
      :on-exceed="handleExceed"
      accept=".xlsx, .xls"
      drag
    >
      <Icon icon="ep:upload" />
      <div class="el-upload__text">将xlsx表拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip text-center">
          <span>仅允许导入 xls、xlsx 格式文件。</span>
          <el-link
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            type="primary"
            @click="importTemplate"
          >
            下载模板
          </el-link>
          <div class="el-upload__tip"  style="color:#ff0000;">
            <el-checkbox v-model="updateSupport"/>
            是否更新已经存在的标本数据
          </div>
        </div>
      </template>
    </el-upload>

    <el-upload
      ref="uploadimageRef"
      v-model:file-list="imageList"
      drag
      :action="importUrl + '?updateSupport=' + updateSupport + '&updateType=' + updateType"
      :on-success="submitImageSuccess"
      :auto-upload="false"
      :disabled="formLoading"
      :limit="1"
      :on-error="submitFormError"
      :headers="uploadHeaders"
      accept=".zip"
    >
      <el-icon class="el-icon--upload">
        <upload-filled/>
      </el-icon>
      <div class="el-upload__text">
        <div class="el-upload__text">将图片压缩包拖到此处，或<em>点击上传</em></div>
      </div>
      <template #tip>
        <div class="el-upload__tip text-center">
          <span>仅允许导入 .zip 格式文件。</span>
<!--          <div class="el-upload__tip">-->
<!--            <el-checkbox v-model="updateSupport"/>-->
<!--            是否更新已经存在的标本数据-->
<!--          </div>-->
        </div>
      </template>
    </el-upload>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import download from '@/utils/download'
import {getAccessToken, getTenantId} from '@/utils/auth'
import {SpecimenInfoApi} from "@/api/museums/specimeninfo";
import {ref, nextTick} from 'vue';
import {UploadFilled} from "@element-plus/icons-vue";
import {useUpload} from "@/components/UploadFile/src/useUpload";

defineOptions({name: 'SpecimenImportForm'})
const loading = ref(true) // 列表的加载中
const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const uploadRef = ref()
const uploadimageRef = ref()

const message = useMessage() // 消息弹窗
import axios from 'axios';
const updateType = ref(-1)
const updateSupport = ref(true) // 是否更新已经存在的用户数据
const fileList = ref([]) // 文件列表
const imageList = ref([])
const uploadHeaders = ref() // 上传 Header 头
const importUrl =
  import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/museums/specimen-info/import-specimen-with-images'

/** 打开弹窗 */
const open = (typeNum : any) => {
  loading.value = true
  dialogVisible.value = true
  updateSupport.value = true
  if(typeNum != null && typeNum != '' && typeNum != undefined){
    updateType.value = typeNum
  }else {
     updateType.value = -1
  }
  fileList.value = []
  imageList.value = []
  resetForm()
}
defineExpose({open}) // 提供 open 方法，用于打开弹窗
const { httpRequest } = useUpload()

/** 提交表单 */
const submitForm = async () => {
  if (fileList.value.length == 0 ) {
    message.error('必须上传EXCEL文件')
    return
  }
  // 提交请求
  uploadHeaders.value = {
    Authorization: 'Bearer ' + getAccessToken(),
    'tenant-id': getTenantId()
  }
  formLoading.value = true
  const formData = new FormData()
  if (fileList.value.length > 0) {
    formData.append('file', fileList.value[0].raw)
  }
  if (imageList.value.length > 0) {
    formData.append('imageFile', imageList.value[0].raw)
  }

  try {
    const response = await axios.post(importUrl + '?updateSupport=' + updateSupport.value
      + '&updateType=' + updateType.value, formData, {
      headers: {
        ...uploadHeaders.value,
        'Content-Type': 'multipart/form-data'
      }
    });
    console.log(123)
    submitFormSuccess(response)
    console.log(1233333)
  } catch (error) {
    submitFormError()
  } finally {
    formLoading.value = false;
  }
};
/** 文件上传成功 */
const emits = defineEmits(['success'])
const submitFormSuccess = (response: any) => {
  console.log('上传响应:', response)
  // console.log(response.data.code != 0 , response.data.code)
  if (response.data.code != 0) {
    message.error(response.data.msg)
    return
  }
  if (response.data.code == -19) {
    message.error(response.data.msg)
    // formLoading.value = false
    return
  }
  // 拼接提示语
  const data = response.data.data
  // console.log(data)
  let text = '';
  if(data.createSpecimenNumbers != null){
    text += '上传成功数量：' + data.createSpecimenNumbers.length + ';'
    for (let specimenInfodata of data.createSpecimenNumbers) {
      text += '标本编号：' + specimenInfodata + '、'
    }
  }
  if(data.updateSpecimenNumbers != null){
    text += '。更新成功数量：' + data.updateSpecimenNumbers.length + ';'
    for (const specimenInfodata of data.updateSpecimenNumbers) {
      text += '标本编号：' + specimenInfodata + '、'
    }
  }
  console.log('上传响应:2', response)
  if(JSON.stringify(data.failureSpecimenNumbers) != '{}' &&data.failureSpecimenNumbers != null) {
    text += '。更新失败数量：' + Object.keys(data.failureSpecimenNumbers).length + ';'
    for (const specimenInfodata in data.failureSpecimenNumbers) {
      text += '< ' + specimenInfodata + ': ' + data.failureSpecimenNumbers[specimenInfodata] + ' >'
    }
  }
  console.log('上传响应:3', response)
  if(data.createSpecimenImages != null){

    text += '图片上传成功数量：' + data.createSpecimenImages.length + ';'
    for (let specimenInfodata of data.createSpecimenImages) {
      text += '图片名称：' + specimenInfodata + '、'
    }
  }
    console.log('上传响应:4', response)

  if(JSON.stringify(data.failureSpecimenImages) != '{}' && data.failureSpecimenImages != null) {
    text += '图片上传失败数量：' + Object.keys(data.failureSpecimenImages).length + ';'
    for (let specimenInfodata in data.failureSpecimenImages) {
      text += '< ' + specimenInfodata + ': ' + data.failureSpecimenImages[specimenInfodata] + ' >'
    }
  }

  console.log(555)
  message.alert(text)
  // formLoading.value = false
  dialogVisible.value = false
  // 发送操作成功的事件
  emits('success')
  formLoading.value = false
}

/** 上传错误提示 */
const submitFormError = (): void => {
  message.error('上传失败，请您重新上传！')

  formLoading.value = false
  dialogVisible.value = false
}

/** 重置表单 */
const resetForm = async (): Promise<void> => {
  // 重置上传状态和文件
  formLoading.value = false
  updateSupport.value = true
  await nextTick()
  uploadRef.value?.clearFiles()
  uploadimageRef.value?.clearFiles()
}

/** 文件数超出提示 */
const handleExceed = (): void => {
  message.error('最多只能上传一个文件！')
}
/** 下载模板操作 */
const importTemplate = async () => {
  const res = await SpecimenInfoApi.importSpecimenInfoTemplate(updateType.value)
  download.excel(res, '标本批量导入模版.xls')
}


/** 图片上传成功 */

// const submitImageSuccess = (response: any) => {
//   console.log('tj',response)
//   if (response.data.code !== 0) {
//     message.error(response.msg)
//     formLoading.value = false
//
//     return
//   }
//   formLoading.value = false
//   dialogVisible.value = false
//   // 发送操作成功的事件
//
// }


</script>
