<template>
  <div>
    <div class="default-width banner px-6">
      <div class="banner-title d-flex justify-space-between">
        <div class="d-flex align-center">
          <h1 class="ellipsis">{{ info.name }}</h1>
          <span class="salary">{{ info.payFrom }}-{{ info.payTo }}/{{ positionInfo.payName }}</span>
          <publicRecruitment v-if="info.hire" class="ml-5" width="50" height="50"></publicRecruitment>
        </div>
        <span class="refresh-time">{{ timesTampChange(info.updateTime) }} {{ $t('common.refresh') }} <v-icon color="warning" size="20">mdi-alert-outline</v-icon></span>
      </div>
      <div class="banner-tags mt-4">
        <span v-for="k in desc" :key="k.mdi" class="mr-10">
          <span v-if="positionInfo[k.value]">
            <v-icon color="var(--color-666)" size="20">{{ k.mdi }}</v-icon>
            <span class="ml-1">{{ positionInfo[k.value] }}</span>
          </span>
        </span>
      </div>
      <div class="banner-tools my-4">
        <v-chip size="small" label v-for="(k, i) in info.tagList" :key="i" class="mr-1" color="primary">{{ k }}</v-chip>
      </div>
      <div class="d-flex justify-space-between mb-5">
        <div>
          <div>
            <v-chip v-if="info.hire && info.hirePrice && info.hirePrice > 0" label color="primary">赏金：{{ commissionCalculation(info.hirePrice, 1) }}元</v-chip>
            <v-chip v-if="info.hire && info.hirePoint && info.hirePoint > 0" label color="primary" class="ml-1">积分：{{ commissionCalculation(info.hirePoint, 1) }}点</v-chip>
          </div>
          <div v-if="info?.hire" class="font-size-14 mt-3 color-error">推荐好友入职即可获得赏金</div>
        </div>
        <div class="banner-tools-btns">
          <v-btn
            class="radius mr-2 button-item"
            variant="outlined"
            color="error"
            prepend-icon="mdi-share-outline"
            style="height: 36px;"
            v-if="info?.hire"
            @click="handleShare"
          >我要赏金</v-btn>
          <v-btn
            v-else
            class="radius mr-2 button-item"
            variant="outlined"
            color="error"
            prepend-icon="mdi-share-outline"
            style="height: 36px;"
            @click="handleShare"
          >{{ $t('position.rewardsShared') }}</v-btn>
          <v-btn
            class="button-item radius"
            color="warning" 
            variant="outlined" 
            :prepend-icon="isCollection ? 'mdi-heart' : 'mdi-heart-outline'"
            @click="handleCollection"
          >{{ isCollection ? $t('position.cancelFavorite') : $t('position.collection') }}</v-btn>
          <v-btn class="button-item mx-2 radius" color="success" variant="outlined">{{ $t('position.communicate') }}</v-btn>
          <v-btn class="button-item radius" :disabled="delivery" color="primary" variant="outlined" @click="handleDelivery">{{ delivery ? $t('position.delivered') : $t('position.submitResume') }}</v-btn>
        </div>
      </div>
      <v-divider></v-divider>
      <div class="d-flex">
          <div class="content-left">
            <div v-if="Object.keys(info).length">
              <div>{{ $t('position.jobResponsibilities') }}：</div>
              <div class="requirement" v-html="info.content.replace(/\n/g, '</br>')"></div>
              <div class="mt-3">{{ $t('position.jobRequirements') }}：</div>
              <div class="requirement" v-html="info.requirement.replace(/\n/g, '</br>')"></div>
            </div>
            <v-divider class="my-3"></v-divider>
            <div class="contact" v-if="Object.keys(info).length">
              <div class="float-left d-flex align-center">
                <v-img :src="info.contact.avatar || 'https://minio.citupro.com/dev/menduner/7.png'" :width="45" style="height: 45px;"></v-img>
                <div class="ml-2">
                  <div class="contact-name">{{ info.contact.name }}</div>
                  <div class="contact-info">
                    {{ info.enterprise.name }}
                     <span v-if="info?.enterprise?.name && info?.contact?.postNameCn">·</span>
                    {{ info.contact.postNameCn }}</div>
                </div>
              </div>
              <!-- <div class="float-right">
                <v-chip color="primary" label>{{ $t('position.currentOnline') }}</v-chip>
              </div> -->
            </div>
            <v-divider class="my-3"></v-divider>
            <div>
              <h4>{{ $t('position.address') }}</h4>
              <div class="mt-1">
                <v-icon size="25" color="primary">mdi-map-marker</v-icon>
                <span style="color: var(--color-666);font-size: 15px;">{{ info.address }}</span>
              </div>
            </div>
            <div class="mt-3 text-center">
              <v-btn class="mr-2 radius button-item" color="success" variant="outlined">{{ $t('position.communicate') }}</v-btn>
              <v-btn class="radius button-item" :disabled="delivery" color="primary" @click="handleDelivery">{{ delivery ? $t('position.delivered') : $t('position.submitResume') }}</v-btn>
            </div>
          </div>
          <div class="content-right" v-if="Object.keys(info).length">
            <!-- 公司信息 -->
            <EnterpriseInfo :info="{ ...info, position: { ...positionInfo } }"></EnterpriseInfo>
            <!-- 相似职位 -->
            <similarPositions v-if="similarList.length" class="mt-3" :list="similarList" :info="info"></similarPositions>
          </div>
      </div>
    </div>

    <!-- 弹窗提示去上传简历 -->
    <promptToUpload v-model="dialog" @handleToUpload="handleToUpload"></promptToUpload>
    <!-- 选择简历 -->
    <selectResumeDialog v-model="showResume" :list="resumeList" @submit="handleSubmit" @close="handleClose"></selectResumeDialog>
    <!-- 复制分享链接 -->
    <Dialog
      :visible="shareDialog" :widthType="2" :footer="false" titleClass="text-h6"
      :title="$t('position.rewardsShared')"
      @close="shareDialog = false"
    >
      <div>
        <div class="pa-4" style="background-color: #f0f0f0; border-radius: 8px;">{{ shareUrlTxt }}</div>
        <v-btn v-if="!getToken()" class="mt-1" color="warning" variant="text">您还未登录，登录后分享可享受分享有礼活动！</v-btn>
        <v-btn class="mt-4 ml-3" color="success" @click="copyText">复制分享链接</v-btn>
        <v-btn class="mt-4 ml-3" color="primary" variant="outlined" @click="openShareLink">打开分享链接</v-btn>
      </div>
      <template #footer>
        <v-divider></v-divider>
        <div>
          <v-btn
            class="float-right ma-2"
            color="primary"
            variant="text"
            @click="shareDialog = false"
          >{{ $t('common.close') }}</v-btn>
        </div>
      </template>
    </Dialog>
  </div>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
</template>

<script setup>
import { commissionCalculation } from '@/utils/position'
defineOptions({ name: 'position-details' })
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'
import { timesTampChange } from '@/utils/date'
import { getPersonResumeCv } from '@/api/recruit/personal/resume'
import { useI18n } from '@/hooks/web/useI18n'
import { getPositionDetails, getSimilarPosition, getJobFavoriteCheck, getPersonJobFavorite, getPersonJobUnfavorite, jobCvRelCheckSend, jobCvRelSend } from '@/api/position'
import { dealDictObjData, dealDictArrayData } from '@/utils/position'
import similarPositions from '@/components/Position/similarPositions.vue'
import EnterpriseInfo from '@/components/Enterprise/info.vue'
import Snackbar from '@/plugins/snackbar'
import Dialog from '@/components/CtDialog'
import promptToUpload from './jobDetails/promptToUpload'
import selectResumeDialog from './jobDetails/selectResumeDialog'
import { getToken } from '@/utils/auth'

const { t } = useI18n()
const router = useRouter()
const { id } = router.currentRoute.value.params
const delivery = ref(false) // 是否已投递简历

// 相似职位
const similarList = ref([])
const getSimilarPositionList = async () => {
  if (!Object.keys(positionInfo).length) return
  const { list } = await getSimilarPosition({ pageNo: 1, pageSize: 4, positionId: positionInfo.value.positionId, expType: positionInfo.value.expType, eduType: positionInfo.value.eduType })
  const items = list.splice(0, 4)
  similarList.value = dealDictArrayData([], items)
}

// 职位详情
const info = ref({})
const positionInfo = ref({})
const getPositionDetail = async () => {
  const data = await getPositionDetails({ id })
  info.value = data
  positionInfo.value = { ...dealDictObjData({}, info.value), ...info.value }
  getSimilarPositionList()
}
getPositionDetail()

// 效验是否有投递过简历
const deliveryCheck = async () => {
  const data = await jobCvRelCheckSend({ jobId: id })
  if (data) delivery.value = true
}
if (getToken()) deliveryCheck()

const desc = [
  { mdi: 'mdi-map-marker-outline', value: 'areaName' },
  { mdi: 'mdi-school-outline', value: 'eduName' },
  { mdi: 'mdi-clock-time-ten-outline', value: 'expName' }
]

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

// 分享有礼
const shareDialog = ref(false)
const shareUrl = ref('')
const userInfo = localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')) : {}
const handleShare = async () => {
  // 分享链接携带参数: 用户id、职位id
  // if (!id || !userInfo.id) return
  shareUrl.value = '/shareJob?' + new URLSearchParams({
    jobId: id,
    sharedById: userInfo?.id,
  }).toString()
  shareDialog.value = true
}
const openShareLink = () => { window.open(shareUrl.value) }

// 复制分享链接
const shareUrlTxt = computed(() => {
  return 'http://menduner.citupro.com:7878' + shareUrl.value
})
const copyText = async () => {
  // try {
  //   const txt = shareUrlTxt.value
  //   if (navigator.clipboard && navigator.clipboard.writeText) {
  //     await navigator.clipboard.writeText(txt)
  //     Snackbar.success('复制成功')
  //   } else {
  //     const textArea = document.createElement("textarea")
  //     textArea.value = txt
  //     textArea.style.position = "fixed" // 避免在页面上滚动  
  //     textArea.style.top = 0
  //     textArea.style.left = 0
  //     textArea.style.width = "2em"
  //     textArea.style.height = "2em"
  //     textArea.style.padding = 0
  //     textArea.style.border = "none"
  //     textArea.style.outline = "none"
  //     textArea.style.boxShadow = "none"
  //     textArea.style.background = "transparent"
  //     document.body.appendChild(textArea)
  //     textArea.focus()
  //     textArea.select()
  //     const successful = document.execCommand('copy')
  //     Snackbar.success(successful ? '复制成功' : '复制失败，请手动复制。')
  //   }
  // } catch (err) {
  //   Snackbar.error('复制失败，请手动复制。')
  // }
  try {
    await navigator.clipboard.writeText(shareUrlTxt.value)
    Snackbar.success('复制成功')
  } catch (err) {
    Snackbar.error('复制失败，请手动复制。')
  }
}

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

const dialog = ref(false)
const showResume = ref(false)
// 去上传附件
const handleToUpload = () => {
  dialog.value = false
  window.open('/recruit/personal/personalCenter')
}

// 效验是否有投递简历
const resumeList = ref([])
const selectResume = ref()
const handleDelivery = async () => {
  if (delivery.value) return Snackbar.warning(t('resume.alreadyResume'))
  const result = await getPersonResumeCv()
  resumeList.value = result
  // 没有上传过简历的先去上传
  if (!result.length) {
    dialog.value = true
    return
  }
  showResume.value = true
}

// 简历投递
const handleClose = () => {
  showResume.value = false
  selectResume.value = null
}
const handleSubmit = async (val) =>{
  selectResume.value = val
  if (!selectResume.value) return Snackbar.warning(t('resume.selectResumeToSubmit'))
  const obj = resumeList.value.find(e => e.id === selectResume.value)
  if (!obj) return Snackbar.warning(t('resume.selectedResumeNotExist'))
  await jobCvRelSend({ jobId: id, title: obj.title, url: obj.url, type: info.value.hire ? 1 : 0 })
  setTimeout(() => {
    Snackbar.success(t('resume.deliverySuccess'))
  }, 3000)
  handleClose()
  deliveryCheck()
}
</script>

<style lang="scss" scoped>
.banner {
  background-color: #fff;
  padding: 18px 0 20px;
}
.banner-title {
  line-height: 40px;
  font-size: 28px;
  font-weight: 600;
}
.banner-title h1 {
  display: inline-block;
  color: #37576c;
  font-size: 28px;
  margin-right: 30px;
  margin-top: 1px;
  max-width: 360px;
  vertical-align: middle;
}
.button-item {
  min-width: 110px;
  height: 36px
}
.salary {
  color: var(--v-error-base);
  line-height: 41px;
  font-weight: 600;
  height: auto;
  display: inline-block;
  vertical-align: sub;
}
.refresh-time {
  float: right;
  color: var(--color-666);
  font-size: 14px;
  line-height: 66px;
  vertical-align: sub;
}
.banner-tags span {
  font-weight: 600;
}
.radius {
  border-radius: 8px;
}
.content-left {
  width: 810px;
  padding: 20px 20px;
}
.content-right {
  flex: 1;
  padding: 20px 20px 20px 0;
}
.label-text {
  color: #7f7a7a;
  font-weight: 600;
}
.value-text {
  color: #000;
  font-weight: 400;
}
.requirement {
  white-space: pre-wrap;
  word-break: break-all;
  line-height: 28px;
  color: var(--color-333);
  font-size: 15px;
  text-align: justify;
  letter-spacing: 0;
}
.contact {
  height: 60px;
  line-height: 60px;
}
.contact-name {
  font-size: 20px;
  font-weight: 500;
  color: var(--color-222);
  line-height: 28px;
}
.contact-info {
  font-size: 15px;
  color: var(--color-666);
  line-height: 21px;
  margin-top: 8px;
}
</style>