<template>
  <view class="upload-container">
    <!-- 图片展示区域 -->
    <view class="image-list">
      <!-- 添加按钮 -->
      <view
        v-if="images.length < maxCount"
        class="add-btn"
        @click="chooseImage"
      >
      </view>
      <view
        v-for="(item, index) in images"
        :key="index"
        class="image-item"
        @click="previewImage(index)"
      >
        <image :src="item" class="image" mode="aspectFill"></image>
        <text class="delete-icon" @click.stop="deleteImage(index)">×</text>
      </view>
    </view>
    <!-- 提示文字 -->
    <view class="tip">
      <slot name="tip">
        请对检查项进行拍照留存（限{{
          maxCount
        }}张）。发现“异常、告警”时，需拍照留存。
      </slot>
    </view>
  </view>
</template>

<script>
import { createFolder, copyImage } from "@/utils/plus.js";
export default {
  name: "CommonUpload",
  props: {
    value: {
      type: Array,
      default: () => [],
    },
    maxCount: {
      type: Number,
      default: 5, // 默认最多上传 5 张图片
    },
    sourceType: {
      type: Array,
      default: () => ["camera"], // 默认从相机拍摄
    },
    sizeType: {
      type: Array,
      default: () => ["compressed"], // 默认压缩图 ["original", "compressed"]
    },
  },
  data() {
    return {
      images: this.value, // 绑定的图片数组
    };
  },
  watch: {
    value(newVal) {
      this.images = newVal;
    },
    images(newVal) {
      this.$emit("input", newVal); // 同步更新父组件绑定的数据
    },
  },
  mounted() {},
  methods: {
    // 检查存储权限
    async checkPermission() {
      return new Promise((resolve) => {
        plus.android.requestPermissions(
          ["android.permission.WRITE_EXTERNAL_STORAGE"],
          (result) => resolve(result.granted),
          (err) => {
            console.error("权限请求失败：", err.message);
            resolve(false);
          }
        );
      });
    },

    // 选择图片并保存到应用目录
    async chooseImage() {
      const hasPermission = await this.checkPermission();
      if (!hasPermission) {
        uni.showToast({ title: "无存储权限，请授权", icon: "none" });
        return;
      }

      await createFolder("data/photos");

      uni.chooseImage({
        count: this.maxCount - this.images.length,
        sizeType: this.sizeType,
        sourceType: this.sourceType,
        success: async (res) => {
          for (const tempFilePath of res.tempFilePaths) {
            try {
              const saveRes = await uni.saveImageToPhotosAlbum({
                filePath: tempFilePath,
              });
              console.log("path", saveRes.path);
              const fileName = saveRes.path.split("/").pop();
              const targetPath = `_documents/data/photos/${fileName}`;
              console.log("targetPath", targetPath);
              const savedPath = await copyImage(saveRes.path, targetPath);
              console.log("savedPath", savedPath);
              this.images.push(savedPath);
            } catch (err) {
              console.error("保存失败：", err);
              uni.showToast({ title: "图片保存失败", icon: "none" });
            }
          }
        },
      });
    },

    // 预览图片
    previewImage(index) {
      uni.previewImage({
        current: index,
        urls: this.images,
      });
    },
    // 删除图片
    deleteImage(index) {
      this.images.splice(index, 1);
    },
    // 转换文件为 Base64
    convertFileToBase64(filePath) {
      return new Promise((resolve, reject) => {
        plus.io.resolveLocalFileSystemURL(
          filePath,
          (entry) => {
            entry.file(
              (file) => {
                const reader = new plus.io.FileReader();
                reader.onloadend = (evt) => {
                  resolve(evt.target.result); // 返回 Base64 数据
                };
                reader.readAsDataURL(file); // 读取文件并转换为 Base64
              },
              (error) => {
                reject("获取文件对象失败：" + error.message);
              }
            );
          },
          (error) => {
            reject("解析文件路径失败：" + error.message);
          }
        );
      });
    },
  },
};
</script>

<style scoped lang="scss">
.upload-container {
}

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

.image-item {
  position: relative;
  width: 72px;
  height: 72px;
  margin-right: 10px;
}

.image {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}

.delete-icon {
  position: absolute;
  top: -6.4px;
  right: -6.4px;
  background-color: #ff4d4f;
  color: #fff;
  width: 12.8px;
  height: 12.8px;
  border-radius: 50%;
  text-align: center;
  line-height: 12.8px;
  font-size: 9.6px;
}

.add-btn {
  position: relative;
  width: 72px;
  height: 72px;
  border: 1px dashed #ccc;
  cursor: pointer;
  margin-right: 10px;
  box-sizing: border-box;

  &::before {
    position: absolute;
    content: "";
    width: 30px;
    height: 2px;
    background-color: #ccc;
    left: 50%;
    top: 50%;
    transform: translateX(-50%) translateY(-50%);
  }

  &::after {
    position: absolute;
    content: "";
    width: 2px;
    height: 30px;
    background-color: #ccc;
    left: 50%;
    top: 50%;
    transform: translateX(-50%) translateY(-50%);
  }
}

.tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}
</style>
