<template>
  <ContentWrap>
    <div class="box flex items-center justify-center decoration-column transition-duration-500" :class="{ active: isSearch }">
      <div class="!w-75%">
        <el-input
          v-model.trim="searchValue"
          size="large"
					clearable
          placeholder="请输入您的描述信息定位人才"
          @keydown.enter="handleSearch"
					@clear="handleSearch('clear')"
        >
					<template #append>
						<el-button :icon="Search" @click="handleSearch" />
					</template>
				</el-input>
				<el-text v-if="!isSearch" class="text-xs !color-gray-400">例如：有酒店筹开经验，且担任总经理的人</el-text>
      </div>
    </div>
  </ContentWrap>
	
  <ContentWrap v-if="isSearch">
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      row-key="pg_id"
    >
      <el-table-column label="中文名" align="left" prop="name_zh" />
      <el-table-column label="英文名" align="left" prop="name_en" />
      <el-table-column label="联系电话" align="center" prop="mobile" />
      <el-table-column label="电子邮箱" align="center" prop="email" />
      <el-table-column label="更新时间" align="center" prop="updated_at" />
      <el-table-column label="操作" align="left">
        <template #default="scope">
          <el-button link type="primary" @click="handleDetails(scope.row.pg_id)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>

	<Dialog
    title="人才详情"
    v-model="dialogVisible"
    :modalClose="false"
    width="90%"
    @close="dialogVisible = false"
  >
		<el-row :gutter="20">
			<el-col :span="9">
				<div v-if="sourceList && sourceList.length > 0" class="!h-80vh overflow-y-auto">
					<el-card v-for="val in sourceList" :key="val.id" class="mb-10px">
						<template #header>
							<CardTitle :title="typeObj[val.task_type] + val.source_date" />
						</template>
						<el-image 
							v-if="['名片', '杂项'].includes(val.task_type)"
							width="100%"
							:preview-src-list="[val.minio_path]"
							class="cursor-pointer"
							:src="val.minio_path"
						/>

						<!-- 门墩儿招聘 -->
						<template v-if="val.task_type === '招聘'">
							<el-tabs v-model="activeName" type="border-card">
								<el-tab-pane label="基本信息" name="info">
									<Info :id="personId" :user-id="userId" />
									<expExtend :user-id="userId" defaultShowAll class="m-t-20px" />
								</el-tab-pane>
								<el-tab-pane label="附件简历" name="Attachment">
									<Attachment showPreview :user-id="userId" />
								</el-tab-pane>
							</el-tabs>
						</template>

						<template v-if="val.task_type === '简历'">
							<IFrame :src="val.minio_path" />
						</template>

						<template v-if="val.task_type === '新任命'">
							<iframe
								:id="val.id"
								class="markdownContent"
								src=""
								frameborder="0"
							></iframe>
						</template>
					</el-card>
				</div>
				<el-card v-else>
					<el-empty description="暂无来源" />
				</el-card>
			</el-col>
			<el-col :span="15">
				<el-descriptions title="人才标签" :column="1" border>
					<el-descriptions-item label="标签">
						<el-tag v-for="k in talentTags" :key="k.talent" type="success" class="mr-10px my-10px">{{ k.name_zh }}</el-tag>
					</el-descriptions-item>
				</el-descriptions>

				<el-descriptions class="my-30px" title="基本信息" :column="2" border>
					<el-descriptions-item 
						v-for="val in keyArr" 
						:key="val.value" 
						:label="val.label"
					>
						{{ detail[val.value] ?? '' }}
					</el-descriptions-item>
					<el-descriptions-item label="状态">
						<el-tag :type="detail.status === 'active' ? 'primary' : 'danger'">
							{{ detail.status === 'active' ? '已启用' : '已禁用' }}
						</el-tag>
					</el-descriptions-item>
				</el-descriptions>

				<div class="career">
					<div class="el-descriptions__header el-descriptions__title">职业轨迹</div>
					<el-table :data="detail.career_path" border>
						<el-table-column prop="hotel_zh" label="酒店名称">
							<template #default="{ row }">{{ row.hotel_zh ?? '-'}}</template>
						</el-table-column>
						<el-table-column prop="title_zh" label="职位名称">
							<template #default="{ row }">{{ row.title_zh ?? '-'}}</template>
						</el-table-column>
						<el-table-column prop="date" label="日期">
							<template #default="{ row }">{{ row.date ?? '-'}}</template>
						</el-table-column>
					</el-table>
				</div>
			</el-col>
		</el-row>
    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup>
import { Search } from '@element-plus/icons-vue'
import { generateUUID } from '@/utils'
import { marked } from 'marked'
import { talentSearchApi } from '@/api/menduner/system/talentMap/search'
import { talentLabelingApi } from '@/api/menduner/system/talentMap/labeling'
import Info from '@/views/menduner/system/person/details/components/info.vue'
import expExtend from '@/views/menduner/system/person/details/components/expExtend.vue'
import Attachment from '@/views/menduner/system/person/details/components/attachment.vue'

const message = useMessage() // 消息弹窗
const searchValue = ref(null)
const formRef = ref()
const loading = ref(false)
const list = ref([])
const abortController = ref(null)

const dialogVisible = ref(false)
const detailsLoading = ref(false)
const detail = ref({})
const talentTags = ref([])
const keyArr = [
  { label: '中文名', value: 'name_zh' },
  { label: '英文名', value: 'name_en' },
  { label: '职位/头衔(中)', value: 'title_zh' },
  { label: '职位/头衔(英)', value: 'title_en' },
  { label: '生日', value: 'birthday' },
  { label: '年龄', value: 'age' },
  { label: '籍贯', value: 'native_place' },
  { label: '工作地', value: 'residence' },
  { label: '性别', value: 'gender' },
  { label: '电子邮箱', value: 'email' },
  { label: '固定电话', value: 'phone' },
  { label: '手机号码', value: 'mobile' },
  { label: '酒店/公司名称(中)', value: 'hotel_zh' },
  { label: '酒店/公司名称(英)', value: 'hotel_en' },
  { label: '地址(中)', value: 'address_zh' },
  { label: '地址(英)', value: 'address_en' },
  { label: '邮政编码(中)', value: 'postal_code_zh' },
  { label: '邮政编码(英)', value: 'postal_code_en' },
  { label: '品牌名称(中)', value: 'brand_zh' },
  { label: '品牌名称(英)', value: 'brand_en' },
  { label: '隶属关系(中)', value: 'affiliation_zh' },
  { label: '隶属关系(英)', value: 'affiliation_en' },
  { label: '品牌组合', value: 'brand_group' },
  { label: '人才信息', value: 'talent_profile' },
  { label: '创建时间', value: 'created_at' },
  { label: '更新时间', value: 'updated_at' }
]
const typeObj = {
	'招聘': '门墩儿招聘',
	'新任命': '门墩儿新任命',
	'名片': '名片',
	'简历': '简历',
	'杂项': '杂项'
}

// markdown回显
const showPage = (id, html) => {
   // 将 data-src 转化为 src
  html = html.replace(/data-src/g, 'src')
    .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/g, '')
    .replace(/https/g, 'http')

  const iframe = document.getElementById(id)
  
  const doc = iframe.contentDocument || iframe.document
  // 设置 iframe 中请求不发送 referrer，以绕过图片防盗链
  const htmlArr = html.split('</head>')
  const html_src_add = htmlArr[0] + '<meta name="referrer" content="never"></head>' + htmlArr[1]
  doc.open()
  doc.write(html_src_add)
  doc.close()

  // 设置图片宽高
  let iwindow = iframe.contentWindow;
  iframe.addEventListener('load',function () {
    let idoc = iwindow.document;
    let imgs = idoc.getElementsByTagName('img')
    for (let i = 0; i < imgs.length; i++) {
      const img = imgs[i]
      if (img) {
        if (img.width >= img.height) {
          img.width = iframe.clientWidth / 2
        } else {
          img.height = iframe.clientHeight / 2
          let left = (iframe.clientWidth - img.width) / 2
          img.style.marginLeft = left + "px"
        }
      }
    }
  })
}

const handleShowPage = async (id, url) => {
	await nextTick()
	const response = await fetch(url)
	const text = await response.text()
	const doc = `
		<!DOCTYPE html>
		<html class="">
			<head></head>
			<body>
				${marked(text)}
			</body>
		</html>
	`
	showPage(id, doc)
}

const resetData = () => {
	sourceList.value = []
	talentTags.value = []
	detail.value = {}
	personId.value = null
	userId.value = null
}

const personId = ref('')
const userId = ref('')
const activeName = ref('info')
const sourceList = ref([])
const handleDetails = async (id) => {
	if (!id) return

	resetData()

	detailsLoading.value = true
	try {
    const result = await talentSearchApi.getBusinessCardDetails(id)
    detail.value = result || {}

		if (result?.origin_source) {
			const list = typeof result.origin_source === 'string' ? JSON.parse(result.origin_source) : result.origin_source
			// 时间排序
			const sortedList = list.sort((a, b) => new Date(b.source_date) - new Date(a.source_date))
			sourceList.value = sortedList.map(e => {
				const item = { ...e, id: generateUUID() }
				if (e.task_type === '新任命') {
					setTimeout(() => {
						handleShowPage(item.id, item.minio_path)
					}, 200)
				}

				if (e.task_type === '招聘') { // 门墩儿招聘-人员信息在组件中通过id和userId获取
					const obj = typeof e.minio_path === 'string' ? JSON.parse(e.minio_path) : e.minio_path
					personId.value = obj?.id || ''
					userId.value = obj?.userId || ''
					activeName.value = 'info'
				}
				return item
			})
		}

		// 获取人才标签
		const tagData = await talentLabelingApi.getTalentTagById(id)
		talentTags.value = tagData ?? []

		dialogVisible.value = true
  } finally {
		detailsLoading.value = false
	}
}

const getList = async () => {
	loading.value = true
	try {
		abortController.value = new AbortController()
		const signal = abortController.value.signal
		const data = await talentSearchApi.getTalentList({ query_requirement: searchValue.value }, signal)
		if (!data || !data.length) {
			message.warning('暂无数据，请更换查询条件后再试')
			list.value = []
			isSearch.value = false
			return
		}
		list.value = data
	} finally {
		loading.value = false
	}
}

const isSearch = ref(false)
const handleSearch = (type='search') => {
	if (type === 'clear') {
		list.value = []
		isSearch.value = false
		if (abortController.value) {
      abortController.value.abort() 
      abortController.value = null
    }
		return
	}
	isSearch.value = true
	if (!searchValue.value) return message.warning('请输入查询条件')
	getList()
}
</script>

<style scoped lang="scss">
.box {
  min-height: 500px;
  &.active {
    min-height: unset;
  }
}
:deep {
	.career {
		.el-table th.el-table__cell {
			background-color: #f5f7fa;
		}
	}
	.markdownContent {
		width: 100%;
		max-width: 100%;
		height: 600px;
	}
}
</style>