<!-- 企业 -->
<template>
  <div class="position-relative">
    <!-- 轮播 -->
    <v-carousel 
      v-if="jobFair?.pcHeadImg && jobFair?.pcHeadImg.length > 0" 
      :show-arrows="jobFair?.pcHeadImg.length > 1 ? 'hover' : false" 
      cycle :hide-delimiters="true" 
      :style="{'height': isMobile ? '200px' : '500px'}"
    >
			<v-carousel-item v-for="(k, i) in jobFair?.pcHeadImg" :key="i">
				<img :src="k" :lazy-src="k" style="width: 100%; height:100%;">
			</v-carousel-item>
		</v-carousel>

    <!-- 招聘会分享按钮 -->
    <div class="position-fixed" style="right: 24px; top: 80px;">
      <v-btn icon="mdi-share-all" color="primary" size="x-large" @click.stop="handleShare"></v-btn>
    </div>

    <div :style="{'background-color': jobFair.backgroundColour || '#fff', 'min-height': jobFair?.pcHeadImg && jobFair?.pcHeadImg.length > 0 ? `calc(100vh - ${isMobile ? '200px' : '500px'})` : '100vh'}">
      <div :class="{'default-width': !isMobile}">
        <!-- 类别展示 -->
        <div class="d-flex align-center" v-if="jobFair?.tag && jobFair.tag.length" style="overflow-x: auto;">
          <div 
            v-for="(val, index) in jobFair.tag" 
            :key="index" 
            class="tag-item"
            :class="[{'tag-active-bg': index === tab && jobFair.backgroundColour}, {'mx-5': isMobile}, {'tag-active': index === tab && !jobFair.backgroundColour}]" 
            :style="{'width': `calc(100% / ${jobFair.tag.length} )`, 'color': jobFair.backgroundColour ? '#fff' : 'var(--v-primary-base)'}"
            @click.stop="handleTabClick(index)"
          >
            {{ val.title }}
          </div>
        </div>

        <div 
          v-if="!items.length" 
          class="text-center" 
          :style="{'color': jobFair.backgroundColour ? '#fff' : 'var(--v-primary-base)', 'height': `calc(100vh - ${jobFair?.tag && jobFair.tag.length ? '574px': '500px'})`, 'line-height': `calc(100vh - ${jobFair?.tag && jobFair.tag.length ? '574px': '500px'})`}"
        >
          {{ loadingType === 1 ? loadingText[loadingType] : '暂无数据，去看看其他吧~' }}
        </div>
        <template v-else>
          <EntCard v-if="jobFair?.category === '0'" :jobFairId="jobFair?.id" :list="items" :isMobile="isMobile" class="mt-5" />
          <JobCard v-if="jobFair?.category === '1'" :jobFairId="jobFair?.id" :list="items" :isMobile="isMobile" class="mt-5" />
          <div 
            :class="['loading', {'cursor-pointer': !loadingType}]" 
            :style="{'color': !jobFair?.tag || !jobFair.tag.length ? 'var(--v-primary-base)' : '#fff'}" 
            class="py-5" 
            @click="handleChangePage"
          >
            {{ loadingText[loadingType] }}
          </div>
        </template>
      </div>
    </div>

    <div class="hideCanvasView">
      <canvas ref="shareCanvas" :width="canvasWidth" :height="canvasHeight"></canvas>
    </div>
  </div>

  <Loading :visible="loading" />

  <PreviewImage v-if="showPreview" :urlList="[previewSrc]" :fileName="jobFair?.title?.replace(/<\/?p[^>]*>/gi, '')" @close="showPreview = !showPreview" />

</template>

<script setup>
defineOptions({name: 'jobFair-enterprises'})
import { ref, reactive, onMounted } from 'vue'
import { getJobFairEnterprisePage, getJobFair, getJobFairEntJobPage, saveShareQuery } from '@/api/recruit/personal/jobFair'
import EntCard from './components/entCard1.vue'
import JobCard from './components/jobCard1.vue'
import { useRoute } from 'vue-router'; const route = useRoute();
import { dealDictArrayData, dealDictObjData } from '@/utils/position'
import { getJobAdvertisedShareQrcode } from '@/api/position'

const tab = ref(0)
const loading = ref(false)
const query = reactive({
  pageNo: 1,
  pageSize: 20,
	jobFairId: route.params.id
})

const showPreview = ref(false)
const shareCanvas = ref(null)
const previewSrc = ref('')
const canvasWidth = 500
const canvasHeight = 900

const isMobile = ref(false)
onMounted(() => {
  const userAgent = navigator.userAgent
  isMobile.value = /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i.test(userAgent)
})

const items = ref([])
const loadingText = ['点击加载更多', '加载中...', '']
const loadingType = ref(0)

// 参与招聘会的企业
const getList = async () => {
	loadingType.value = 1

  // 有类别的添加筛选条件
  if (jobFair.value?.tag && jobFair.value?.tag.length) {
    const key = jobFair.value.tag[tab.value].key
    const value = jobFair.value.tag[tab.value].value
    query[key] = value
  }

	try {
		const result = jobFair.value?.category === '0' ? await getJobFairEnterprisePage(query) : await getJobFairEntJobPage(query)
		const list = result?.list || []
    if (list.length) {
      if (jobFair.value?.category === '1') {
        items.value.push(...list.map(e => {
          e.enterprise = dealDictObjData({}, e.enterprise)
          e = dealDictObjData({}, e)
          return e
        }))
      }
      else items.value = items.value.concat(dealDictArrayData([], list))

			loadingType.value = items.value.length === result.total ? 2 : 0
		} else {
			loadingType.value = 2
		}
	} catch {}
}

// 招聘会详情
const jobFair = ref([])
const getJobFairDetail = async () => {
  const data = await getJobFair(route?.params?.id)
  if (!data) return
  jobFair.value = data
  document.title = data.title.replace(/<\/?p[^>]*>/gi, '')
  getList()
}
getJobFairDetail()

// tab项点击
const handleTabClick = (index) => {
  items.value = []
  query.pageNo = 1
  tab.value = index
  getList()
}

const handleChangePage = () => {
  if (loadingType.value) return // 没有更多数据了
  // 加载更多
  query.pageNo++
  getList()
}

const handleShare = () => {
  loading.value = true

  const canvas = shareCanvas.value
  const ctx = canvas.getContext('2d')
  const img = new Image()
  img.setAttribute('crossOrigin', 'anonymous')
  img.onload = async () => {
    //清空画布
    ctx.clearRect(0, 0, canvasWidth, canvasHeight)

    // 设置背景图片
    ctx.drawImage(img, 0, 0, canvasWidth, canvasHeight)

    // 分享二维码
    const secondImg = new Image()
    secondImg.setAttribute('crossOrigin', 'anonymous')
    secondImg.onload = () => {
      // 计算第二张图片的位置和大小（这里以示例为准，您可以根据需要调整）
      const secondImgWidth = Math.min(secondImg.width, canvas.width / 4)
      const secondImgHeight = (secondImgWidth / secondImg.width) * secondImg.height // 保持宽高比
      const x = (canvas.width - secondImgWidth) / 2 // 水平居中
      const y = canvas.height - secondImgHeight - 190 // 垂直放置在 Canvas 底部上方 170 像素处
  
      // 绘制第二张图片到 Canvas 上的指定位置和大小
      ctx.drawImage(secondImg, x, y, secondImgWidth, secondImgHeight)

      ctx.font = 'bold 16px Arial'
      ctx.fillStyle = '#10325d'
      const text = '诚挚邀约 共享机遇'
      const textWidth = ctx.measureText(text).width
      const textX = x + (secondImgWidth - textWidth) / 2
      const textY = y + secondImgHeight + 30
      ctx.fillText(text, textX, textY)

      previewSrc.value = canvas.toDataURL()
      loading.value = false
      showPreview.value = true
    }
    
    // 保存分享参数
    const result = await saveShareQuery({ jobFairId: jobFair.value.id })
    const query = {
      scene: 'id=' + result,
      path: 'pagesB/jobFair/positionClassification',
      width: 200,
      autoColor: false,
      checkPath: true,
      hyaline: false
    }
    const data = await getJobAdvertisedShareQrcode(query)
    secondImg.src = 'data:image/png;base64,' + data
  }

  img.onerror = (error) => {
    console.error('Failed to load image:', error)
    loading.value = false
  }

  img.src = jobFair.value?.shareImg
}
</script>

<style scoped lang="scss">
.tag-item {
  font-weight: 700;
  font-size: 24px;
  text-align: center;
  height: 74px;
  line-height: 74px;
  opacity: .8;
  cursor: pointer;
  text-wrap: nowrap;
}
.tag-active-bg {
  opacity: 1;
  position: relative;
  &::before {
    display: block;
    content: '';
    width: 34px;
    height: 4px;
    background-color: #fff;
    position: absolute;
    top: 62px;
    left: 50%;
    border-radius: 2px;
    transform: translateX(-50%);
  }
}
.tag-active {
  opacity: 1;
  position: relative;
  &::before {
    display: block;
    content: '';
    width: 34px;
    height: 4px;
    background-color: var(--v-primary-base);
    position: absolute;
    top: 62px;
    left: 50%;
    border-radius: 2px;
    transform: translateX(-50%);
  }
}
.loading {
  margin-top: 8px;
  text-align: center;
  font-size: 18px;
}
.hideCanvasView {
	position: fixed;
	top: -99999px;
	left: -99999px;
	z-index: -99999;
}
::-webkit-scrollbar {
  width: 0;
  height: 0;
}
::-webkit-scrollbar-thumb, .temporaryAdd ::-webkit-scrollbar-thumb, .details_edit ::-webkit-scrollbar-thumb {
  // 滚动条-颜色
  background: #c3c3c379;
}
::-webkit-scrollbar-track, .temporaryAdd ::-webkit-scrollbar-track, .details_edit ::-webkit-scrollbar-track {
  // 滚动条-底色
  background: #e5e5e58f;
}
</style>
