<template>
  <div v-loading="saveLoading">
    <el-row :gutter="10">
      <el-col :span="12">
        <el-tabs type="border-card">
          <el-tab-pane label="简历解析" v-loading="loading">
            <div v-if="fileUrl">
              <div class="text-right m-b-10px">
                <el-button type="primary" @click="handleResetUpload">重新上传简历</el-button>
              </div>
              <IFrame :src="fileUrl" />
            </div>
            <el-upload
              v-else
              ref="uploadRef"
              v-model:file-list="fileList"
              :action="uploadUrl"
              :auto-upload="false"
              :data="data"
              :limit="1"
              :on-change="handleChange"
              :on-error="submitFormError"
              :on-exceed="handleExceed"
              :on-success="submitFormSuccess"
              :http-request="httpRequest"
              accept=".pdf, doc, .docx"
              drag
              style="flex: 1;"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">上传附件， 将文件拖到此处，或 <em>点击上传</em></div>
              <template #tip>
                <div class="el-upload__tip" style="color: red">
                  提示：仅允许导入 pdf、doc、docx 格式文件！
                </div>
              </template>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="人员搜索">
            <Search @detail="handleDetail" />
          </el-tab-pane>
        </el-tabs>
      </el-col>

      <el-col :span="12">
        <div ref="content" :style="{'height': height, 'overflow-y': 'auto'}">
          <el-tabs type="border-card">
            <el-tab-pane label="简历解析内容">
              <Info ref="InfoRef" v-model="result.person" :areaTreeData="areaTreeData" :isEdit="isEdit" />
              <JobIntention v-model="result.person.jobInterestedList" :isEdit="isEdit" @change="handleUpdateJobIntention" />
              <Edu v-model="result.eduList" :isEdit="isEdit"  />
              <Exp v-model="result.workList" :isEdit="isEdit" />
              <Training v-model="result.trainList" :isEdit="isEdit" />
              <div class="text-center m-t-30px">
                <el-affix position="bottom" :offset="20">
                  <el-button @click="push('/menduner/talentMap')" type="warning" plain size="large" class="!w-120px">取 消</el-button>
                  <el-button v-if="id === 'add'" type="primary" @click="handleSave" size="large" class="!w-120px">保 存</el-button>
                </el-affix>
              </div>
            </el-tab-pane>
            <el-tab-pane label="标签">
              <el-card shadow="never">
                <template #header>
                  <CardTitle title="已有标签" />
                </template>
                <Tags v-if="Object.keys(result).length" :data="result?.resume?.skillsObjs" />
              </el-card>
              <!-- <el-card shadow="never" class="m-t-10px">
                <template #header>
                  <CardTitle title="推荐标签" />
                </template>
                <TagsRecommend />
              </el-card> -->
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
defineOptions({ name: 'TalentMapDetail'})
import { useTagsViewStore } from '@/store/modules/tagsView'
import { TalentMap } from '@/api/menduner/system/talentMap'
import { useUpload } from '@/components/UploadFile/src/useUpload'
import { commonApi } from '@/api/menduner/common'
import { Base64 } from 'js-base64'
import { getDict } from '@/hooks/web/useDictionaries'
import DefaultData from './defaultData'
import { cloneDeep } from 'lodash-es';

import Info from './components/info.vue'
import Edu from './components/edu.vue'
import Exp from './components/exp.vue'
import JobIntention from './components/jobIntention.vue'
import Training from './components/training.vue'
import Tags from './components/tags.vue'
import TagsRecommend from './components/tagsRecommend.vue'
import Search from './components/search.vue'

const { push } = useRouter()

const loading = ref(false)
const saveLoading = ref(false)
const result = ref(cloneDeep(DefaultData))
const fileUrl = ref('') // https://minio.menduner.com/dev/person/229988673960153088/attachment/ee3eb21f45e13ede3557a03d18585ed80c5b4212ac5634e3436e309afaa8fe6a.pdf
const uploadRef = ref()
const fileList = ref([])
const data = ref({ path: '' })
const { uploadUrl, httpRequest } = useUpload()

/** 初始化 */
const InfoRef = ref()
const content = ref()
const message = useMessage() // 消息弹窗
const height = ref(0)
const { currentRoute } = useRouter() // 路由
const route = useRoute()
const { id } = route.params
const baseUrl = import.meta.env.VITE_PREVIEW_URL
const isEdit = ref(false)

// 地区树状列表
const areaTreeData = ref([])
const getDictData = async () => {
  const { data } = await getDict('areaTreeData', {}, 'areaTreeData')
  const obj = data.find(e => e.name === '中国')
  const list = obj?.children ? obj.children.map(e =>{
    // 市辖区直接显示区
    const municipality = e.children && e.children.length && e.children[0].name === '市辖区'
    if (municipality && e.children[0].children?.length) e.children = e.children[0].children
    return e
  }) : []
  areaTreeData.value = list.length ? list : []
}
getDictData()

// 获取人才详情
const getTalentMap = async () => {
  loading.value = true
  try {
    const data = await TalentMap.getTalentMapDetails(id)
    if (!data || !Object.keys(data).length) return
    if (data.person?.resumeUrl) {
      fileUrl.value = !data.person?.resumeUrl.includes('.pdf') ?  `${baseUrl}/onlinePreview?url=${encodeURIComponent(Base64.encode(data.person?.resumeUrl))}` : data.person?.resumeUrl
    }
    result.value = data
    result.value.person.interestedAreaIdList = result.value.person.interestedAreaIdList && result.value.person.interestedAreaIdList.length ? result.value.person.interestedAreaIdList.map(e => Number(e)) : []
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  height.value = document.documentElement.clientHeight + 'px'
  if (id && id !== 'add') {
    isEdit.value = true
    await getTalentMap()
  } else result.value = cloneDeep(DefaultData)
})

// 简历解析
const getResumeParser = async (url) => {
  loading.value = true
  try {
    const data = await commonApi.resumeParser({ fileUrl: url })
    result.value = data
    result.value.person.interestedAreaIdList = result.value.person.interestedAreaIdList && result.value.person.interestedAreaIdList.length ? result.value.person.interestedAreaIdList.map(e => Number(e)) : []
  } finally {
    loading.value = false
  }
}

// 文件上传
const handleChange = async (file) => {
  data.value.path = file.name
  unref(uploadRef)?.submit()
  if (!fileList.value.length) return

  const url = fileList.value[0].response.data
  fileUrl.value = !url.includes('.pdf') ?  `${baseUrl}/onlinePreview?url=${encodeURIComponent(Base64.encode(url))}` : url
  await getResumeParser(url)
}

/** 上传错误提示 */
const submitFormError = () => {
  message.error('上传失败，请您重新上传！')
}

/** 文件数超出提示 */
const handleExceed = () => {
  message.error('最多只能上传一个文件！')
}

const submitFormSuccess = () => {
  // 清理
  unref(uploadRef)?.clearFiles()
}

// 重新上传简历
const handleResetUpload = async () => {
  await message.confirm('是否确定重新上传简历？确定后将清空当前信息')
  fileUrl.value = ''
  data.value.path = ''
  fileList.value = []
  result.value = cloneDeep(DefaultData)
}

// 搜索-查看详情
const keyList = ['person', 'eduList', 'workList', 'trainList']
const handleDetail = async (userId) => {
  if (!userId) return message.warning('请先选择人才！')
  try {
    const data = await TalentMap.getTalentMapDetail(userId)
    if (data && data.person && data.person.id) delete data.person.id
    keyList.forEach(key => result.value[key] = data[key])
  } catch {}
}

// 新增人才
const handleSave = async () => {
  if (result.value?.resume) delete result.value.resume
  console.log(result.value, 'result-add')

  // 效验基本信息中必填项是否有填写
  // if (!result.value?.person.name || !result.value.person.phone) {
  //   message.notifyWarning('请将必填项填写完整')
  //   InfoRef.value.formRef.validate()
  //   content.value.scrollTo({ top: 0, behavior: 'smooth' })
  //   return
  // }

  saveLoading.value = true
  try {
    await TalentMap.createTalentMapInfo(result.value)
    message.success('新增成功！')
    result.value = cloneDeep(DefaultData)
    push('/menduner/talentMap')
  } catch (error) {
    console.log(error)
  } finally {
    saveLoading.value = false
  }
}

// 查看详情-编辑求职意向
const handleUpdateJobIntention = async (val, type) => {
  try {
    await TalentMap.updateTalentMapInfo(result.value.person)
    message.success((type === 'add' ? '新增' : type === 'edit' ? '编辑' : '删除') + '成功')
  } catch (error) {
    console.log(error)
  } finally {
    formLoading.value = false
  }
}
</script>
