<!-- 简历附件解析 -->
<template>
  <view>
    <!-- 选择简历 -->
    <resume v-if="step === 1" resumeAnalysis @submit="handleResumeAnalysis"></resume>
    <!-- 解析内容-表单 -->
    <view v-if="step === 2 && formLIst?.length" style="padding-bottom: 150rpx;">
      <uni-card v-for="item of formLIst" :key="item.id" :id="item.id">
		    <uni-section :title="item.text" type="line">
          <template v-slot:right>
            <view v-if="item.path !== 'baseInfoEdit'" style="color: #e64340;" @click="del(item)">删除</view>
          </template>
          <avatarEdit v-if="item.path === 'avatarEdit'" ref="componentRef" :id="item.id"  :text="item.text" :data="item.data" />
          <baseInfoEdit v-if="item.path === 'baseInfoEdit'" ref="componentRef" :id="item.id"  :text="item.text" :data="item.data" />
          <advantageEdit v-if="item.path === 'advantageEdit'" ref="componentRef" :id="item.id"  :text="item.text" :data="item.data" />
          <educationEdit v-if="item.path === 'educationEdit'" ref="componentRef" :id="item.id"  :text="item.text" :data="item.data" />
          <workExperienceEdit v-if="item.path === 'workExperienceEdit'" ref="componentRef" :id="item.id"  :text="item.text" :data="item.data" />
          <trainingExperienceEdit v-if="item.path === 'trainingExperienceEdit'" ref="componentRef" :id="item.id"  :text="item.text" :data="item.data" />
        </uni-section>
      </uni-card>
      <!-- 保存 -->
      <view class="bottom-sticky flex-column ss-p-b-25" style="background-color: #fff; z-index: 2000; border-top: 1px solid #eee;">
        <button class="recomm-button" :loading="submitLoading" @click="submit">提交（保存至在线简历）</button>
      </view>
    </view>
    <view v-if="step === 3">
      <view class="tips">加载中...</view>
    </view>
    <view v-if="step === 4">
      <view class="tips">加载失败</view>
    </view>
    <!-- 确认框 -->
    <uni-popup ref="confirmRef" type="dialog">
      <uni-popup-dialog
        type="warn"
        cancelText="取消"
        confirmText="确认" 
        title="系统提示"
        :showClose="showClose"
        :content="dialogContent"
        @confirm="handleConfirm"
        @close="null"
      ></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script setup>
import { saveResumeInfo, resumeParser2 } from '@/api/user'
// import { envObj, baseUrl } from '@/utils/config'
import resume from '../resume/index.vue'
import { ref, shallowRef } from 'vue'
import avatarEdit from './components/avatarEdit.vue'
import baseInfoEdit from './components/baseInfoEdit.vue'
import advantageEdit from './components/advantage.vue'
import educationEdit from './components/educationExp.vue'
import workExperienceEdit from './components/workExperience.vue'
import trainingExperienceEdit from './components/trainingExperience.vue'
import { resumeParser2Data } from './testData.js'

const step = ref(1)

const exampleList = {
  avatar: { text: '头像', id: 'avatar', path: 'avatarEdit' },
  person: { text: '基础信息', id: 'person', path: 'baseInfoEdit' },
  advantage: { text: '个人优势', id: 'advantage', path: 'advantageEdit' },
  eduList: { text: '教育经历', id: 'eduList', path: 'educationEdit' },
  workList: { text: '工作经历', id: 'workList', path: 'workExperienceEdit' },
  trainList: { text: '培训经历', id: 'trainList', path: 'trainingExperienceEdit' },
}

const resumeTxt = ref([]) // 查看文本信息
const formLIst = shallowRef([])
const transformToLIst = async (result) => {
  formLIst.value = []
  if (result && Object.keys(result)) {
    if (result.resume?.rawText) resumeTxt.value = result.resume.rawText.split('\n') || []
    if (result.person?.advantage) result.advantage = result.person.advantage
    if (result.person?.avatar) result.avatar = result.person.avatar
    // obj
    const dealObjKeys = ['avatar', 'person', 'advantage']
    dealObjKeys.forEach(key => {
      if (result[key]) {
        const obj = {...exampleList[key]}
        obj.data = result[key]
        formLIst.value.push(obj)
      }
    })
    // arr
    const dealArrKeys = ['eduList', 'workList', 'trainList']
    dealArrKeys.forEach(key => {
      if (result[key]?.length) {
        for (let index = 0; index < result[key].length; index++) {
          const obj = {...exampleList[key]}
          obj.id = obj.id + '_' + index
          obj.text = result[key].length > 1 ? obj.text + (index+1) : obj.text
          obj.data = result[key][index]
          formLIst.value.push(obj)
        }
      }
    })
  }
  // console.log('formLIst:', formLIst.value)
}

const confirmRef = ref()
const dialogContent = ref('')
const showClose = ref(true)
let delId = null
let dialogType = 'del'

const del = (item) => {
  dialogContent.value = `是否确认删除${item.text}？`
  delId = item.id
  dialogType = 'del'
  showClose.value = true
  confirmRef.value.open()
}

const handleConfirm = () => {
  if (dialogType === 'del') {
    formLIst.value = formLIst.value.filter(e => e.id !== delId)
  }
  if (dialogType === 'submitSuccess') {
    uni.navigateTo({ url: '/pagesA/resumeOnline/index' })
  }
}

// const result = ref(JSON.parse(JSON.stringify(data))) // 测试
// transformToLIst(result.value) // 测试

const result = ref({})
const loading = ref(false)
const handleAnalysis = async (url) => {
  url = decodeURIComponent(url)
  if (!url) return
  loading.value = true
  step.value = 3
  try {
    // const res = await resumeParser2({ fileUrl: url })
    // result.value = res?.data || {}
    result.value = resumeParser2Data
    await transformToLIst(result.value)
    step.value = 2
  } catch (error) {
    step.value = 4
    console.log(error)
  } finally {
    loading.value = false
  }
}

const handleResumeAnalysis = (url) => {
  if (!url) {
    return uni.showToast({ icon: 'none', title: '请选择要解析的简历' })
  }
  handleAnalysis(url)
}

const componentRef = ref()
const getValue = async () => {
  let text = ''
  let data = {}
  for (let index = 0; index < componentRef.value.length; index++) {
    const e = componentRef.value[index]
    const query = await e.submit()
    if (query && query.data) {
      data[query.id] = query.data
    } else {
      if (!text) text = query.text
    }
  }
  if (text) {
    uni.showToast({ icon: 'none', title: `请完整填写 ${text} 后提交！` })
    return
  }
  // 处理data
  let obj = Object.keys(data).length ? {} : null
  const keyTransform = { // 转换给后端的key
    eduList: 'eduExp',
    workList: 'workExp',
    trainList: 'trainExp',
  }
  if (obj) {
    Object.keys(data).forEach(key => {
      if (key.includes('_')) { // 数组
        const oldKey = key.split('_')[0]
        const newKey = keyTransform[oldKey] ? keyTransform[oldKey] : oldKey
        if (!obj[newKey]) obj[newKey] = [data[key]]
        else obj[newKey].push(data[key])
      } else {
        const newKey = keyTransform[key] ? keyTransform[key] : key
        obj[newKey] = data[key]
      }
    })
  }
  console.log('123456:', obj)
  return obj && Object.keys(obj).length ? JSON.stringify(obj) : null
}

const submitLoading = ref(false)
const submit = async () => {
  const obj = await getValue()
  if (!obj) return
  submitLoading.value = true
  await saveResumeInfo(obj)
  dialogType = 'submitSuccess'
  dialogContent.value = '提交成功，立即前往在线简历查看'
  showClose.value = false
  confirmRef.value.open()
  // await useUserStore().getUserBaseInfos() // 更新用户信息
}

</script>
<style lang="scss" scoped>
.tips {
  text-align: center;
  margin-top: 50px;
  color: #777;
}
</style>
