<template>
  <Dialog
    :title="readOnly ? '解析详情' : '人才入库'"
    v-model="dialogVisible"
    :modalClose="false"
    width="90%"
    @close="dialogVisible = false"
  >
    <div class="analysisInfoBox">
      <div class="analysisFile !w-50%">
          <!-- 门墩儿人才库 -->
          <template v-if="source === '招聘'">
            <el-tabs v-model="activeName" type="border-card">
              <el-tab-pane label="基本信息" name="info">
                <Info :id="personId" :user-id="userId" @echo="infoEcho" />
                <expExtend :user-id="userId" defaultShowAll class="m-t-20px" @echo="expEcho" />
              </el-tab-pane>
              <el-tab-pane label="附件简历" name="Attachment">
                <Attachment showPreview :user-id="userId" />
              </el-tab-pane>
            </el-tabs>
          </template>
          <!-- 简历解析 -->
          <template v-if="source === '简历'">
            <IFrame :src="fileUrl" />
          </template>
          <!-- 名片解析 -->
          <template v-if="['名片', '杂项'].includes(source)">
            <div class="image">
              <el-image class="!w-100%" :src="imgUrl" />
            </div>
          </template>
          <!-- 网页解析 -->
          <template v-if="source === '新任命'">
            <iframe
              id="MyIframe"
              class="!w-100% !h-[calc(100vh-90px)]"
              src=""
              frameborder="0"
            ></iframe>
          </template>
      </div>
      <div class="flex-1">
				<el-tabs type="border-card">
					<el-tab-pane label="已解析人才列表">
						<div class="tagBox mb-10px" v-if="tagList?.length">
              <el-tag 
                :type="index === tagCurrentIndex ? 'primary' : 'info'" 
                size="large"
                effect="plain"
                v-for="(val, index) in tagList"
                :key="val.name + index"
                class="mr-10px cursor-pointer mb-10px"
                @click="handleTagClick(index)"
              >
                <div class="flex items-center">
                  <el-checkbox v-if="!readOnly" v-model="val.checked" @click.stop />
                  <span class="ml-5px">{{ val.name }}</span>
                  <Icon icon="ep:view" class="ml-5px" /> 
                </div>
              </el-tag>
            </div>
            <FormPage	ref="FormPageRef"	formType="create" :readOnly="readOnly"	:itemData="itemData" />
					</el-tab-pane>
				</el-tabs>
      </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 { generateUUID } from '@/utils'
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() // 消息弹窗

// 配置 marked
// marked.setOptions({
//   breaks: true,       // 允许换行符
//   gfm: true,          // 支持 GitHub Flavored Markdown
//   sanitize: false   // 不转义 HTML（如果需要渲染 HTML 标签）
// })

const emit = defineEmits(['refresh'])
const dialogVisible = ref(false)
const FormPageRef = ref(null)
const itemData = ref({})
const tagList = ref([])
const tagCurrentIndex = ref(0)
const source = ref('')
const originData = ref([])

const imgUrl = ref(null)
const fileUrl = ref(null)
const personId = ref('')
const userId = ref('')
const activeName = ref('info')

// 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) => {
  if (['名片', '杂项'].includes(type)) {
    imgUrl.value = data.minio_path
  }
  if (type === '简历') fileUrl.value = data.minio_path
  
  if (type === '招聘') { // 门墩儿招聘-人员信息在组件中通过id和userId获取
    personId.value = data?.id || ''
    userId.value = data?.userId || ''
    activeName.value = 'info'
    // return
  }
  if (type === '新任命') {
    await nextTick()
    const response = await fetch(data.minio_path)
    const text = await response.text()

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

// 门墩儿招聘人才详情回显赋值
const infoEcho = (data) => {
  data = data ? JSON.parse(data) : null
  itemData.value = {
    ...itemData.value,
    name_zh: data?.name || '',
    email: data?.email || '',
    mobile: data?.phone || '',
    birthday: data?.birthday ? timesTampChange(data.birthday, 'Y-M-D') : '',
    age: data?.birthday ? timestampToAge(data.birthday) : null,
    created_at: data?.createTime ? timesTampChange(data.createTime, 'Y-M-D') : null,
    updated_at: data?.updateTime ? timesTampChange(data.updateTime, 'Y-M-D') : null,
  }
}

// 门墩儿招聘人才工作经历回显赋值
const expEcho = (workList) => {
  itemData.value = {
    ...itemData.value,
    career_path: workList ? workList.map(e => {
      return {
        hotel_zh: e?.enterpriseName || null,
        title_zh: e?.positionName || null,
        date: e?.startTime ? timesTampChange(e.startTime, 'Y-M-D') : null
      }
    }) : null
  }
}

// 重置
const resetData = () => {
  tagCurrentIndex.value = 0
  imgUrl.value = null
  fileUrl.value = null
  itemData.value = {}
  originData.value = []
  tagList.value = []
}

// 打开弹窗
const id = ref(null)
const readOnly = ref(false)
const open = async (task_type, parse_result, task_id, isDetail) => {
  readOnly.value = isDetail // 是否为查看详情
  id.value = task_id
  const { results } = parse_result
  resetData()
  source.value = task_type
  const dataList = results.map((e, index) => {
    tagList.value.push({
      name: e.data?.name_zh || `人才${ index + 1 }`,
      checked: true
    })
    return e
  })
  originData.value = cloneDeep(dataList)
  itemData.value = originData.value[0].data
  dealData(source.value, originData.value[0]) // 赋值左侧原始文件
  dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

// 当前操作数据
const handleTagClick = (index) => {
	tagCurrentIndex.value = index
  const row = originData.value[tagCurrentIndex.value]
	itemData.value = row.data
  dealData(source.value, row)
}

// 监听表单变化，同步更新originData中对应的数据
watch(() => FormPageRef.value?.formQuery, (newVal) => {
  if (tagCurrentIndex.value !== null && originData.value && originData.value.length > tagCurrentIndex.value) {
    originData.value[tagCurrentIndex.value].data = { ...newVal }
  }
}, { deep: true })

// 入库
const handleStore = async () => {
  // 验证originData数组中每个人才的name_zh字段，并处理mobile字段
  const results = [] // 只提交勾选的数据
  if (originData.value && Array.isArray(originData.value) && originData.value.length > 0) {
    for (let i = 0; i < originData.value.length; i++) {
      // 只校验勾选的数据
      if (tagList.value[i].checked) {
        const talent = originData.value[i]
        if (!talent.data.name_zh || talent.data.name_zh.trim() === '') {
          return message.warning(`第${i + 1}个人才中的中文姓名未填写，请完善后再进行保存`)
        }
        
        // 处理mobile字段，如果是数组则转换为字符串
        if (Array.isArray(talent.data.mobile)) {
          talent.data.mobile = talent.data.mobile.filter(i => Boolean(i)).map(j => String(j).replace(/，|,/g, '')).join(',');
        }
        results.push(talent) // 
      }
    }
  }
  
  if (!results?.length) return message.warning(`未选择人才，请选择要入库的人才！`)
  // await message.confirm('是否对当前选中的人才进行入库？')

  const loading = ElLoading.service({
    lock: true,
    text: '正在保存中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  try {
    const params = {
      task_id: id.value,
      data: {
        results
      }
    }
    await talentGatherApi.talentsAdd(JSON.stringify(params))
    message.success('入库成功！')
    dialogVisible.value = false
    // 刷新列表
    emit('refresh')
    // if (result.code === 202 || result.message.includes('疑似重复')) {
    //   if (!result.data?.main_card?.id) return
      
    //   await message.confirm('发现与当前名片的疑似重复数据，去处理')
    //   mergeFormRef.value.open(result.data?.main_card?.id)
    // }
  } finally {
    loading.close()
  }
}
</script>

<style lang="scss" scpoed>
.analysisInfoBox {
  display: flex;
	min-height: 50vh;
  .analysisFile {
    padding-right: 12px;
    overflow: auto;
  }
}
.tagBox {
  padding: 12px;
  border: 1px dashed #409EFF;
  border-radius: 4px;
}
:deep {
  .el-tag__content {
    display: flex;
    align-items: center;
  }
}
</style>