<template>
  <div>
    <div class="d-flex align-center mt-5" style="width: 600px; margin: auto;">
      <Autocomplete v-model="query.jobId" :item="selectItems" @change="handleChange"></Autocomplete>
    </div>
    <CtTable
      class="mt-3"
      :items="items"
      :headers="headers"
      :loading="loading"
      :elevation="0"
      :isTools="false"
      :showPage="true"
      height="calc(100vh - 410px)"
      :total="total"
      :page-info="query"
      itemKey="id"
      @pageHandleChange="handleChangePage"
    >
      <template #name="{ item }">
        <div class="d-flex align-center cursor-pointer" @click="handleToPersonDetail(item)">
          <v-badge
            v-if="item?.sex === '1' || item?.sex === '2'"
            bordered
            offset-y="6"
            :color="badgeColor(item)"
            :icon="badgeIcon(item)">
            <v-avatar size="40" :image="getUserAvatar(item.avatar, item.sex)"></v-avatar>
          </v-badge>
          <v-avatar v-else size="40" :image="getUserAvatar(item.avatar, item.sex)"></v-avatar>
          <span class="defaultLink ml-3 mt-2">{{ item?.name }}</span>
        </div>
      </template>
      <template #interestedPositions="{ item }">
        <div style="max-width: 200px" v-ellipse-tooltip>{{ item.position?.positionNames }}</div>
      </template>
      <template #lastWorkExp="{ item }">
        {{ item?.lastWorkExp && Object.keys(item?.lastWorkExp).length > 0 ? `${item.lastWorkExp?.enterpriseName ? item.lastWorkExp?.enterpriseName + ' - ' : ''}${item.lastWorkExp.positionName}` : '' }}
      </template>
      <template #actions="{ item }">
        <v-btn color="primary" variant="text" @click="handleInvite(item)">邀请面试</v-btn>
        <v-btn color="primary" variant="text" @click="handleCommunicate(item)">立即沟通</v-btn>
      </template>
    </CtTable>
  </div>

  <!-- 面试邀请 -->
  <CtDialog :visible="showInvite" :widthType="4" titleClass="text-h6" title="邀请面试" @close="showInvite = false; itemData = {}" @submit="handleSubmit">
    <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>
</template>

<script setup>
defineOptions({ name: 'searchRecommend' })
import { ref, computed } from 'vue'
import { getPersonRecommendPage, getJobAdvertised } from '@/api/enterprise'
import { timesTampChange } from '@/utils/date'
import { dealDictArrayData } from '@/utils/position'
import { getUserAvatar } from '@/utils/avatar'
import InvitePage from '@/views/recruit/enterprise/resume/components/invite'
import Snackbar from '@/plugins/snackbar'
import { saveInterviewInvite } from '@/api/recruit/enterprise/interview'
import { useRouter } from 'vue-router'; const router = useRouter()
import { talkToUser, defaultTextEnt } from '@/hooks/web/useIM'
import { formatName } from '@/utils/getText'

const query = ref({
  pageNo: 1,
  pageSize: 10,
  jobId: null
})
const selectItems = ref({
  label: '招聘中职位',
  placeholder: '请选择招聘中职位',
  clearable: true,
  width: 600,
  items: []
})
const total = ref(0)
const items = ref([])
const loading = ref(false)
const headers = ref([
  { title: '姓名', key: 'name', sortable: false },
  { title: '求职状态', key: 'jobStatusName', sortable: false },
  { title: '感兴趣职位', key: 'interestedPositions', sortable: false },
  { title: '最近一份工作经历', key: 'lastWorkExp', sortable: false },
  { title: '当前角色', key: 'type', sortable: false, value: item => item.type === '1' ? '在校学生' : '职场人士' },
  { title: '工作年限', key: 'expName', sortable: false },
  { title: '最高学历', key: 'eduName', sortable: false },
  { title: '所在城市', key: 'areaName', sortable: false },
  { title: '户籍地', key: 'regName', sortable: false },
  { title: '婚姻状况', key: 'maritalStatusName', sortable: false },
  { title: '首次工作时间', key: 'firstWorkTime', sortable: false, value: item => timesTampChange(item.firstWorkTime, 'Y-M-D') },
  { title: '操作', key: 'actions', sortable: false }
])
const inviteRef = ref()
const showTip = ref(false)
const showInvite = ref(false)

// 职位列表
const getJobList = async () => {
  const data = await getJobAdvertised({ status: 0 })
  if (data.length) {
    const list = dealDictArrayData([], data)
    selectItems.value.items = list.map(e => {
      const salary = e.payFrom && e.payTo ? `${e.payFrom}-${e.payTo}${e.payName ? '/' + e.payName : ''}` : '面议'
      return { label: `${formatName(e.name)}_${e.areaName ? e.area?.str : '全国'} ${salary}_${e.status === '0' ? '招聘中' : '已关闭'}`, value: e.id, data: e }
    })
  }
}
getJobList()

// 列表
const getData = async () => {
  loading.value = true
  try {
    const res = await getPersonRecommendPage(query.value)
    if (!res.list.length) {
      items.value = []
      total.value = 0
      return
    }
    items.value = dealDictArrayData([], res.list).map(e => {
      e.areaName = e.area?.str ?? ''
      e.regName = e.reg?.str ?? ''
      return e
    })
    total.value = res.total
  } finally {
    loading.value = false
  }
}

// 推荐
const handleChange = () => {
  query.value.pageNo = 1
  if (!query.value.jobId) {
    items.value = []
    total.value = 0
    return
  }
  getData()
}

// 分页
const handleChangePage = (e) =>{
  query.value.pageNo = e
  getData()
}

// 面试邀请
const itemData = ref({})
const handleInvite = ({ userId }) => {
  const job = selectItems.value.items.find(e => e.value === query.value.jobId).data
  itemData.value = {
    userId,
    job
  }
  showInvite.value = true
}

const handleSubmit = async () => {
  const { valid } = await inviteRef.value.CtFormRef.formRef.validate()
  if (!valid) {
    return
  }
  const query = inviteRef.value.getQuery()
  if (!query.time) {
    Snackbar.warning('面试时间不能为空')
    return
  }
  await saveInterviewInvite(query)
  showInvite.value = false
  showTip.value = true
  getData()
  itemData .value = {}
}

// 立即沟通
const handleCommunicate = async (item) => {
  // // 企业必须有招聘中的职位才能发起沟通
  if (!selectItems.value.items.length) return Snackbar.warning('请先发布职位')
  const userId = item.userId
  if (!userId) return
  await talkToUser({userId, text: defaultTextEnt})
  let url = `/recruit/enterprise/invite/chatTools?id=${userId}`
  router.push(url)
}

// 人才详情
const handleToPersonDetail = ({ userId }) => {
  if (!userId) return
  window.open(`/recruit/enterprise/talentPool/details/${userId}`)
}

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

const badgeColor = computed(() => (item) => {
  return (item && item.sex) ? (item.sex === '1' ? '#1867c0' : 'error') : 'error'
})
const badgeIcon = computed(() => (item) => {
  return (item && item.sex) ? (item.sex === '1' ? 'mdi-gender-male' : 'mdi-gender-female') : 'mdi-gender-female'
})
</script>

<style scoped lang="scss">

</style>
