<template>
  <view class="album-deletable">
    <view
      class="album-item"
      v-for="(item, index) in urls"
      :key="index"
      :style="itemStyle"
    >
      <image
        class="album-image"
        :src="getSrc(item)"
        mode="aspectFill"
        @tap="previewFullImage ? onPreviewTap(index) : ''"
      />
      <view
        v-if="deletable"
        class="delete-btn"
        @tap.stop="handleDelete(index, item)"
      >
        <u-icon name="close-circle-fill" color="#ff4d4f" size="22"></u-icon>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'AlbumDeletable',
  props: {
    urls: {
      type: Array,
      default: () => [],
    },
    keyName: {
      type: String,
      default: '',
    },
    singleSize: {
      type: [String, Number],
      default: 180,
    },
    multipleSize: {
      type: [String, Number],
      default: 170,
    },
    space: {
      type: [String, Number],
      default: 12,
    },
    rowCount: {
      type: [String, Number],
      default: 3,
    },
    deletable: {
      type: Boolean,
      default: true,
    },
    previewFullImage: {
      type: Boolean,
      default: true,
    },
  },
  computed: {
    itemStyle() {
      const size =
        this.urls.length === 1
          ? uni.$u.addUnit(this.singleSize)
          : uni.$u.addUnit(this.multipleSize);
      return {
        width: size,
        height: size,
        marginRight: uni.$u.addUnit(this.space),
        marginBottom: uni.$u.addUnit(this.space),
      };
    },
  },
  methods: {
    getSrc(item) {
      return uni.$u.test.object(item)
        ? (this.keyName && item[this.keyName]) || item.src
        : item;
    },
    onPreviewTap(index) {
      const urls = this.urls.map((item) => this.getSrc(item));
      uni.previewImage({
        current: urls[index],
        urls,
      });
    },
    handleDelete(index, item) {
      this.$emit('delete', index, item);
    },
  },
};
</script>

<style scoped lang="scss">
.album-deletable {
  display: flex;
  flex-wrap: wrap;
}

.album-item {
  position: relative;
  flex-shrink: 0;
}

.album-image {
  width: 100%;
  height: 100%;
  border-radius: 12rpx;
}

.delete-btn {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  width: 44rpx;
  height: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  border-radius: 50%;
  z-index: 2;
}
</style>
