<template>
  <view class="Mall4j component-img-box upload-img">
    <!-- 单图 -->
    <view class="upload">
      <!-- 添加按钮 -->
      <view
        v-if="!resourcesVal"
        class="upload-chequer"
        @tap="getUploadImg"
      >
        <view class="cross">
          ＋
        </view>
      </view>
      <!-- 图片 -->
      <view
        v-if="resourcesVal"
        class="preview"
      >
        <image
          :src="resourcesVal"
          mode="aspectFill"
          @tap="getUploadImg"
          @error="imgError"
        />
        <view
          v-if="needDeleteBtn"
          class="del"
          @tap="removeImgByIndex"
        >
          <image src="@/static/images/close-w.png" />
        </view>
        <view
          class="preview-img"
          @tap="previewImage"
        >
          预览
        </view>
      </view>
    </view>
    <helang-compress ref="hCompressRef" />
  </view>
</template>

<script setup>
import { onMounted, watch } from 'vue'
const resourcesUrl = import.meta.env.VITE_APP_RESOURCES_URL

const props = defineProps({
  imgId: {
    type: [String, Number],
    default: ''
  },
  imgUrl: {
    type: String,
    default: ''
  },
  needDeleteBtn: {
    type: Boolean,
    default: true
  },
  type: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['getImagePath'])

const imgNum = 1 // 图片上传数量，默认1，最大9
const resourcesVal = ref('')
let inited = false
const tempFilePaths = ref([]) // 图片上传列表
const attachFiles = []
let ossList = null
let tempFiles = null
watch(() => props.imgUrl, (newVal, oldVal) => {
  if (!oldVal && newVal && !inited) {
    if (newVal.indexOf(resourcesUrl) === 0) {
      resourcesVal.value = newVal
    } else {
      resourcesVal.value = resourcesUrl + newVal
    }
    inited = true
  }
})

onMounted(() => {
  if (props.imgUrl) {
    if (props.imgUrl?.indexOf(resourcesUrl) === 0) {
      resourcesVal.value = props.imgUrl
    } else {
      resourcesVal.value = resourcesUrl + props.imgUrl
    }
  }
})

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

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

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

/**
 * 获取上传图片数据
 */
const getUploadData = () => {
  const fileNames = tempFiles?.map(item => {
    let fileName = ''
    // #ifdef H5
    fileName = item.name
    // #endif
    // #ifdef APP-PLUS || MP-WEIXIN
    fileName = item.path
    // #endif
    return fileName
  }).join(',')
  const params = {
    url: '/tmerclub_biz/ua/oss/get_batch_pre_sign_url',
    method: 'GET',
    data: {
      fileNames // 需要获取token的文件名
    }
  }
  http.request(params).then(res => {
    uni.hideLoading()
    ossList = res
    confirmUpload()
  })
}

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

/**
 * 上传成功回调
 */
const onUploadSuccess = (filePath) => {
  resourcesVal.value = resourcesUrl + '/' + filePath
  emit('getImagePath', '/' + filePath, props.imgId)
}

/**
 * 删除图片
 */
const removeImgByIndex = () => {
  resourcesVal.value = ''
  emit('getImagePath', '', props.imgId)
}

let isShowPreview = false
/**
 * 图片预览
 */
const previewImage = () => {
  const urls = []
  urls.push(resourcesVal.value)
  uni.previewImage({
    current: 0,
    urls,
    success: () => {
      isShowPreview = true
    }
  })
}
const imgError = () => {
  if (props.type === 'user') {
    resourcesVal.value = '@/static/images/head-sculpture.png'
  }
}

</script>

<style lang="scss" scoped>
.component-img-box {
  display: block;
  .upload {
    display: block;
    width: 100%;
    height: 100%;
    .preview {
      display: block;
      width: 100%;
      height: 100%;
      border-radius: 4px;
      background: #f9f9f9;
      position: relative;
      image {
        display: block;
        width: 100%;
        height: 100%;
        border-radius: 8rpx;
      }
    }
    .upload-chequer {
      width: 100%;
      height: 100%;
      border-radius: 4px;
      background: #f9f9f9;
      display: flex;
      align-items: center;
      justify-content: center;
      .cross {
        font-size: 96rpx;
        font-weight: 200;
        color: #ccc;
      }
    }
  }

  .preview {
    /* 删除 */
    .del {
      position: absolute;
      top: 5rpx;
      right: 5rpx;
      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>
