<template>
  <view class="upload" @click="beforeUploadImg">
    <view class="icon-add"></view>
    <view class="icon-add rotate"></view>
    <canvas
      :style="{
        width: `${thumbWidth}px`,
        height: `${thumbHeight}px`,
        position: 'fixed',
        left: '10000rpx'
      }"
      canvas-id="myCanvas"
    ></canvas>
  </view>
</template>

<script setup lang="ts">
import { uploadFile } from '@/utils/upload'
import { onMounted, defineEmits, ref, getCurrentInstance } from 'vue'
import { getWxLocationApi } from '@/wxUtils/index'
import { qqmapsdk } from '@/wxUtils/QQMapWX'

const emit = defineEmits(['uploadImgInfo'])

const { ctx: _this } = getCurrentInstance() as any

const porops = defineProps({
  count: Number
})

interface imgType {
  path: string
  url: string
}

const sourceType = ref<string[]>([])

const beforeUploadImg = () => {
  uni.showActionSheet({
    itemList: ['相机', '从相册选择'],
    success: function (res) {
      if (res.tapIndex === 0) {
        sourceType.value = ['camera']
      } else {
        sourceType.value = ['album']
      }
      uploadImg()
    },
    fail: function (res) {}
  })
}

onMounted(() => {
  getLocation()
})

const address = ref()
const getLocation = async () => {
  try {
    const res: any = await getWxLocationApi()
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: res?.latitude,
        longitude: res?.longitude
      },
      success: function (res: any) {
        const result = res.result
        address.value = result.address
      }
    })
  } catch (e) {
    uni.showToast({
      title: '获取定位失败',
      icon: 'none'
    })
    console.log(e)
  }
}

const uploadImg = async () => {
  uni.chooseImage({
    count: porops?.count || 9,
    sizeType: ['original', 'compressed'],
    sourceType: sourceType.value,
    async success(res: any) {
      let tempFiles = res.tempFiles
      // 当前相片来源为拍照
      if (sourceType.value[0] === 'camera') {
        const path = await addWatermark(tempFiles[0].path)
        if (path) {
          res.tempFiles[0].path = path
          tempFiles[0].path = path
        }
      }
      // 保存上传成功的数据
      const imageValue: imgType[] = []
      // 使用map而不是forEach，因为map会返回一个Promise数组
      const uploadPromises = tempFiles.map(async (item: any) => {
        let res: any = await uploadFile(item.path)
        if (res?.code === 0) {
          // 当前为拍照
          if (sourceType.value[0] === 'camera') {
            if (res?.data?.url) {
              res.data.url = res.data.url + ';1'
            }
          } else if (sourceType.value[0] === 'album') {
            res.data.url = res.data.url + ';2'
          }
          imageValue.push({
            path: res?.data?.url,
            url: import.meta.env.VITE_APP_URL + res?.data?.url
          })
        }
      })
      // 使用Promise.all等待所有的uploadFile函数执行完毕
      await Promise.all(uploadPromises)
      // 所有uploadFile上传完成后执行emit
      emit('uploadImgInfo', imageValue)
    }
  })
}

const thumbWidth = ref()
const thumbHeight = ref()
const addWatermark = (fileUrl: string) => {
  const dpr = wx.getSystemInfoSync().pixelRatio
  return new Promise((resolve) => {
    uni.getImageInfo({
      src: fileUrl, // 替换为你的图片路径
      success: async (res) => {
        thumbWidth.value = res.width
        thumbHeight.value = res.height
        // #ifdef MP-WEIXIN
        let text = address.value
        let textArr = []
        let oneRowTextNum = Math.floor(thumbWidth.value / 31) // 一行可以显示的文字数, 除以的31稍微比文字30大, 防止内容溢出
        if (text?.length <= oneRowTextNum) {
          textArr.push(text)
        } else {
          const totalRowNum = Math.ceil(text.length / oneRowTextNum) // 文字要显示的总行数
          for (let i = 0; i < totalRowNum; i++) {
            textArr.push(text.substr(i * oneRowTextNum, oneRowTextNum))
          }
        }
        const time =
          new Date().toJSON().substring(0, 10) + ' ' + new Date().toTimeString().substring(0, 8)
        const ctx = uni.createCanvasContext('myCanvas', _this)
        ctx.drawImage(fileUrl, 0, 0, thumbWidth.value, thumbHeight.value) //先画出图片
        ctx.setFontSize(30) //注意：设置文字大小必须放在填充文字之前，否则不生效
        ctx.setFillStyle('white')
        for (let i = 0; i < textArr.length; i++) {
          ctx.fillText(textArr[i], 10, 72 + i * 40)
        }
        ctx.setFontSize(26)
        ctx.fillText(time, 10, 35)
        ctx.draw(false, () => {
          setTimeout(() => {
            //绘画完成回调
            //生成图片
            uni.canvasToTempFilePath(
              {
                fileType: 'jpg',
                canvasId: 'myCanvas',
                success: async (res: any) => {
                  resolve(res.tempFilePath)
                },
                fail(err: any) {
                  console.log(err)
                }
              },
              _this
            )
          }, 600)
        })
        // #endif
      }
    })
  })
}
</script>

<style lang="scss" scoped>
.upload {
  width: 200rpx;
  height: 200rpx;
  border: 2rpx solid #eee;
  border-radius: 3px;
  display: flex;
  align-items: center;
  justify-content: center;

  .icon-add {
    width: 100rpx;
    height: 10rpx;
    background-color: #f1f1f1;
    border-radius: 4rpx;
  }
  .rotate {
    position: absolute;
    transform: rotate(90deg);
  }
}
</style>
