<template>
  <div class="mt-4">
    <div class="d-flex justify-center">
      <TextInput v-model="queryParams.content" :item="textItem" @enter="handleConfirm" @appendInnerClick="handleConfirm"></TextInput>
    </div>
    <div>
      <Position :isClear="clear" @clear="clear = false" :selectData="position" @select="val => position = val"></Position>
      <div class="font-size-15 d-flex align-center color-666">
        <span>地&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;区：</span>
        <cascade v-model="queryParams.areaIds" :item="selectItems" @change="val => handleSearch('areaIds', val)" style="width: 300px;"></cascade>
      </div>
      <CommonPage :isClear="clear" @clear="clear = false" class="my-3" dictType="menduner_education_type" title="最高学历" @select="val => handleSearch('eduType', val)"></CommonPage>
      <CommonPage :isClear="clear" @clear="clear = false" dictType="menduner_exp_type" title="工作经验" @select="val => handleSearch('expType', val)"></CommonPage>
      <v-divider class="mt-1 mb-3"></v-divider>
      <div>
        <div>
          <v-chip v-for="k in position" :key="k.id" label class="mr-3" closable @click:close="handleClose(k)">{{ k.nameCn }}</v-chip>
        </div>
        <div class="text-end">
          <v-btn  color="primary" variant="text" @click="handleClear">清空筛选条件</v-btn>
        </div>
      </div>
      <div class="text-center mt-3">
        <v-btn class="half-button" color="primary" @click="handleConfirm">搜 索</v-btn>
      </div>
    </div>
  </div>

  <div class="mt-10" v-loading="loading">
    <v-divider></v-divider>
    <div class="py-3">
      <v-card
        v-for="item in items"
        :key="item.id"
        elevation="5"
        class="mb-3"
        :subtitle="item.subTitle"
        :title="item?.name"
      >
        <template #prepend>
          <v-badge
            v-if="item?.sex === '1' || item?.sex === '2'"
            class="mr-3 cursor-pointer"
            bordered
            offset-y="6"
            :color="badgeColor(item)"
            :icon="badgeIcon(item)"
            @click="handleToPersonDetail(item)"
          >
            <v-avatar size="48" :image="getUserAvatar(item.avatar, item.sex)"></v-avatar>
          </v-badge>
          <v-avatar v-else class="mr-3 cursor-pointer" size="48" :image="getUserAvatar(item.avatar, item.sex)"  @click="handleToPersonDetail(item)"></v-avatar>
        </template>
        <template #append>
          <v-btn color="primary" variant="text" @click="handleInvite(item)">邀请面试</v-btn>
          <v-btn color="primary" variant="text" @click="handleCommunicate(item)">立即沟通</v-btn>
        </template>
        <template #title>
          <span class="cursor-pointer defaultLink" @click="handleToPersonDetail(item)">
            {{ item.name }}
          </span>
        </template>
        <template #subtitle>
          <div class="d-flex">
            <div class="mr-10">{{ item.subTitle }}</div>
            <div class="mr-10">首次工作时间： {{ timesTampChange(item.firstWorkTime, 'Y-M-D') }}</div>
            <div v-if="item.interestedList?.length" class="mr-10 d-flex flex-wrap">
              <div>求职意向：</div>
              <div
                v-for="(interested, index) in item.interestedList"
                :key="interested.id"
              >
                <span :class="{'mx-3': index}">{{ (index ? '|' : '') }}</span>
                <span>{{ positionData.find(e => e.id === interested.positionId)?.nameCn ?? '暂无' }}</span>
              </div>
            </div>
          </div>
        </template>
        
        <div class="px-5 pb-8">
          <div v-if="item?.workList?.length">
            <div class="second-title">工作经验</div>
            <v-timeline density="compact" align="start" side="end" truncate-line="both">
              <v-timeline-item v-for="(j, i) in item.workList" :key="i" dot-color="primary" size="small">
                <div v-if="j.show" class="timeline-item mt-1">
                  <div v-ellipse-tooltip style="width: 20%;">
                    <span>{{ j.startTimeStr }}</span>
                    <span v-if="j.endTimeStr"> - {{ j.endTimeStr }}</span>
                    <span v-if="j.year"> ({{ j.year }})</span>
                  </div>
                  <div v-ellipse-tooltip class="timeline-item-name mx-3">{{ formatName(j.enterpriseName) || '' }}</div>
                  <div v-ellipse-tooltip class="timeline-item-name">{{ formatName(j.positionName) || '' }}</div>
                </div>
              </v-timeline-item>
            </v-timeline>
          </div>
        </div>
      </v-card>
    </div>
    <CtPagination :total="total" :page="query.pageNo" :limit="query.pageSize" @handleChange="handleChangePage"></CtPagination>
  </div>

  <CtDialog :visible="showInvite" :widthType="4" titleClass="text-h6" title="邀请面试" @close="showInvite = false" @submit="handleSubmit">
    <InvitePage v-if="showInvite" ref="inviteRef" :item-data="itemData" :position="positionList"></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: 'searchRetrieval' })
import { ref, computed } from 'vue'
import CommonPage from '../components/common.vue'
import Position from './components/position.vue'
import { getPersonSearchPage } from '@/api/enterprise.js'
import { dealDictArrayData } from '@/utils/position'
import { timesTampChange } from '@/utils/date'
import { talkToUser, defaultTextEnt } from '@/hooks/web/useIM'
import { getUserAvatar } from '@/utils/avatar'
import { getJobAdvertisedList } from '@/api/position'
import Snackbar from '@/plugins/snackbar'
import { saveInterviewInvite } from '@/api/recruit/enterprise/interview'
import { useRouter } from 'vue-router'; const router = useRouter()
import InvitePage from '@/views/recruit/enterprise/interviewManagement/components/invite'
import { getDict } from '@/hooks/web/useDictionaries'
import { getTimeDifferenceInChinese } from '@/utils/date'
import { formatName } from '@/utils/getText'

const textItem = ref({
  type: 'text',
  width: 600,
  value: '',
  label: '输入关键字',
  clearable: true,
  appendInnerIcon: 'mdi-magnify'
})
const query = ref({
  pageNo: 1,
  pageSize: 5
})
const queryParams = ref({
  content: null,
  positionIds: [],
  areaIds: [],
  expType: '',
  eduType: ''
})

const selectItems = ref({
  value: null,
  itemText: 'name',
  itemValue: 'id',
  hideDetails: true,
  clearable: true,
  multiple: true,
  checkStrictly: true,
  collapseTags: true,
  placeholder: '地区',
  items: [],
})

const positionData = ref([])

getDict('areaTreeData', null, 'areaTreeData').then(res => {
  const data = res?.data?.length ? res.data : []
  if (data[0] && data[0].id === 10000) data[0].children = []
  selectItems.value.items = data
})

getDict('positionData', {}, 'positionData').then(({ data }) => {
  positionData.value = data
})

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: '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 getData = async () => {
  loading.value = true
  try {
    const res = await getPersonSearchPage(Object.assign(queryParams.value, query.value))
    if (!res?.list?.length) {
      items.value = []
      total.value = 0
      return
    }
    items.value = dealDictArrayData([], res.list).map(e => {
      e.regName = e.reg?.str ?? ''
      e.areaName = e.area?.str ?? '暂无'
      e.subTitle = [e.jobStatusName, e.expName ? e.expName + '工作经验' : null, e.eduName, e.maritalStatusName].filter(k => k).join(' | ')
      if (e.workList?.length) {
        e.workList.forEach(exp => {
          exp.startTimeStr = exp.startTime ? timesTampChange(exp.startTime, 'Y-M') : '未填写工作时间'
          exp.endTimeStr = exp.startTime ? exp.endTime ? timesTampChange(exp.endTime, 'Y-M') : '至今' : ''
          exp.year = exp.endTimeStr ? getTimeDifferenceInChinese(exp.startTime, exp.endTime) : ''
          // 未填写工作经验内容，不展示
          exp.show = Boolean(exp.year) || Boolean(exp.enterpriseName) || Boolean(exp.positionName)
        })
      }
      return e
    })
    total.value = res.total
  } finally {
    loading.value = false
  }
}

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

const position = ref([])
const handleSearch = (key, value) => {
  query.value.pageNo = 1
  queryParams.value[key] = value
}

const checkValue = (obj) => {
  return Object.values(obj).some(value => {  
    return value !== null && value !== undefined && value !== '' && (Array.isArray(value) ? value.length > 0 : true)
  })
}

const handleConfirm = () => {
  const positionIds = position.value.map(k => k.id)
  queryParams.value.positionIds = positionIds || []
  query.value.pageNo = 1
  if (!checkValue(queryParams.value)) {
    Snackbar.warning('至少选择一个条件进行搜索')
    items.value = []
    total.value = 0
    return
  }
  getData()
}

// 清空筛选条件
const clear = ref(false)
const handleClear = () => {
  position.value = []
  queryParams.value = {
    content: null,
    positionIds: [],
    areaIds: [],
    expType: '',
    eduType: ''
  }
  query.value.pageNo = 1
  items.value = []
  total.value = 0
  clear.value = true
}

const handleClose = (item) => {
  position.value = position.value.filter(k => k.id !== item.id)
}

// 职位列表
const jobNum = ref(0)
const positionList = ref([])
const getJobList = async () => {
  const { total, list } = await getJobAdvertisedList({ pageNo: 1, pageSize: 10, hasExpiredData: false, status: 0 })
  jobNum.value = total
  if (!list?.length) {
    positionList.value = []
    jobNum.value = 0
    return
  }
  positionList.value = list.map(e => {
    const salary = e.payFrom && e.payTo ? `${e.payFrom ? e.payFrom + '-' : ''}${e.payTo}${e.payName ? '/' + e.payName : ''}` : '面议'
    return {
      label: `${e.name}_${e.areaName ? e.area?.str : '全国'} ${salary}`,
      value: e.id,
      data: e
    }
  })
}
getJobList()

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

const showInvite = ref(false)
const showTip = ref(false)
const inviteRef = ref()
const itemData = ref({})
const handleInvite = (item) => {
  if (jobNum.value === 0) return Snackbar.warning('请先发布职位')
  itemData.value = item
  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
  }
  delete query.id
  await saveInterviewInvite(query)
  showInvite.value = false
  showTip.value = true
}

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

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

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">
.clear:hover {
  color: var(--v-primary-base);
}

.second-title {
  color: var(--color-666);
  font-size: 15px;
}

.timeline-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  color: var(--color-666);
  font-size: 13px;
  .timeline-item-name {
    width: 40%;
  }
}
:deep(.v-timeline-item__body) {
  width: 100%;
}
:deep(.v-timeline--vertical.v-timeline) {
  row-gap: 0;
}
:deep(.v-timeline-divider__dot--size-small) {
  width: 10px !important;
  height: 10px !important;
  margin-top: 10px !important;
}
:deep(.v-timeline-divider__inner-dot) {
  width: 10px !important;
  height: 10px !important;
}
</style>
