<template>
  <view class="form-image">
    <view class="image-list">
      <view v-for="(item, index) in imageList" :key="index" class="image-item">
        <image :src="item" mode="aspectFill" class="preview-image" @click="previewImage(index)" />
        <view class="delete-btn" @click.stop="deleteImage(index)">
          <text class="delete-icon">&times;</text>
        </view>
      </view>
      <view v-if="imageList.length < maxCount" class="image-item add-btn" @click="chooseImage">
        <text class="add-icon">+</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: "FormItemImage",
  props: {
    value: { type: Array, default: function() { return []; } },
    maxCount: { type: Number, default: 9 }
  },
  data: function() {
    return {
      imageList: []
    };
  },
  watch: {
    value: {
      handler: function(val) {
        this.imageList = Array.isArray(val) ? val.slice() : [];
      },
      immediate: true
    }
  },
  methods: {
    chooseImage: function() {
      var remaining = this.maxCount - this.imageList.length;
      if (remaining <= 0) return;
      var self = this;
      uni.chooseImage({
        count: remaining,
        sizeType: ["compressed"],
        sourceType: ["album", "camera"],
        success: function(res) {
          self.imageList = self.imageList.concat(res.tempFilePaths);
          self.$emit("input", self.imageList);
        }
      });
    },
    deleteImage: function(index) {
      this.imageList.splice(index, 1);
      this.$emit("input", this.imageList);
    },
    previewImage: function(index) {
      uni.previewImage({
        urls: this.imageList,
        current: index
      });
    }
  }
};
</script>

<style scoped>
.form-image {
  width: 100%;
}
.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}
.image-item {
  width: 200rpx;
  height: 200rpx;
  border-radius: 8rpx;
  overflow: hidden;
  position: relative;
}
.preview-image {
  width: 100%;
  height: 100%;
}
.delete-btn {
  position: absolute;
  top: 0;
  right: 0;
  width: 40rpx;
  height: 40rpx;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
}
.delete-icon {
  color: #ffffff;
  font-size: 28rpx;
}
.add-btn {
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2rpx dashed #cccccc;
}
.add-icon {
  font-size: 60rpx;
  color: #999999;
}
</style>
