<template>
  <view class="Mall4j component-upload-imgs">
    <!-- 多图 -->
    <view class="upload">
      <!-- 图片列表 -->
      <view
        v-for="(item, index) in imgFiles"
        :key="index"
        class="preview"
      >
        <image
          v-if="imgFiles.length > 0 && imgFiles.length <= imgNum"
          :src="item.url"
          :data-index="index"
          @tap="getUploadImg"
        />
        <view
          class="del"
          @tap="removeImgByIndex(index)"
        >
          <image src="@/static/images/close-w.png" />
        </view>
        <view
          class="preview-img"
          @tap="previewImage(index)"
        >
          预览
        </view>
      </view>
      <!-- 上传按钮 -->
      <view
        v-if="imgFiles.length < imgNum"
        class="upload-chequer"
        @tap="getUploadImg"
      >
        <view class="cross">
          ＋
        </view>
      </view>
    </view>
    <helang-compress ref="hCompressRef" />
  </view>
</template>

<script setup>
import util from '../../utils/util'

const props = defineProps({
  imgsId: {
    type: [String, Number],
    default: ''
  },
  imgNum: { // 图片上传数量，默认1，最大9
    type: Number,
    default: 1
  },
  imgUrls: {
    type: Array,
    default: () => {}
  }
})

const emit = defineEmits(['getImagePath', 'getImagePath'])

const resourcesUrl = import.meta.env.VITE_APP_RESOURCES_URL

const imgFiles = ref([]) // 已上传图片列表
watch(
  () => props.imgUrls,
  (newVal, oldVal) => {
    if (!oldVal && newVal) {
      imgFiles.value = newVal
    }
  }
)

onMounted(() => {
  if (props.imgUrls) imgFiles.value = props.imgUrls
})

onUnmounted(() => {
  if (isShowPreview) {
    uni.closePreviewImage({
      success: () => {
        isShowPreview = false
      }
    })
  }
})

/**
 * 上传图片
 */
let imgIndex = null // 当前点击的图片下标
const tempFiles = ref(null)
const tempFilePaths = ref([]) // 图片上传列表
const getUploadImg = (e) => {
  imgIndex = e.currentTarget.dataset.index
  let imgNum = null
  if (!imgFiles.value.length) {
    imgNum = props.imgNum
  } else if (imgFiles.value.length > 0 && imgFiles.value.length < props.imgNum) {
    imgNum = props.imgNum - imgFiles.value.length
  } else if (imgFiles.value.length === props.imgNum) {
    imgNum = 1
  }

  uni.chooseImage({
    count: imgNum, // 默认9
    sizeType: ['original', 'compressed'],
    sourceType: ['album'],
    success: (res) => {
      // 图片的本地临时文件路径列表
      tempFilePaths.value = res.tempFilePaths
      tempFiles.value = res.tempFiles
      beforeUpload()
    }
  })
}

/**
 * 校验图片合法性
 */
const hCompressRef = ref(null)
const feilType = ref(null) // 文件类型
const beforeUpload = () => {
  if (!tempFiles.value) {
    return
  }
  feilType.value = tempFiles.value ? tempFiles.value[0].type?.split('/') : null
  if (feilType.value && feilType.value[0] !== 'image') {
    uni.showToast({
      title: '只能上传图片,其他文件已清除',
      icon: 'none'
    })
    tempFilePaths.value = []
    tempFiles.value = []
    return
  }
  getUploadData()
}

/**
 * 获取上传图片数据
 */
const ossList = ref(null)
const notImg = ref(false)
const getUploadData = () => {
  const fileNames = tempFiles.value?.map(item => {
    let fileName = ''
    // #ifdef H5
    fileName = item.name
    // #endif
    // #ifdef APP-PLUS || MP-WEIXIN
    fileName = item.path
    // #endif
    return fileName
  }).join(',')
  http.request({
    url: '/tmerclub_biz/ua/oss/get_batch_pre_sign_url',
    method: 'GET',
    data: {
      fileNames
    }
  }).then((data) => {
    ossList.value = data
    notImg.value = true
    confirmUpload()
  })
}

/**
 * 确认上传
 */
const attachFiles = ref([])
const confirmUpload = () => {
  const attachFile = Object.assign({
    fileType: 'image',
    fileName: tempFiles.value[0].name,
    fileSize: tempFiles.value[0].size,
    type: 1
  })
  if (ossList.value.length <= 0) {
    uni.showToast({
      title: '数据异常，请刷新后重试',
      icon: 'none'
    })
  }
  // aws文件上传
  util.awsUpload(ossList.value, tempFiles.value).then(() => {
    ossList.value.forEach((item) => {
      const filePath = item.dir + item.fileName
      onUploadSuccess(filePath)
    })
  })
  attachFiles.value.push(attachFile)
}

const onUploadSuccess = (filePath) => {
  const halfPath = '/' + filePath
  if (imgIndex >= 0) {
    imgFiles.value[imgIndex] = {
      url: resourcesUrl + halfPath,
      path: halfPath
    }
  } else {
    imgFiles.value.push({
      url: resourcesUrl + halfPath,
      path: halfPath
    })
  }
  emit('getImagePath', imgFiles.value, props.imgsId)
}

/**
 * 删除图片
 */
const removeImgByIndex = (idx) => {
  imgFiles.value.splice(idx, 1)
  emit('getImagePath', imgFiles.value, props.imgsId)
}

let isShowPreview = false
/**
 * 图片预览
 */
const previewImage = (index) => {
  const urls = []
  imgFiles.value.forEach(el => {
    urls.push(el.url)
  })
  uni.previewImage({
    current: index,
    urls,
    success: () => {
      isShowPreview = true
    }
  })
}

</script>

<style scoped lang="scss">
  .component-upload-imgs {
    display: block;
    .upload {
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;
      width: 100%;
      height: 100%;
      background: #fff;
      row-gap: 20rpx;
      .preview {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 180rpx;
        height: 180rpx;
        border-radius: 8rpx;
        background: #f9f9f9;
        position: relative;
        margin-right: 20rpx;
        image {
          display: block;
          width: 100%;
          height: 100%;
          border-radius: 8rpx;
        }
      }
      .upload-chequer {
        width: 180rpx;
        height: 180rpx;
        border-radius: 8rpx;
        background: #f9f9f9;
        display: flex;
        align-items: center;
        justify-content: center;
        .cross {
          font-size: 96rpx;
          font-weight: 200;
          color: #ccc;
        }
      }
    }
    .preview {
      .del {
        position: absolute;
        top: 0;
        right: 0;
        width: 36rpx;
        height: 36rpx;
        font-size: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        background: rgba(0,0,0,.3);
        border-radius: 0 8rpx 0 30rpx;
        image {
          width: 14rpx;
          height: 14rpx;
          margin: 0 0 2rpx 2rpx;
        }
      }
      .preview-img {
        position: absolute;
        bottom: 0;
        display: block;
        width: 100%;
        height: 2em;
        line-height: 2em;
        background: rgba(0,0,0,.3);
        text-align: center;
        color: #fff;
        border-radius: 0 0 8rpx 8rpx;
      }
    }
  }
</style>
