<template>
  <section class="create_land_attrs_content_">
    <el-upload
      v-if="props.view != 'view'"
      class="custom-form__uploader"
      action=""
      :show-file-list="false"
      :accept="props.accept"
      :limit="20"
      :http-request="rowUploadPicture"
    >
      <el-icon class="custom-form__uploader__icon"><Plus /></el-icon>
    </el-upload>
    <div v-for="item in attrs_" :key="`attr_${item.uid}`" class="attrs_content__item">
      <img :src="item.url" :alt="item.name" style="" />
      <el-icon v-if="props.view != 'view'" class="clear_btn" @click="handleClearAttr(item.uid)"><CircleCloseFilled /></el-icon>
    </div>
  </section>
</template>
<script setup>
import { ref, watch } from 'vue';
import { CommonUpload } from '@/apis';

const emit = defineEmits(['update:attrs']);
const props = defineProps({
  accept: {
    type: String,
    default: 'image/*',
  },
  view: {
    type: String,
    default: 'view',
  },
  attrs: {
    type: Array,
    default: () => [],
  },
});
const attrs_ = ref([]);
watch(
  () => props.attrs,
  (val) => {
    attrs_.value = val;
  },
  { deep: true, immediate: true }
);
function handleClearAttr(uid) {
  attrs_.value = attrs_.value.filter((item) => item.uid !== uid);
  emit('update:attrs', attrs_.value);
}
async function rowUploadPicture({ file }) {
  const formData = new FormData();
  formData.append('file', file);
  const res = await CommonUpload(formData);
  if (res.code === 200) {
    attrs_.value.push({
      ...res.data,
      uid: 'id_' + Date.now(),
    });
    emit('update:attrs', attrs_.value);
  }
}
</script>

<style lang="scss">
.create_land_attrs_content_ {
  display: flex;
  flex-wrap: wrap;
  box-sizing: border-box;
  gap: 20px;
  .custom-form__uploader {
    box-sizing: border-box;
    height: auto;
  }
  > div {
    width: calc(50% - 10px);
    aspect-ratio: 1 / 1;
  }
  .attrs_content__item {
    box-sizing: border-box;
    position: relative;
    padding: 6px;
    border: 1px solid #ccc;
    border-radius: 4px;
    img {
      width: 100%;
      height: 100%;
      border-radius: 2px;
    }
    .clear_btn {
      position: absolute;
      right: 0px;
      top: 0px;
      font-size: 18px;
      color: #f15c5c;
      opacity: 0;
      cursor: pointer;
      background-color: #fff;
      border-radius: 50%;
    }
    &:hover {
      .clear_btn {
        opacity: 1;
      }
    }
  }
}
</style>
