<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="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,defineProps,watch,onUpdated } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import { uploadUrl, downloadUrl } 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 emit = defineEmits<Emits>()
const props = defineProps<Props>()  //接收父组件传来的props
const previwUrl = ref('')
const flag = ref(0)


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

interface Props {
  ImgUrlList: string;
}

onUpdated(()=>{   //组件数据更新后调用
  if(flag.value === 0){
    formatImgUrlList()
  }
})


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 formatImgUrlList = () => {   //回显多张图片
  flag.value = 1
  goodImgArr.value = previwUrl.value.split(';')
  // console.log('分号隔开的数组--->',goodImgArr.value)
  goodImgArr.value.forEach(item => {   //回显
    ImgList.value.push({
      url: downloadUrl + item
    })
  })
  goodImgStr.value = goodImgArr.value.join(';')   //还原objectKey字符串
}

const ImgList: any = ref([])

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 => item !== 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) {
    goodImgArr.value.push(res.data.data)
    goodImgStr.value = goodImgArr.value.join(';')   //上传一张就更新一下goodImgStr
    loading.value = false
  }
}

watch(()=> props.ImgUrlList, (newVal) => {
  previwUrl.value = newVal
})

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