<template>
  <div>
    <CtTable
      class="mt-3"
      :items="items"
      :headers="headers"
      :loading="false"
      :elevation="0"
      :disableSort="true"
      :isTools="false"
      height="calc(100vh - 360px)"
      :showPage="true"
      :total="total"
      :page-info="pageInfo"
      itemKey="id"
      @pageHandleChange="e => emit('page', e)"
    >
      <template #name="{ item }">
        <div class="d-flex align-center cursor-pointer" @click="handleToPersonDetail(item)">
          <v-badge
            v-if="item?.person?.sex === '1' || item?.person?.sex === '2'"
            bordered
            offset-y="6"
            :color="badgeColor(item)"
            :icon="badgeIcon(item)">
            <v-avatar size="40" :image="getUserAvatar(item.person.avatar, item.person.sex)"></v-avatar>
          </v-badge>
          <v-avatar v-else size="40" :image="getUserAvatar(item.person?.avatar, item.person?.sex)"></v-avatar>
          <span class="defaultLink ml-3">{{ item?.person?.name || item?.phone }}</span>
        </div>
      </template>
      <template #jobName="{item}">
        <svg-icon v-if="item.jobFairId" name="jobFair" size="20"></svg-icon>
        {{ formatName(item.job.name) }}
      </template>
      <template #status="{ item }">
        <span v-if="tab === 0">{{ item.status && item.status === '0' ? '未查看' : '已查看' }}</span>
        <span v-else>{{ item.status ? props.statusList.find(i => i.value === item.status)?.label : '' }}</span>
      </template>
      <template #actions="{ item }">
        <!-- <v-btn color="primary" variant="text" @click="handlePreviewResume(item)">查看附件</v-btn>
        <v-menu v-if="actionItems(item).length">
          <template v-slot:activator="{ props }">
            <v-icon v-bind="props" class="mx-3" size="20" color="primary">mdi-dots-horizontal</v-icon>
          </template>
          <v-list>
            <v-list-item
              v-for="(k, index) in actionItems(item)"
              :key="index"
              :value="index"
              color="primary"
              @click="k.click(item)"
            >
              <v-list-item-title>
                <span :class="{'disabledItem': tab === 0 && ['邀请面试', '立即沟通'].includes(k.title) && item.jobClosed}">{{ k.title }}</span>
                <v-tooltip v-if="tab === 0 && ['邀请面试', '立即沟通'].includes(k.title) && item.jobClosed" activator="parent" location="top">职位已关闭</v-tooltip>
              </v-list-item-title>
            </v-list-item>
          </v-list>
        </v-menu> -->

        <v-btn icon variant="text" v-for="(k, index) in actionItems(item)" :key="index" @click.stop="k.click(item)">
          <v-icon :color="k?.disabled ? '#ccc' : k.color">{{ k.icon }}</v-icon>
          <v-tooltip :text="k.title" location="top" activator="parent">
            <span>{{ k.title }}</span>
          </v-tooltip>
        </v-btn>
      </template>
    </CtTable>

    <!-- 邀请面试 -->
    <CtDialog :visible="showInvite" :widthType="4" titleClass="text-h6" title="面试信息" @close="handleEditClose" @submit="handleEditSubmit">
      <InvitePage v-if="showInvite" ref="inviteRef" :itemData="itemData"></InvitePage>
    </CtDialog>

    <TipDialog :visible="showTip" icon="mdi-check-circle-outline" message="面试邀请发送成功" @close="showTip = false">
      <div class="color-primary text-decoration-underline cursor-pointer" @click="handleToInterviewManagement">点击到面试中查看。</div>
    </TipDialog>

    <Loading :visible="formLoading" />
  </div>
</template>

<script setup>
defineOptions({ name: 'table-page'})
import { ref, computed, watch } from 'vue'
import { previewFile } from '@/utils'
import { personJobCvLook, joinEliminate, personEntryByEnterprise, personCvUnfitCancel, joinToTalentPool } from '@/api/recruit/enterprise/personnel'
import { saveInterviewInvite } from '@/api/recruit/enterprise/interview'
import { hireJobCvRelSettlement } from '@/api/recruit/public/delivery'
import { useI18n } from '@/hooks/web/useI18n'
import { useUserStore } from '@/store/user'
import Snackbar from '@/plugins/snackbar'
import Confirm from '@/plugins/confirm'
import InvitePage from './invite.vue'
import { getUserAvatar } from '@/utils/avatar'
import { getBlob, saveAs } from '@/utils'
import { talkToUser, defaultTextEnt } from '@/hooks/web/useIM'
import { useRouter } from 'vue-router'; const router = useRouter()
import { formatName } from '@/utils/getText'

const showTip = ref(false)
const { t } = useI18n()
const emit = defineEmits(['refresh', 'page'])
const props = defineProps({
  tab: Number,
  items: Array,
  statusList: Array,
  pageInfo: Object,
  total: Number
})
const badgeColor = computed(() => (item) => {
  return (item.person && item.person.sex) ? (item.person.sex === '1' ? '#1867c0' : 'error') : 'error'
})

const badgeIcon = computed(() => (item) => {
  return (item.person && item.person.sex) ? (item.person.sex === '1' ? 'mdi-gender-male' : 'mdi-gender-female') : 'mdi-gender-female'
})

const formLoading = ref(false)
const userStore = useUserStore()
const inviteRef = ref()
const showInvite = ref(false)
const headers = ref([
  { title: '姓名', value: 'name', sortable: false },
  { title: '人才类型', key: 'person.type', sortable: false, value: item => item.person?.type ? item.person.type === '1' ? '在校学生' : '职场人士' : '' },
  { title: '求职状态', key: 'person.jobStatusName', sortable: false },
  { title: '工作经验', key: 'person.expName', sortable: false },
  { title: '最高学历', key: 'person.eduName', sortable: false },
  { title: '应聘职位', key: 'jobName', sortable: false },
  { title: '操作时间', key: 'createTime', sortable: false },
  { title: '状态', key: 'status', sortable: false },
  { title: '操作', value: 'actions', sortable: false }
])

let baseInfo = ref(JSON.parse(localStorage.getItem('entBaseInfo')) || {})
userStore.$subscribe((mutation, state) => {
  if (Object.keys(state.entBaseInfo).length) baseInfo.value = state.entBaseInfo
})

watch(
  () => props.tab,
  (val) => {
    // 不合适不需要展示状态
    if (val === 4) {
      const obj = headers.value.find(e => e.key === 'status')
      const i = headers.value.indexOf(obj)
      if (i !== -1) headers.value.splice(i, 1)
    }
  },
  { immediate: true }
)

// 人才详情
const handleToPersonDetail = async (item) => {
  const userId = item.userId
  const id = props.tab === 0 ? item.id : item.cvRel.id
  if (!userId || !id) return
  // 改变状态
  try {
    const res = await personJobCvLook(id)
    if (res) {
      emit('refresh')
    }
  } catch (err) {
    console.log(err)
  }
  window.open(`/recruit/enterprise/talentPool/details/${userId}`)
}

// 加入人才库 
const handleJoinToTalentPool = async (item) => {
  if (!item.userId) return Snackbar.warning('数据异常')
  Confirm('系统提示', '是否确认将此求职者加入人才库？').then(async () => {
    await joinToTalentPool(item.userId)
    Snackbar.success(t('common.operationSuccessful'))
    emit('refresh')
  })
}

// 入职
const handleEnterByEnterprise = async (item) => {
  if (!item.id) return
  Confirm('系统提示', '是否确认将此求职者操作入职？').then(async () => {
    await personEntryByEnterprise(item.id)
    Snackbar.success(t('common.operationSuccessful'))
    emit('refresh')
  })
}

// 不合适
const handleEliminate = async (item) => {
  if (!item.id || !item?.job?.id) return
  Confirm('系统提示', '是否确认加入不合适？').then(async () => {
    const query = {
      bizId: item.id,
      jobId: item.job.id,
      userId: item.userId,
      jobCvRelId: props.tab === 0 ? item.id : item.cvRel?.id,
      type: props.tab === 0 ? '0' : '1' // 投递简历0 已邀约1
    }
    // 招聘会职位则带id
    if (item?.jobFairId) query.jobFairId = item.jobFairId
    await joinEliminate(query)
    Snackbar.success(t('common.operationSuccessful'))
    emit('refresh')
  })
}

// 取消不合适
const handleCancelEliminate = async (item) => {
  if (!item.id) return
  Confirm('系统提示', '是否确认取消不合适？').then(async () => {
    await personCvUnfitCancel(item.id)
    Snackbar.success(t('common.operationSuccessful'))
    emit('refresh')
  })
}

// 查看简历
const handlePreviewResume = async (item) => {
  // 招聘会收到的简历不需要效验
  if (!item.jobFairId) {
    // 效验企业是否有查看简历次数
    await userStore.getEnterpriseInfo(true)
    if (baseInfo.value?.entitlement?.lookCvCount <= 0) return Snackbar.warning('您的查看简历次数已用完，请联系平台管理员！')
  }

  const url = props.tab === 0 ? item.url : item.cvRel.url
  const id = props.tab === 0 ? item.id : item.cvRel.id
  if (!url || !id) return Snackbar.warning('简历不存在')
  try {
    const res = await personJobCvLook(id)
    if (res) {
      emit('refresh')
      previewFile(url)
    }
  } catch (err) {
    console.log(err)
  }
}

// 邀请面试
const itemData = ref({})
const handleInterviewInvite = (item) => {
  if (item.handleStatus) return
  if (item?.jobClosed) return // 职位已关闭
  itemData.value = item
  showInvite.value = true
}

const handleToCommunicate = async (item) => {
  if (item?.jobClosed) return // 职位已关闭
  const userId = item.userId
  await talkToUser({userId, text: defaultTextEnt})
  let url = `/recruit/enterprise/chatTools?id=${userId}`
  router.push(url)
}

const handleEditClose = () => {
  showInvite.value = false
  itemData.value = {}
}

const handleEditSubmit = async () => {
  const { valid } = await inviteRef.value.CtFormRef.formRef.validate()
  if (!valid) return
  const query = inviteRef.value.getQuery()
  if (!query?.time) return Snackbar.warning('请选择面试时间')

  query.jobCvRelId = itemData.value.id

  formLoading.value = true
  try {
    await saveInterviewInvite(query)
    showTip.value = true
    handleEditClose()
    emit('refresh')
  } finally {
    formLoading.value = false
  }
}

// 结算
const handleSettlement = async (item) => {
  if (!item.id) return
  Confirm('系统提示', '是否确认结算？').then(async () => {
    await hireJobCvRelSettlement(item.id)
    Snackbar.success(t('common.operationSuccessful'))
    emit('refresh')
    // 更新账户信息
    setTimeout(async () => {
      await userStore.getEnterpriseUserAccountInfo()
    }, 2000)
  })
}

const handleToInterviewManagement = () => {
  router.push('/recruit/enterprise/interviewManagement')
}

// 下载附件
const handleDownloadAttachment = async (k) => {
  // 招聘会收到的简历不需要效验
  if (!k.jobFairId) {
    // 效验企业是否有下载简历次数
    await userStore.getEnterpriseInfo(true)
    if (baseInfo.value?.entitlement?.lookCvCount <= 0) return Snackbar.warning('您的下载简历次数已用完，请联系平台管理员！')
  }

  const url = props.tab === 0 ? k.url : k.cvRel?.url
  if (!url) return
  getBlob(url).then(blob => {
    saveAs(blob, props.tab === 0 ? k.title : k.cvRel?.title)
  })
}

const actionItems = (item) => {
  const arr = []
  // 有返回简历信息的才展示查看简历&下载简历
  if ((props.tab === 0 && item.url) || (props.tab !== 0 && item?.cvRel && item.cvRel?.url)) arr.push(
    { title: '查看附件', color: 'warning', click: handlePreviewResume, icon: 'mdi-eye-outline' }, 
    { title: '下载附件', color: 'error', click: handleDownloadAttachment, icon: 'mdi-arrow-down-bold-circle-outline' }
  )
  if (props.tab === 0) {
    arr.push(
      {
        title: item?.jobClosed ? '邀请面试（职位已关闭）' : (item.handleStatus ? '邀请面试（已邀面试）' : '邀请面试'),
        disabled: item?.jobClosed || item.handleStatus,
        color: 'success',
        click: handleInterviewInvite,
        icon: 'mdi-account-clock-outline'
      }, 
      {
        title: item?.jobClosed ? '立即沟通（职位已关闭）' : '立即沟通',
        color: 'primary',
        disabled: item?.jobClosed,
        click: handleToCommunicate,
        icon: 'mdi-comment-processing-outline'
      }
    )
  }
  if ([0, 1].includes(props.tab)) arr.push({ title: '不合适', color: 'indigo', click: handleEliminate, icon: 'mdi-account-remove-outline' })
  if (props.tab === 4) arr.push({ title: '取消不合适', color: 'light-blue', click: handleCancelEliminate, icon: 'mdi-account-check-outline' })
  if (props.tab === 2 && item?.job?.hire) arr.push({ title: '结算', click: handleSettlement, icon: 'mdi-currency-cny' })
  if (props.tab === 1 && ['3', '4'].includes(item.status)) arr.push({ title: '入职', click: handleEnterByEnterprise, icon: 'mdi-account-arrow-right-outline' })
  // 面试后才能够加入储备
  if ([1, 2, 3].includes(props.tab) && !item.inTalentPool) arr.push({ title: '加入储备', color: '#00897B', click: handleJoinToTalentPool, icon: 'mdi-account-star-outline' })
  return arr
}
</script>

<style scoped lang="scss">
:deep(.v-table > .v-table__wrapper > table > thead) {
  background-color: #f7f8fa !important;
}
:deep(.v-selection-control__input) {
  color: var(--v-primary-base) !important;
}
.disabledItem {
  cursor: auto;
  opacity: .5;
}
</style>
