<template>
  <!--  批量图片上传  -->
  <el-upload
      v-model:file-list="ImgList"
      action="#"
      list-type="picture-card"
      :http-request="compressImage"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-exceed="ExceedImg"
      limit="1"
      v-loading="loading">
    <el-icon><Plus /></el-icon>
  </el-upload>
  <el-dialog v-model="dialogVisible">
    <el-image :src="dialogImageUrl"/>
  </el-dialog>
</template>

<script lang="ts" setup>
import myAxios from '@/api/myAxios'
import { ref,defineEmits,watch } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import { uploadUrl } from '@/utils/formatImgUpload'
import { WarnInfo } from "@/utils/messageInfo";
import Compressor from "compressorjs";

const goodImgStr = ref('')  //图片字符串
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const loading = ref(false)
const ImgList: any = ref([])
const emit = defineEmits<Emits>()   //向父组件传递数据

interface Emits {
  (event: 'update:goodImgArr' , newVal: string): void
}


const compressImage =(file: any)=> {   //图片压缩方法
  // console.log('compressImage',file)
  return new Promise((resolve, reject) => {
    new Compressor(file.file, {
      quality: 0.2,   //压缩质量，越高文件越大
      success(result) {
        // console.log('res--->',result)
        // 压缩成功后的处理
        const compressedFile = new File([result], file.file.name, { type: result.type });
        // 可以在这里预览、上传或者做其他处理
        // console.log("Compressed file:", compressedFile);
        // 如果需要上传，可以在这里执行上传操作
        customUpload(compressedFile)
        // resolve(compressedFile);
      },
      error(err) {
        reject("压缩失败");
        console.log("Compressor error:", err.message);
      }
    });
  });
}


const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {  //前者是删掉的，后者是删掉后得数组
  goodImgStr.value = ''
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

const ExceedImg: UploadProps['onExceed'] = (files) => { //覆盖商品照片   'onExceed'当文件个数超过限制时，做出的判断
  WarnInfo('请删掉后再上传')
}

//图片上传方法
const customUpload = async (file:any) => {
  loading.value = true
  const res = await  myAxios({
    url: uploadUrl,
    method: 'post',
    headers: {
      'Content-Type': 'multipart/form-data',
    },
    data: {
      biz: "test",
      file: file
    }
  })
  console.log('图片上传--->',res)
  if(res.data.code === 1) {
    goodImgStr.value = res.data.data
    loading.value = false
  }
}

watch(goodImgStr, (newVal:any) => {
  emit('update:goodImgArr', newVal)
})
</script>