<template>
    <el-upload 
          ref="uploadProductImg"
          action="#" 
          list-type="picture-card" 
          :auto-upload="false" 
          multiple="true"
          :on-remove="handleRemove"
          @change="(event: any) => handleChange(event, 0)" 
          :on-exceed="Exceed_ProductImg"
          limit="1" >
          <el-icon>
            <Plus />
          </el-icon>
        </el-upload>
    <div>图片url: {{ imgUrl }}</div>
</template>

<script setup lang="ts">
import { ref, onMounted , inject} from 'vue';
import {  Plus } from '@element-plus/icons-vue';
import { ElMessage, type UploadFile , type UploadProps , genFileId , type UploadRawFile} from 'element-plus';
import myAxios from "@/api/myAxios";
const fileSimple = ref() //单个文件
const uploadProductImg : any = ref()  //图片上传的ref绑定
const imgUrl = ref('')
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}
const handleChange = async (file: any, flag: number) => {
  fileSimple.value = file
  let formData = new FormData()  //这一步很重要 创建一个FormData对象
  formData.append("file", fileSimple.value.raw)  //fileSimple.value.raw 才是文件主体  将其以文件的格式插入formData
  const res = await myAxios({   //编写请求，与以前的请求不同，这一次要指定好头部类型和文件类型
    url: '/file/upload/server/not_login',
    method: 'post',
    headers: {
      'content-Type': 'multipart/form-data'
    },
    data: {
      biz: "test",
      // 取出formData对象中的file
      file: formData.get("file")
    }
  })
  if (res.data.code === 1) {
    //三元运算   当flag为0时，赋值给商品图片  flag为1时，赋值给详情图片
    imgUrl.value = res.data.data
  }
}
const Exceed_ProductImg: UploadProps['onExceed'] = (files) => { //覆盖商品照片
  uploadProductImg.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  uploadProductImg.value!.handleStart(file)
}
</script>

<style scoped>

</style>