<template>
  <view style="position: relative;">
    <view v-if="shareUrl" class="d-flex align-center flex-column justify-center" style="height: 100vh;">
      <image v-if="!!shareUrl" :style="imgStyle" @click="handlePreviewSharePoster" :src="shareUrl" :show-menu-by-longpress="true"></image>
      <view class="color-999 ss-m-t-20 font-size-14 ss-m-b-50">点击图片预览，长按图片保存</view>
    </view>
		<canvas canvas-id="posterCanvas" class="shareCanvas" style="width: 540px; height: 788px;"></canvas>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getJobAdvertisedShareQrcode } from '@/api/user'
import { getJobFairPosition, getJobFair, saveShareQuery } from '@/api/jobFair'
import { formatName } from '@/utils/getText'
import { userStore } from '@/store/user'

const useUserStore = userStore()
const shareUrl = ref('')
const windowWidth = ref(0)
let jobFairId = '' // 分享会ID
let entLogoUrl = useUserStore?.userInfo?.logoUrl || 'https://minio.citupro.com/dev/menduner/company-avatar.png'
let entName = formatName(useUserStore?.userInfo?.enterpriseAnotherName || useUserStore?.userInfo?.enterpriseName) || '门墩儿' // 企业名称
let shareImg = '' // 分享背景图片-底图

onLoad(async (options) => {
  jobFairId = options.jobFairId
  await getJobFairDetail()
  await getEntPositionList()
  const windowInfo = wx.getWindowInfo()
  windowWidth.value = windowInfo.windowWidth
  if (shareImg) createPoster() // 生成海报
})

const getJobFairDetail = async () => {
  if (!jobFairId) return
  const { data } = await getJobFair(jobFairId)
  shareImg = data?.contentImg || ''
}

let positionNameList = []
const getEntPositionList = async () => {
  if (!jobFairId) {
    uni.showToast({ title: '获取企业岗位失败，请重试！', icon: 'none', duration: 2000 })
    return
  }
  try {
    const { data } = await getJobFairPosition(jobFairId)
    positionNameList = data.map(e => { return formatName(e?.name) }).slice(0, 3)
  } catch (error) {}
}

const imgStyle = computed(() => {
  if (windowWidth.value <= 320) return `width: 259px; height: 377px;`
  if (windowWidth.value > 320 && windowWidth.value <= 375) return `width: 313px; height: 455px;`
  if (windowWidth.value > 375) return `width: 328px; height: 474px;`
})

// 图片预览
const handlePreviewSharePoster = () => {
	uni.previewImage({
		current: 0,
		longPressActions: {
			itemList: ['发送给朋友', '保存图片', '收藏']
		},
		urls: [shareUrl.value]
	})
}

const getImageTempRatio = (url) => {
  return new Promise((req, rej)=>{
    wx.getImageInfo({
      src:url,
      success:(res) =>{
        req(res)
      }
    })
  })
}

const getToLocal = (base64data) => {
  const fsm = wx.getFileSystemManager()
  const FILE_BASE_NAME = `tmp_${new Date().getTime()}` // 自定义文件名
  const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || []
  if (!format) {
    return (new Error('ERROR_BASE64SRC_PARSE'))
  }
  const filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.${format}`
  const buffer = wx.base64ToArrayBuffer(bodyData);
  fsm.writeFile({
    filePath,
    data: buffer,
    encoding: 'binary',
    success(r) {
      console.log(filePath,'filePath')
      qrCode.value = filePath
    },
    fail() {
      return (new Error('ERROR_BASE64SRC_WRITE'))
    }
  })
}

// 生成分享二维码
const qrCode = ref()
const handleShareCode = async () => {
  const result = await saveShareQuery({ jobFairId, entName, enterpriseId: useUserStore?.userInfo?.enterpriseId })
	const query = {
		scene: 'id=' + result.data,
    path: 'pagesB/jobFair/positionClassification',
		width: 200,
		autoColor: false,
		checkPath: true,
		hyaline: false // 二维码背景颜色为透明
	}
	const res = await getJobAdvertisedShareQrcode(query, { noAuth: true })
	const data = res?.data ? 'data:image/png;base64,' + res.data : ''
  getToLocal(data)
}


const createPoster = async () => {
  uni.showLoading({ title: '生成中...', mask: true })
  await handleShareCode() // 生产分享二维码
  var context = uni.createCanvasContext('posterCanvas')

  //清空画布
  context.clearRect(0, 0, 540, 788)

  //背景图片 
  const { path: bgUrl } = await getImageTempRatio(shareImg)
  context.drawImage(bgUrl, 0, 0, 540, 788) // 路径、x、y、宽、高

  // 企业头像
  context.save()
  const secondImgWidth = 120
  const secondImgHeight = 120
  const x = (540 - secondImgWidth) / 2
  const y = 788 - secondImgHeight - 460
  context.beginPath()
  context.arc(x + secondImgWidth / 2, y + secondImgHeight / 2, secondImgWidth / 2, 0, Math.PI * 2, true)
  context.clip()
  const { path: entLogoUrlPath } = await getImageTempRatio(entLogoUrl)
  context.drawImage(entLogoUrlPath, x, y, secondImgWidth, secondImgHeight)
  context.restore()
  
  // 企业名称
  const maxTextWidth = 400
  const fontStyle = 'bold 24px Arial'
  context.font = fontStyle
  let truncatedText = entName
  while (context.measureText(truncatedText + '...').width > maxTextWidth && truncatedText.length > 0) {
    truncatedText = truncatedText.slice(0, -1)
  }
  if (truncatedText !== entName) truncatedText += '...'
  const textX = x + (secondImgWidth - context.measureText(truncatedText).width) / 2
  const textY = y + secondImgHeight + 30
  context.fillStyle = '#000'
  context.fillText(truncatedText, textX, textY)
  
  // 职位标签
  const tagPaddingLeftRight = 20
  const tagPaddingTopBottom = 10
  const tagRadius = 8
  const tagSpacing = 22
  let tagY = textY + tagSpacing + 10
  positionNameList.forEach((tag) => {
    let truncatedTag = tag
    context.font = '18px Arial' // 绘制前设置字体，否则tagWidth受前面的font fontStyle影响

    while (context.measureText(truncatedTag + '...').width > maxTextWidth - 2 * tagPaddingLeftRight && truncatedTag.length > 0) {
      truncatedTag = truncatedTag.slice(0, -1)
    }
    if (truncatedTag !== tag) truncatedTag += '...'

    const tagWidth = context.measureText(truncatedTag).width + 2 * tagPaddingLeftRight
    const tagX = x + (secondImgWidth - tagWidth) / 2

    context.fillStyle = '#00B760'
    context.beginPath()
    context.moveTo(tagX + tagRadius, tagY)
    context.lineTo(tagX + tagWidth - tagRadius, tagY)
    context.quadraticCurveTo(tagX + tagWidth, tagY, tagX + tagWidth, tagY + tagRadius)
    context.lineTo(tagX + tagWidth, tagY + tagPaddingTopBottom * 2)
    context.quadraticCurveTo(tagX + tagWidth, tagY + tagPaddingTopBottom * 2 + tagRadius, tagX + tagWidth - tagRadius, tagY + tagPaddingTopBottom * 2 + tagRadius)
    context.lineTo(tagX + tagRadius, tagY + tagPaddingTopBottom * 2 + tagRadius)
    context.quadraticCurveTo(tagX, tagY + tagPaddingTopBottom * 2 + tagRadius, tagX, tagY + tagPaddingTopBottom * 2)
    context.lineTo(tagX, tagY + tagRadius);
    context.quadraticCurveTo(tagX, tagY, tagX + tagRadius, tagY)
    context.closePath()
    context.fill()

    context.fillStyle = '#fff'
    context.fillText(truncatedTag, tagX + tagPaddingLeftRight, tagY + tagPaddingTopBottom + 10)

    tagY += tagPaddingTopBottom * 2 + tagSpacing
  })

  
  //分享二维码
  context.drawImage(qrCode.value, 80, 550, 110, 110)

  context.font = 'bold 18px Arial'
  context.fillStyle = '#000'
  context.fillText('海量职位火热招聘中', 280, 605)

  context.font = '15px Arial'
  context.fillStyle = '#999'
  context.fillText('长按图片识别二维码', 290, 625)
  

  context.draw(false, () =>{
    wx.canvasToTempFilePath({ 
      canvasId: 'posterCanvas',
      success:(res)=>{
        shareUrl.value = res.tempFilePath
        console.log('canvas-success', shareUrl.value)
		    uni.hideLoading({})
      },
      fail:(err)=>{
        uni.hideLoading({})
        console.log('canvas-fail', err)
      }
    })
  })
}
</script>

<style scoped lang="scss">
.shareCanvas {
	position: fixed;
	top: -99999upx;
	left: -99999upx;
	z-index: -99999;
}
</style>
