<template>
<!--  批量图片上传  -->
  <el-upload
      v-model:file-list="ImgList"
      action="#"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-exceed="ExceedImg"
      :http-request="compressImage"
      limit="7"
      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 goodImgArr= ref<String[]>([])  //后端数据库返回的图片objectKey
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) => {  //前者是删掉的，后者是删掉后得数组
  // console.log(uploadFile)
  // let deleteObjKey = uploadFile.url?.substring(downloadUrl.length)
  // console.log('格式化后的数组--->',deleteObjKey)
  goodImgArr.value = goodImgArr.value.filter((item)=>{   //根据相同文件名过滤掉已删掉的
    return !item.includes(replaceSpecialChars(uploadFile.name))
  })
  goodImgStr.value = goodImgArr.value.join(';')
}

const replaceSpecialChars = (input : any) => {   //上传文件后一些特殊字符(+、&)会替换为下划线，文件名也要替换
  // 使用正则表达式替换非中文、字母、数字和点号的字符为下划线
  return input.replace(/[^a-zA-Z0-9\u4e00-\u9fa5.]/g, '_');
}

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.data)
  if(res.data.code === 1) {
    goodImgStr.value = ''
    goodImgArr.value.push(res.data.data)
    goodImgStr.value = goodImgArr.value.join(';')
    loading.value = false
  }
}

watch(goodImgStr, (newVal:any) => {
  emit('update:goodImgArr', newVal)
  // console.log('监听的新变化--->',newVal)
})
</script>