<template>
  <layout-page>
    <scroll-view class="scrollBox" style="position:relative;">
      <view class="box">
        <view v-if="loading" class="vertical80-center">{{ loadingText }}</view>
        <view v-else>
          <!-- 职位名称 + 薪资 -->
          <h2 class="JobName">{{ info.name }}</h2>
          <view style="text-align: end;">
            <span v-if="!info.payFrom && !info.payTo" class="salary w-600">面议</span>
            <span v-else class="salary w-600">{{ info.payFrom }}-{{ info.payTo }}/{{ positionInfo.payName }}</span>
          </view>
          <!-- 职位地区 收藏职位 -->
          <view class="d-flex justify-space-between mt-5">
            <view style="font-size: 14px;">
              <span>
                <span>{{positionInfo?.areaName }}</span>
                <span class="viewider-mx" v-if="positionInfo?.areaName && positionInfo?.eduName">|</span>
                <span>{{positionInfo?.eduName }}</span>
                <span class="viewider-mx" v-if="positionInfo?.expName">|</span>
                <span>{{positionInfo?.expName }}</span>
              </span>
            </view>
            <!-- 收藏职位 -->
            <view @click="handleCollection">
              <uni-icons
                :type="isCollection ? 'heart-filled' : 'heart'"
                color="#fc6d5e"
                class="mr"
                size="25"
              ></uni-icons>
            </view>
          </view>
          <!-- 标签 -->
          <view class="tagList mt">
            <view class="tag" v-for="(tag,i) in info?.tagList || []" :key="'tagList' + i">
              {{ tag }}
            </view>
          </view>
          <!-- 赏金 -->
          <view v-if="info.hire" class="topLine mt-5" style="display: flex; align-items: center;">
            <view class="iconfont icon-a-1_zhaopin" style="color: #e03506; font-size: 30px;"></view>
            <view class="hirePrice">{{ `赏金：${commissionCalculation(info.hirePrice, 1)}元` }}</view>
          </view>
          <!-- 企业信息 -->
          <view class="topLine mt-5 d-flex" @click="handleToEnterprise">
            <view class="avatarBox">
              <image class="avatar" :src="info.enterprise?.logoUrl || 'https://minio.citupro.com/dev/menduner/company-avatar.png'"></image>
            </view>
            <view >
              <view class="contact-name">{{ info.contact?.name }}</view>
              <view class="contact-info">{{ info.enterprise?.anotherName || info.enterprise?.name }} {{ info.contact?.postNameCn ? '· ' + info.contact?.postNameCn : '' }}</view>
            </view>
          </view>
          <!-- 岗位职责 -->
          <view class="topLine fs14 mt-5">
            <view class="fs15 w-600 my5">岗位职责</view>
            <view v-if="!info.content"></view>
            <rich-text v-else class="htmlCss" :nodes="cleanedHtml(info.content)"></rich-text>
          </view>
          <!-- 岗位要求 -->
          <view class="topLine mt-5">
            <view class="fs15 w-600 my5">岗位要求</view>
            <view v-if="!info.requirement"></view>
            <rich-text v-else class="htmlCss" :nodes="cleanedHtml(info.requirement)"></rich-text>
          </view>
          <!-- 工作地址 -->
          <view class="topLine mt-5">
            <view class="fs15 w-600 my5">工作地址</view>
            <view class="my10">
              <uni-icons
                type="map-pin-ellipse"
                color="#00897B"
                class="mr"
                size="25"
              ></uni-icons>
              <span style="color: var(--color-666);font-size: 15px;line-height: 26px;">{{ info.address || '' }}</span>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
    <!-- 分享 投递 -->
    <view class="bottom-sticky" v-if="!loading && jobId && info.status === '0'">
      <view class="bottom-content">
        <!-- 已登录可以分享 -->
        <button v-if="beenLogin" class="bottom-content-tool shareButtonCss" open-type="share">
          <uni-icons type="redo-filled" size="24" color="#00897B" style="line-height: 24px;"/>
          <span style="color:#00897B;font-weight:bold;line-height: 22px;">分享</span>
        </button>
        <!-- 未登录点击分享拉起登录 -->
        <view v-else @click="handleClickShare" class="bottom-content-tool">
          <uni-icons type="redo-filled" size="24" color="#00897B"/>
          <span style="color:#00897B;font-weight:bold;">分享</span>
        </view>
        <button class="btnStyle bgButtons" @tap="handleSend">立即沟通</button>
        <button v-if="delivery" :disabled="true" class="buttons btnStyle disable">我已投递</button>
        <button v-else class="buttons btnStyle" @click="handleDelivery">我要投递</button>
      </view>
    </view>
    <uni-popup
        ref="poster"
        type="center"
        class="f-straight"
        style="position: relative;"
    >
        <canvas
          :style="{
            width:`${appInfo.windowWidth}px;`,
            height:`${appInfo.windowHeight}px;margin-left:-9999px; margin-top:-99.5vh;`
          }" canvas-id="firstCanvas" id="firstCanvas"></canvas>
        <image
          :style="{ width:`${appInfo.windowWidth}px;`, height:`${appInfo.windowHeight*.9}px;`}"
          :src="imgSrc"
          mode="aspectFit"
        />
        <!-- <uni-icons v-if="!!imgSrc" type="clear" size="35" color="#FFF" style="position: absolute;top: 10px;right: 28px;" @click="posterClose"></uni-icons> -->
    </uni-popup>
    
    <!-- 选择简历 -->
    <uni-popup ref="popup" background-color="#fff" :mask-click="false" >
      <view class="dialogBox" style="width: 86vw;">
        <view class="dialog-title">
          <view class="title">选择简历</view>
          <uni-icons type="close" color="grey" size="26" @click="popupClose" />
        </view>
        <view style="height: 1px; margin: 0 20rpx; background-color: #dedede;"></view>
        <scroll-view class="dialog-content" scroll-y="true" style="max-height: 50vh; width: auto;">
          <uni-card
            v-for="(item, index) in resumeList"
            :key="index"
            shadow="0px 0px 3px 1px rgba(0,0,0,0.1)"
            :is-shadow="true"
            :border='false'
             background-color="red"
            :class="{'selected': selectIndex === index}"
            @click="selectIndex = index"
          >
            <view class="d-flex align-center">
              <view style="flex: 1;">
                <view style="font-weight: bold;">
                  <uni-icons v-if="selectIndex === index" color="green" type="checkmarkempty" size="18"></uni-icons>
                  {{ item.title }}
                </view>
                <view>上传时间：{{ timesTampChange(item.createTime, 'Y-M-D') }}</view>
              </view>
              <view class="ss-m-l-30" style="width: 60rpx;">
                <uni-icons @click="preview(item.url)" type="eye" size="24"></uni-icons>
              </view>
            </view>
          </uni-card>
          <view class="selectOnline" @click="handleUpload">选取微信聊天文件</view>
        </scroll-view>
        <view class="dialog-bottom" @click="deliverySubmit()">确认投递</view>
      </view>
    </uni-popup>
    <!-- 上传简历 -->
    <uni-popup ref="uploadPopup" type="dialog">
			<uni-popup-dialog
        type="warn"
        cancelText="取消"
        confirmText="确定"
        title="系统提示"
        content="您还未上传过简历，是否选取微信聊天文件投递？"
        @confirm="handleUpload"
				@close="uploadPopup.close()"
      ></uni-popup-dialog>
		</uni-popup>

    <!-- 职位分享 -->
    <uni-popup ref="sharePopup" type="share">
      <uni-popup-share title="分享到">
        <view class="share-pop">
          <button class="f-straight" open-type="share">
            <view class="share-round share-round-1" >
              <uni-icons type="weixin" color="#FFF" size="30" />
            </view>
            <view style="font-size:12px;">微信</view>
          </button>
        </view>
      </uni-popup-share>
    </uni-popup>

    <view class="hideCanvasView">
      <canvas class="shareCanvas" canvas-id="shareCanvas" style="width: 452px; height: 362px;"></canvas>
    </view>
  </layout-page>
</template>

<script setup>
import { commissionCalculation } from '@/utils/position'
import { timesTampChange } from '@/utils/date'
import { preview } from '@/utils/preview'
import { uploadFile } from '@/api/file'
import layoutPage from '@/layout'
import { ref, watch } from 'vue';
import {
  jobCvRelSend,
  getPositionDetails,
  jobCvRelCheckSend,
  getPersonJobUnfavorite, // 取消收藏
  getPersonJobFavorite, // 收藏
  getJobFavoriteCheck,
  jobCvRelHireSend,
  getShareDetail
} from '@/api/position'
import { getPersonResumeCv, saveResume } from '@/api/user'
import { dealDictObjData } from '@/utils/position'
import { getAccessToken } from '@/utils/request'
import { onLoad, onShareAppMessage, onShow } from '@dcloudio/uni-app'
import { prologue, defaultText } from '@/hooks/useIM'
import { userStore } from '@/store/user'

const useUserStore = userStore()
const sharePopup = ref()
const loading = ref(false)
const loadingText = ref('加载中 . . . ')

// 职位详情
const info = ref({})
const positionInfo = ref({})
const isEmployment = ref(null)
const imgSrc = ref('')
const appInfo = ref({})
const poster = ref()
const beenLogin = ref(false)
const areaName = ref('')
const canvasToTempFilePath = ref('')

// 监听登录状态
watch(() => useUserStore.refreshToken, (newVal) => {
	beenLogin.value = Boolean(newVal)
}, { immediate: true }, { deep: true })

let jobId = ''
let obj = {}
onLoad(async (options) => {
  console.log(options, 'options')
  areaName.value = options?.area || ''

  // 网站二维码分享
  if (options.scene) {
    const scene = decodeURIComponent(options.scene)
    const str = scene.split('=')
    const res = await getShareDetail({ id: str[1] })
    obj = res.data
  }

  // 是否众聘
  isEmployment.value = options?.sharedById || obj?.sharedById
  jobId = options?.id || options?.jobId || obj?.jobId || ''
  if (jobId) {
    loading.value = true
    loadingText.value = '加载中 . . . '
    deliveryCheck()
    getCollectionStatus()
    getPositionDetail()
  } else {
    loadingText.value = '加载失败 . . . '
  }
})

onShow(() => {
  if (!jobId) {
    return
  }
  deliveryCheck()
})

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


/**
  ctx： 画布的上下文环境
  fontSize: 文字大小
  text： 绘制文本
  maxWidth： 一行文字最大宽度
  x：文本在x轴显示的位置
  y：文本在y轴显示的位置
  maxLine：最多绘制的行数
**/
//处理文字多出省略号显示
const dealWords = (ctx, fontSize, text, maxWidth, x, y, maxLine) => {
  ctx.setFontSize(fontSize);//设置字体大小
  var allRow = Math.ceil(ctx.measureText(text).width / maxWidth);//实际总共能分多少行
  var count = allRow >= maxLine ? maxLine : allRow;//实际能分多少行与设置的最大显示行数比，谁小就用谁做循环次数
  var endPos = 0;//当前字符串的截断点
  for (var j = 0; j < count; j++) {
    var nowStr = text.slice(endPos);//当前剩余的字符串
    var rowWid = 0;//每一行当前宽度  
    if (ctx.measureText(nowStr).width > maxWidth) {//如果当前的字符串宽度大于最大宽度，然后开始截取
      for (var m = 0; m < nowStr.length; m++) {
        rowWid += ctx.measureText(nowStr[m]).width;//当前字符串总宽度
        if (rowWid > maxWidth) {            
          if (j === maxLine - 1) { //如果是最后一行
            ctx.fillText(nowStr.slice(0, m - 1) + '...', x, y + (j + 1) * 30);  //(j+1)*18这是每一行的高度    
          } else {
            ctx.fillText(nowStr.slice(0, m), x, y + (j + 1) * 30);
          }
          endPos += m;//下次截断点
          break;
        }
      }
    } else {//如果当前的字符串宽度小于最大宽度就直接输出
      ctx.fillText(nowStr.slice(0), x, y + (j + 1) * 30);
    }
  }
}

// 职位分享图片绘制
const createPoster = async () => {
  var context = uni.createCanvasContext('shareCanvas')

  //清空画布
  context.clearRect(0, 0, 452, 362);

  //背景图片
  context.drawImage('../../static/img/share-cover-border.jpg', 0, 0, 452, 362);
  
  // 岗位名称
  context.setFillStyle('#333333')
  dealWords(context, 25, positionInfo.value?.name, 350, 40, 30, 2)

  // 工作地区、工作经验、学历要求
  context.setFillStyle('#6c6e7b')
  context.setFontSize(20)
  const area = (areaName.value !== 'undefined' && areaName.value !== '' && areaName.value !== 'null' ? areaName.value + ' | ' : '') || (positionInfo.value?.areaName ? positionInfo.value?.areaName + ' | ' : '')
  const combinationText = (area || '') + (positionInfo.value.expName || '') + (positionInfo.value.eduName ? ' | ' + positionInfo.value.eduName : '')
  context.fillText(combinationText, 40, 130)

  // 薪资
  context.setFontSize(22)
  context.setFillStyle('#f67272')
  const { payFrom, payTo, payName } = positionInfo.value
  const salary = payFrom && payTo ? payFrom + '-' + payTo + (payName ? '元/'+ payName : '') : '面议'
  context.fillText(salary, 40, 170)

  // 间隔线
  context.setLineDash([2, 4], 1)
  context.beginPath()
  context.moveTo(40, 195)
  context.lineTo(412, 195)
  context.setStrokeStyle('#00897B')
  context.stroke()

  // 企业头像
  const { logoUrl, anotherName, industryName, scaleName } = positionInfo.value.enterprise
  const {path : headImg} = await getImageTempRatio(logoUrl ? logoUrl : 'https://minio.citupro.com/dev/menduner/company-avatar.png')
  context.drawImage(headImg, 40, 220, 90, 90)

  // 企业名称
  context.setFillStyle('#000000')
  dealWords(context, 25, anotherName, 250, 150, 210, 2)

  // 企业行业类型、规模
  context.setFontSize(20)
  let industry = industryName && industryName.length > 6 ? `${industryName.slice(0, 7)}...` : industryName
  context.fillText(`${industry || ''}${scaleName ? ' | ' + scaleName : ''}`, 150, 310)

  context.draw(false, () =>{
    wx.canvasToTempFilePath({ 
      canvasId: 'shareCanvas',
      success:(res)=>{
        canvasToTempFilePath.value = res.tempFilePath
        console.log('canvas-success', canvasToTempFilePath.value)
      },
      fail:(err)=>{
        console.log('canvasToTemp-fail', err)
      }
    })
  })
}

//在点击open-type="share"按钮后会触发以下函数，可以在函数中写需要的逻辑，当然函数的返回值必须是一个对象，用于设置分享卡片的展示形式
//发送给微信好友  
onShareAppMessage((res) => {
  console.log(1, 'onShareAppMessage', res)
  let path = `/pagesB/positionDetail/index?jobId=${info.value.id}`
  if (info.value.hire) {
    path += `&sharedById=${info.value.userId}`
  }
  if(!canvasToTempFilePath.value){
		setTimeout(() => {},1000)
	}
  return {
    title: '我发现了一个好职位，快来看看吧',
    path,
    imageUrl: canvasToTempFilePath.value
  }
})

// 富文本内容处理，去除多余的换行空格等
const cleanedHtml = (text) => {
  let cleaned = text.replace(/\n/g, '</br>')
  cleaned = cleaned.replace(/\s+/g, ' ').trim()
  cleaned = cleaned.replace(/(^|\s+)<\/p>(\s*<p>|$)/g, '</p><p>').trim()
  cleaned = cleaned.replace(/<p>\s*(<br>)\s*<\/p>/g, '')
  cleaned = cleaned.replace(/<p>\s*(<\/br>)\s*<\/p>/g, '')
  return cleaned
}

// 企业详情
const handleToEnterprise = () => {
  uni.navigateTo({
    url: `/pagesB/companyDetail/index?id=${info.value.enterprise?.id}`
  })
}

// 职位详情
async function getPositionDetail () {
  try {
    loading.value = true
    const { data } = await getPositionDetails({ id: jobId })
    info.value = data
    positionInfo.value = { ...dealDictObjData({}, info.value), ...info.value, enterprise: dealDictObjData({}, data.enterprise) }
    loading.value = false

    // 生成分享图片
    createPoster()
  } finally {
  }
}
// 效验是否有投递过简历
const delivery = ref(false) // 是否已投递简历
async function deliveryCheck () {
  try {
    if (!getAccessToken()) return delivery.value = false
    const { data } = await jobCvRelCheckSend({ jobId })
    delivery.value = Boolean(data)
  } finally {
  }
}

import { showAuthModal } from '@/hooks/useModal'
const popup = ref()
const uploadPopup = ref()
const resumeList = ref([])
const selectIndex = ref(null)
const handleDelivery = async () => {
  // 未登录
  if (!getAccessToken()) {
    uni.showToast({
      title:'请先登录',
      icon: 'none'
    })
    showAuthModal()
    return
  }
  // 已投递
  if (delivery.value) {
    uni.showToast({ title: '您已投递过该职位！', icon: 'none', duration: 2000, })
    return
  }

  const { data } = await getPersonResumeCv()
  resumeList.value = data
  // 未上传简历
  if (!resumeList.value?.length) {
    return uploadPopup.value.open()
  }
  popup.value.open()
}
const deliverySubmit = async (uploadFile) => {
  const resume = uploadFile ? uploadFile : resumeList.value[selectIndex.value]
  if (!resume) {
    selectIndex.value = null
    uni.showToast({ title: '请选择简历', icon: 'none', duration: 2000, })
    return
  }

  if (isEmployment.value) {
    await jobCvRelHireSend({
      jobId,
      url: resume.url,
      recommendUserId: isEmployment.value
    })
  } else {
    await jobCvRelSend({
      jobId,
      title: resume.title,
      url: resume.url,
      type: info.value.hire ? 1 : 0
    })
  }
  
  uni.showToast({ title: '投递成功', icon: 'none', duration: 2000, })
  deliveryCheck()
  popup.value.close()
}

const popupClose = () => {
  selectIndex.value = null
  popup.value.close()
}

// 发起聊天
async function handleSend () {
  if (!getAccessToken()) {
    showAuthModal()
    return
  }
  const userId = info.value.contact.userId
  const enterpriseId = info.value.contact.enterpriseId
  const textObj = {
    text: defaultText,
    positionInfo: positionInfo.value,
    
  }
  const channel = await prologue({userId, enterpriseId, text: JSON.stringify(textObj)})
  // 跳转
  const query = {
		id: userId,
    isEmployment: isEmployment.value ? isEmployment.value : '-1',
		name: info.value?.contact?.name,
		postName: info.value?.contact?.postNameCn,
		enterpriseName: info.value?.enterprise?.anotherName,
		enterpriseId: info.value?.enterpriseId,
		channelId: channel.channel_id,
		avatar: info.value?.contact?.avatar,
		sex: info.value?.contact?.sex,
	}
	const queryStr = Object.keys(query).reduce((r, v) => {
		return r += `${v}=${encodeURIComponent(query[v])}&`
	}, '?')
	uni.navigateTo({
    url: `/pagesA/chart/index${queryStr.slice(0, -1)}`
  })
}

// 效验求职者是否有收藏该职位
const isCollection = ref(false)
const getCollectionStatus = async () => {
  if (!getAccessToken()) return isCollection.value = false
  const { data } = await getJobFavoriteCheck({ jobId })
  isCollection.value = Boolean(data)
}

// 操作 收藏&取消收藏职位
const handleCollection = async () => {
  const api = isCollection.value ? getPersonJobUnfavorite : getPersonJobFavorite
  await api(isCollection.value ? jobId : { jobId })
  await getCollectionStatus()
}

// 选取微信聊天文件
// 上传附件
const handleUpload = () => {
  wx.chooseMessageFile({
    count: 1,
    type: 'file',
    success (res) {
      // 限制文件上传大小
      const size = res.tempFiles[0].size
      if (size / (1024*1024) > 20) {
        uni.showToast({ icon: 'none', title: '文件大小不能超过20M' })
        return
      }

      const title = res.tempFiles[0].name
      const path = res.tempFiles[0].path
      //效验是否为支持的文件格式
      if(/\.(pdf|docx|doc)$/.test(title)){
        uploadFile(path, 'attachment').then(async (res) => {
          if (!res.data) {
            uni.showToast({
              title: '上传失败',
              icon: 'none'
            })
            return
          }
          await saveResume({ title, url: res.data })
          uni.showToast({
            title: '上传成功',
            icon: 'success'
          })
          deliverySubmit({ title, url: res.data })
        })
      }else{
        uni.showToast({
          icon: 'none',
          title: '请上传pdf、doc、docx类型的文件',
          duration: 2000
        })
        return
      }
    }
  })
}

// 分享
const handleClickShare = () => {
  if (!getAccessToken()) {
    uni.showToast({
      title:'请先登录',
      icon: 'none'
    })
    showAuthModal()
    return
  }
  sharePopup.value.open()
}
</script>

<style scoped lang="scss">
@import '../../static/style/position/index.scss';

.hideCanvasView{
	position: relative;
}
.shareCanvas {
	position: fixed;
	top: -99999upx;
	left: -99999upx;
	z-index: -99999;
}

.bottom-content {
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  width: 100%;
  margin: 20rpx 0;
  .btnStyle {
    flex: 1;
    margin-right: 20rpx;
  }
  .bgButtons {
    border: 2rpx solid #00897b;
    color: #00897b;
    background: #FFF;
    border-radius: 50rpx;
  }
  .shareButtonCss {
    font-size: 16px;
    background: unset;
    &::after{
      border:none !important;
    }
  }
  &-tool {
    width: 160rpx;
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
  }
}
.share-pop {
    width: 100%;
    // height:300rpx;
    display: flex;
    justify-content: center;
    .f-straight {
      margin: 40rpx;
      background: unset;
      &::after{
        border:none !important;
      }
    }
    .share-round {
      border-radius:50%;
      height:100rpx;
      width:100rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .share-round-1 {
        background-color:#22a039;
    }
    .share-round-2 {
        background-color:#3693cd;
    }
}
.preview {
  position: fixed;
  z-index: 9;
  height: 100vh;
  width: 100vw;
  left: 0;
  top: 0;
  .image {
    position: absolute;
    width: 80%;
    left: 10%;
    top: 100rpx;
  }
}
</style>
