<template>
  <uv-upload
    ref="fileListRef"
    :fileList="props.modelValue"
    name="1"
    :width="props.width"
    :height="props.height"
    imageMode="aspectFit"
    :maxCount="1"
    :sizeType="['compressed']"
	  :previewFullImage="false"
    :uploadText="props.uploadText"
    @afterRead="afterRead"
    @delete="deletePic"
	  @clickPreview="clickPreview"
  > 
  <view class="sfuploadBox" :style="{width:props.width,height:props.height}">
    <image src="/static/upload.png" style="width: 44rpx;height: 44rpx;" class="icon"></image>
    <text>上传图片</text>
  </view>
    <slot></slot>
  </uv-upload>
</template>

<script setup>
import { ref} from "vue";
import { useOrderApi } from "@/Apis/order.js";
import { baseImageUrl,watermarkURL} from "@/config/index.js";
const getApi = useOrderApi();
// const fileList = ref([]);
const fileListRef = ref();
const imageList = ref([]);
const props = defineProps({
  modelValue: Array,
  previewFullImage: {
    type: Boolean,
    default: false,
  },
  addWatermark:{
    type: Boolean,
    default: false,
  },
   /* 新增 ↓↓↓ */
  uploadText: {
    type: String,
    default: () => uni.$u?.t?.("unlock.uploadTip") || "Upload"
  },

  width: {
    type: String,
    default: "280rpx"
  },

  height: {
    type: String,
    default: "220rpx"
  }
});
const emit = defineEmits(["update:modelValue"]);
const clickPreview = (event) => {
  if(props.previewFullImage){
  let url = '';
  if (event.thumb) {
    url = event.thumb;
  } else {
    const reg = /^(http|https):\/\//;
    url = reg.test(event.url) ? event.url : baseImageUrl + event.url+(props.addWatermark?watermarkURL:'');
  }

	uni.previewImage({
		urls: [url],
	});
}
};
// 删除图片
const deletePic = (event) => {
  let fileList = [...props.modelValue];
  fileList.splice(event.index, 1);
  emit("update:modelValue", fileList);
};
// 上传请求
async function UploaderImage(url) {
  let url1 = "";
  try {
    const res = await getApi.UploaderImage({ filePath: url });
    // const jsonstr = JSON.parse(res);
    url1 = res.data+(props.addWatermark?watermarkURL:'');
  } catch (error) {
    // 在这里处理错误情况
    console.error("UploaderImage error:", error);
    throw error; // 抛出错误，可以让调用者处理
  }
  return url1;
}
// 新增图片方法
const afterRead = async (event) => {
  let fileList = [...props.modelValue];
  let lists = [].concat(event.file); // 将上传的文件转换为数组
  let fileListLen = fileList.length;
   
  // 给每个文件添加上传中状态
  lists.forEach((item) => {
    // 去掉默认图片
    item.thumb = null
    fileList.push({
      ...item,
      status: "uploading",
      message: "上传中",
    });
  });
  emit("update:modelValue", [...fileList]);
  // 并行上传所有图片
  const uploadPromises = lists.map(async (item, index) => {
    try {
      const result = await UploaderImage(item.url);
      fileList[fileListLen + index] = {
        ...item,
        status: "success",
        message: "",
        thumb:baseImageUrl+result,
        url: result,

      };
    } catch (error) {
      fileList[fileListLen + index] = {
        ...item,
        status: "failed",
        message: "上传失败",
        url: "",
      };
    }
  });

  // 等待所有上传任务完成
  await Promise.all(uploadPromises);
  // 所有上传完成后，发出更新事件
  emit("update:modelValue", [...fileList]);
};
</script>

<style lang="scss">
.sfuploadBox{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #F2F3F8;
  color: #6C6F73;
  border-radius: 8px;
  text{
    margin-top: 10rpx;
    font-size: 24rpx;
  }
}
::v-deep .uv-upload__deletable {
  width: 20px !important;
  height: 20px !important;
}
</style>
