<template>
  <view class="image-upload">
    <!-- 显示已选择的图片 -->
    <view class="image-list">
      <view v-for="(image, index) in imageList" :key="index" class="image-item">
        <image :src="image" mode="aspectFill" class="image"></image>
        <view class="delete-btn" @click="deleteImage(index)">×</view>
      </view>
    </view>

    <!-- 选择图片按钮 -->
    <view class="upload-btn" @click="chooseImage">
      <text>+</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      imageList: [], // 存储已选择的图片路径
    };
  },
  methods: {
    // 打开相册选择图片
    chooseImage() {
      uni.chooseImage({
        count: 9, // 最多可以选择 9 张图片
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图
        sourceType: ['album'], // 仅从相册选择
        success: (res) => {
          // 将选择的图片路径添加到 imageList 中
          this.imageList = this.imageList.concat(res.tempFilePaths);
        },
        fail: (err) => {
          console.error('选择图片失败', err);
          uni.showToast({
            title: '选择图片失败',
            icon: 'none',
          });
        },
      });
    },

    // 删除图片
    deleteImage(index) {
      this.imageList.splice(index, 1);
    },

    // 上传图片
    uploadImages() {
      if (this.imageList.length === 0) {
        uni.showToast({
          title: '请先选择图片',
          icon: 'none',
        });
        return;
      }

      // 遍历 imageList 上传每张图片
      this.imageList.forEach((imagePath) => {
        uni.uploadFile({
          url: 'https://your-upload-url.com/upload', // 替换为你的上传接口地址
          filePath: imagePath,
          name: 'file', // 文件对应的 key
          formData: {
            // 可以添加额外的表单数据
            userId: '123',
          },
          success: (uploadRes) => {
            console.log('上传成功', uploadRes);
            uni.showToast({
              title: '上传成功',
              icon: 'success',
            });
          },
          fail: (err) => {
            console.error('上传失败', err);
            uni.showToast({
              title: '上传失败',
              icon: 'none',
            });
          },
        });
      });
    },
  },
};
</script>

<style scoped>
.image-upload {
  display: flex;
  flex-wrap: wrap;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
}

.image-item {
  position: relative;
  width: 100px;
  height: 100px;
  margin: 5px;
}

.image {
  width: 100%;
  height: 100%;
  border-radius: 5px;
}

.delete-btn {
  position: absolute;
  top: 0;
  right: 0;
  width: 20px;
  height: 20px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  cursor: pointer;
}

.upload-btn {
  width: 100px;
  height: 100px;
  border: 1px dashed #ccc;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #ccc;
  margin: 5px;
  border-radius: 5px;
}
</style>