<template>
  <Dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    :modalClose="false"
    width="90%"
    @close="dialogVisible = false"
  >
    <div class="analysisInfoBox">
      <div class="analysisFile !w-50%">
        <div v-if="isDrilling">
					<!-- 门墩儿招聘 -->
					<template v-if="source === '招聘'">
						<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="source === '简历'">
						<IFrame :src="minio_path" />
					</template>

					<!-- 名片、杂项 -->
					<template v-if="['名片', '杂项'].includes(source)">
						<div class="image">
							<el-image class="!w-100%" :src="minio_path" :initial-index="0" :preview-src-list="[minio_path]" />
						</div>
					</template>

					<!-- 门墩儿新任命 -->
					<template v-if="source === '新任命'">
						<iframe
							id="MyIframe"
							class="!w-100% !h-[calc(100vh-90px)]"
							src=""
							frameborder="0"
						></iframe>
					</template>
				</div>
				<div v-else class="flex items-center justify-center !h-100%">请在右侧的原始数据选择要查看的项点击详情</div>
      </div>

      <div class="flex-1">
				<el-tabs type="border-card">
          <el-tab-pane label="原始数据">
            <el-table
              v-loading="false"
              class="mb-50px"
              v-if="otherList?.length > 0"
              :data="otherList"
              border
            >
							<el-table-column label="文件名" align="center" prop="original_filename" />
							<el-table-column label="发布时间" align="center" prop="publish_time" />
							<el-table-column label="状态" align="center" prop="status">
								上传成功
							</el-table-column>
							<el-table-column label="操作" align="center" fixed="right" min-width="110">
								<template #default="scope">
									<el-button link type="primary" @click="handleDetail(scope.row)">详情</el-button>
								</template>
							</el-table-column>
						</el-table>

						<el-table 
              v-loading="false"
              :data="list"
              border
              row-key="minio_path"
              height="60vh"
              @select="handleSelect"
              @select-all="handleSelectAll"
            >
              <el-table-column v-if="showAnalysisBtn" type="selection" width="55" :selectable="selectable" />
							<el-table-column v-if="source !== '招聘'" label="文件名" align="center" prop="original_filename" />
							<el-table-column v-if="source === '新任命'" label="发布时间" align="center" prop="publish_time" />
							<template v-if="source === '招聘'">
								<el-table-column label="姓名" align="center" prop="name_zh" />
								<el-table-column label="联系电话" align="center" prop="mobile" />
							</template>
							<el-table-column label="状态" align="center" prop="status" />
							<el-table-column v-if="list.length > 1" label="操作" align="center" fixed="right" min-width="110">
								<template #default="scope">
									<el-button link type="primary" @click="handleDetail(scope.row)">详情</el-button>
								</template>
							</el-table-column>
						</el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <template #footer>
      <el-button type="primary" v-if="showAnalysisBtn" @click="handleAnlysis">执行解析</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup>
/** 人才采集 详情 */
defineOptions({ name: 'GatherDetail' })
import { marked } from 'marked'
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 emit = defineEmits(['analysis'])
const message = useMessage() // 消息弹窗

const dialogTitle = ref(null)
const dialogVisible = ref(false)
const otherList = ref([])
const list = ref([])
const selectable = (row) => !row.disabled
const originUrl = ref(null)
const source = ref(null)
const typeObj = {
	'简历': '简历',
	'名片': '名片',
	'杂项': '杂项',
	'招聘': '门墩儿招聘',
	'新任命': '门墩儿新任命'
}

const resetData = () => {
  originData.value = {}
	list.value = []
  otherList.value = []
	originUrl.value = null
	source.value = null
	isDrilling.value = false
  showAnalysisBtn.value = false
	dialogTitle.value = null
}

// 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 minio_path = ref(null)
const personId = ref(null)
const userId = ref(null)
const activeName = ref('info')
const dealData = async (data) => {
	const type = source.value
  if (['名片', '杂项', '简历'].includes(type)) {
    minio_path.value = data.minio_path
  }
  
	// 门墩儿招聘-人员信息在组件中通过id和userId获取
  if (type === '招聘') {
    personId.value = data?.id || ''
    userId.value = data?.userId || ''
    activeName.value = 'info'
  }

  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 handleSelect = (arr, row) => {
  const index = list.value.indexOf(row)
  list.value[index].parse_flag = arr.length ? 1 : 0
}
const handleSelectAll = (arr) => {
  list.value.forEach(e => {
    if (!e.disabled) e.parse_flag = arr.length ? 1 : 0 
  })
}

// 打开弹窗
const originData = ref({})
const showAnalysisBtn = ref(false)
const open = async (row) => {
  resetData()
  originData.value = row
	dialogTitle.value = `${typeObj[row.task_type]}【${row.task_name}】详情`
	source.value = row.task_type

  let restList = row.task_source || []
  if (row.task_type === '新任命' && row.task_source?.length > 1) {
    otherList.value = [row.task_source[0]]
    restList = row.task_source.slice(1)
  }
  list.value = restList.map(k => {
    // parse_flag：0表示已经解析完成， 1表示需要提交执行解析
    if (k.parse_flag === 0) k.disabled = true
    return k
  })

  // 只有一条数据时默认展示原始数据
  if (list.value.length === 1) {
    isDrilling.value = true
	  dealData(list.value[0])
  }

  // 待解析 解析成功 部分解析成功 解析失败
  if (['解析中', '部分解析成功', '解析失败'].includes(row.task_status)) {
    showAnalysisBtn.value = row.task_source.some(e => e.parse_flag.toString() === '1')
  }

  dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

// 查看原始文件
const isDrilling = ref(false)
const handleDetail = (row) => {
	isDrilling.value = true
	dealData(row)
}

// 执行解析
const handleAnlysis = () => {
  const isNoAnalysis = list.value.every(e => e.parse_flag === 0)
  if (isNoAnalysis) return message.warning('请勾选要进行解析的项')

  list.value.forEach(e => delete e.disabled)
  let taskList = list.value || []
  if (originData.value.task_type === '新任命' && otherList.value.length) {
    taskList = [originData.value.task_source[0], ...list.value]
  }
  originData.value.task_source = taskList

  dialogVisible.value = false
  emit('analysis', originData.value)
}
</script>

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