<template>
  <section class="create_land_attrs_content_" :style="{ '--columns': props.fileNum }">
    <el-upload
      v-if="props.type != 'view'"
      class="custom-form__uploader"
      action=""
      :show-file-list="false"
      :accept="props.accept"
      :limit="props.limit"
      :http-request="rowUploadPicture"
      :disabled="attrs_.length >= props.limit"
    >
      <el-icon class="custom-form__uploader__icon"><Plus /></el-icon>
    </el-upload>
    <div v-for="item in attrs_" :key="`attr_${item.id}`" class="attrs_content__item">
      <video v-if="isMP4(item.url)" :src="item.url" controls />
      <img v-else :src="item.url" :alt="item.name" />
      <el-icon v-if="props.type != 'view'" class="clear_btn" @click="handleClearAttr(item.id)"><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/*',
  },
  type: {
    type: String,
    default: 'view',
  },
  attrs: {
    type: Array,
    default: () => [],
  },
  limit: {
    type: Number,
    default: 20,
  },
  fileNum: {
    type: Number,
    default: 4,
  },
});
const attrs_ = ref([]);
watch(
  () => props.attrs,
  (val) => {
    attrs_.value = val;
  },
  { deep: true, immediate: true }
);
function handleClearAttr(id) {
  attrs_.value = attrs_.value.filter((item) => item.id !== id);
  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,
      id: 'id_' + Date.now(),
    });
    emit('update:attrs', attrs_.value);
  }
}
function isMP4(filePath) {
  // 使用正则表达式检查文件路径是否以 .mp4 结尾（不区分大小写）
  const regex = /\.mp4$/i;
  return regex.test(filePath);
}
</script>

<style lang="scss">
.create_land_attrs_content_ {
  display: grid;
  flex-wrap: wrap;
  grid-template-columns: repeat(var(--columns), 1fr);
  box-sizing: border-box;
  gap: 20px;
  .custom-form__uploader {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
  }
  > div {
    aspect-ratio: 1 / 1;
  }
  .attrs_content__item {
    box-sizing: border-box;
    position: relative;
    padding: 6px;
    border: 1px solid #ccc;
    border-radius: 4px;
    img,
    video {
      vertical-align: middle;
      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>
