<template>
  <Dialog
    title="人才审核入库"
    v-model="dialogVisible"
    :modalClose="false"
    width="90%"
    @close="dialogVisible = false"
  >
    <div class="analysisInfoBox">
      <div class="analysisFile !w-50%">
        <div v-if="hasSourceUrl">
          <!-- 门墩儿招聘 -->
          <template v-if="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="type === '简历'">
            <IFrame :src="originUrl" />
          </template>
          <!-- 名片解析 -->
          <template v-if="['名片', '杂项'].includes(type)">
            <div class="image">
              <el-image class="!w-100%" :src="originUrl" />
            </div>
          </template>
          <!-- 网页解析 -->
          <template v-if="type === '新任命'">
            <iframe
              id="MyIframe"
              class="!w-100% !h-70vh"
              src=""
              frameborder="0"
            ></iframe>
          </template>
        </div>
        <el-empty v-else description="暂无原始文件" />
      </div>
      <div class="flex-1">
        <FormPage	ref="FormPageRef" formType="create"	:itemData="itemData" :readOnly="readOnly" />
      </div>
    </div>
    <template #footer>
      <el-button v-if="!readOnly" @click="handleStore" type="success">入 库</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup>
/** 人才采集 入库 */
defineOptions({ name: 'Store' })
import { ElLoading } from 'element-plus'
import FormPage from '@/views/menduner/system/talentMap/components/FormPage.vue'
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'
import { cloneDeep } from 'lodash-es'
import { marked } from 'marked'
import { timesTampChange, timestampToAge } from '@/utils/transform/date'
import { talentGatherApi } from '@/api/menduner/system/talentMap/gather'

const message = useMessage() // 消息弹窗

const emit = defineEmits(['refresh'])
const dialogVisible = ref(false)
const FormPageRef = ref(null)
const itemData = ref({})
const type = ref('')
const originData = ref([])

const originUrl = ref(null)
const personId = ref('')
const userId = ref('')
const activeName = ref('info')
const hasSourceUrl = ref(false)

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

  nextTick(() => {
    const iframe = document.getElementById('MyIframe')
    if (!iframe) return
    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 dealData = async (type, data) => {
  hasSourceUrl.value = data.image_path ? true : false
  if (!data.image_path) return

  if (['名片', '杂项', '简历', '招聘'].includes(type)) {
    originUrl.value = data.image_path
  }
  
  if (type === '招聘') { // 门墩儿招聘-人员信息在组件中通过id和userId获取
    const obj = JSON.parse(data.image_path)
    personId.value = obj?.id || ''
    userId.value = obj?.userId || ''
    activeName.value = 'info'
  }
  if (type === '新任命') {
    await nextTick()
    const response = await fetch(data.image_path)
    const text = await response.text()

    const doc = `
      <!DOCTYPE html>
      <html class="">
        <head></head>
        <body>
          ${marked(text)}
        </body>
      </html>
    `
    showPage(doc)
  }
}

// 重置
const resetData = () => {
  readOnly.value = false
  taskId.value = null
  type.value = null
  originUrl.value = null
  itemData.value = {}
  originData.value = []
}

// 打开弹窗
const taskId = ref(null)
const readOnly = ref(false)
const open = async (task_type, parse_result, task_id, isDetail) => {
  resetData()
  readOnly.value = isDetail
  taskId.value = task_id
  type.value = task_type

  originData.value = parse_result
  itemData.value = originData.value[0]
  dealData(type.value, originData.value[0]) // 赋值左侧原始文件
  dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

// 入库
const handleStore = async () => {
  if (!itemData.value.id) return message.warning('缺少id，请稍后再试')
  const formQuery = FormPageRef.value?.formQuery || {}
  if (!formQuery?.name_zh && !formQuery?.name_en) return message.warning(`请完善中文名称或英文名称后再进行保存`)
  if (Array.isArray(formQuery.mobile)) {
    formQuery.mobile = formQuery.mobile.filter(i => Boolean(i)).map(j => String(j).replace(/，|,/g, '')).join(',')
  }
 
  const params = {
    task_id: taskId.value,
    task_type: type.value,
    data: {
      results: [Object.assign(itemData.value, formQuery, { career_path: FormPageRef.value.careerTrajectory })]
    }
  }

  const loading = ElLoading.service({
    lock: true,
    text: '正在入库中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  try {
    const result = await talentGatherApi.talentsAdd(JSON.stringify(params))
    message.success('入库成功！')
    dialogVisible.value = false
    // 刷新列表
    emit('refresh')

    if (result?.message.includes('疑似重复')) {
      message.notifyWarning('发现疑似重复记录，请前往人才去重处理')
    }
  } finally {
    loading.close()
  }
}
</script>

<style lang="scss" scpoed>
.analysisInfoBox {
  display: flex;
	min-height: 50vh;
  .analysisFile {
    padding-right: 12px;
    overflow: auto;
  }
}
</style>