<template>
  <div class="resume-box" style="position: relative; height: 100%;">
    <div class="resume-header">
      <div class="resume-title">{{ props.analysis ? '解析简历附件生成在线简历' : '附件简历'}}</div>
      <v-btn variant="text" color="primary" prepend-icon="mdi-plus-box" @click="handleAdd">{{ props.analysis ? '上传新的简历' : '上传'}}</v-btn>
    </div>
    <p class="font-size-14 color-999">最多只能上传5份附件简历</p>
    <div v-if="attachmentList.length" class="mt-5">
      <div
        :class="['position-item', 'mx-n2', 'px-2']" 
        v-for="(k, i) in attachmentList" 
        :key="i" 
        @mouseenter="k.active = true" 
        @mouseleave="k.active = false"
        @click.self="checkboxClick(i, !k.choose)"
      >
        <div class="d-flex">
          <v-checkbox-btn v-if="props.analysis" v-model="k.choose" color="primary" class="pe-2" @update:modelValue="bool => checkboxClick(i, bool)"></v-checkbox-btn>
          <span @click="checkboxClick(i, !k.choose)">{{ k.title }}</span>
        </div>
        <div class="float-right" v-if="k.active">
          <v-btn variant="text" color="primary" prepend-icon="mdi-eye-outline" @click="previewFile(k.url)">预览</v-btn>
          <v-btn variant="text" color="primary" prepend-icon="mdi-arrow-down-bold-outline" @click="handleDownload(k)">下载</v-btn>
          <v-btn variant="text" color="primary" prepend-icon="mdi-trash-can-outline" @click="handleDelete(k)">{{ $t('common.delete') }}</v-btn>
        </div>
      </div>
      <div v-if="props.analysis" class="d-flex  flex-column align-center mt-15">
        <v-btn class="buttons" color="primary" @click="handleAnalysis">开始解析</v-btn>
        <v-btn class="mt-2" variant="text" color="primary" to="/recruit/personal/personalCenter/resume/online">返回在线简历</v-btn>
      </div>
    </div>
    <div v-else class="resumeNoDataText tips">请上传您的附件简历</div>
  </div>

  <CtDialog
    :visible="showUploadDialog"
    :widthType="2"
    :footer="true"
    title="附件简历上传"
    titleClass="text-h6"
    @close="showUploadDialog = false"
    @submit="handleSubmit"
  >
    <CtForm ref="CtFormRef" :items="formItems">
      <template #uploadFile="{ item }">
        <TextInput v-model="item.value" :item="item" @click="openFileInput"></TextInput>
        <File ref="uploadFile" @success="handleUploadResume"></File>
      </template>
    </CtForm>
    <div class="color-666" style="font-size: 13px;">* 仅支持.doc, .docx, .pdf文件且大小不能超过20MB</div>
  </CtDialog>
</template>

<script setup>
defineOptions({ name: 'person-center-resume-annex'})
import { ref } from 'vue'
import Snackbar from '@/plugins/snackbar'
import Confirm from '@/plugins/confirm'
import { useI18n } from '@/hooks/web/useI18n'
import { getPersonResumeCv, deletePersonResumeCv, savePersonResumeCv } from '@/api/recruit/personal/resume'
import { getBlob, saveAs, previewFile } from '@/utils'

const emit = defineEmits(['analysis'])
const props = defineProps({
  analysis: { // 简历解析
    type: Boolean,
    default: false
  }
})

const { t } = useI18n()

const CtFormRef = ref()
const formItems = ref({
  options: [
    {
      type: 'text',
      key: 'title',
      value: '',
      label: '附件简历名称 *',
      rules: [v => !!v || '请输入附件简历名称']
    },
    {
      slotName: 'uploadFile',
      key: 'url',
      value: '',
      truthValue: '',
      label: '点击上传附件简历 *',
      outline: true,
      accept: '.doc, .docx, .pdf',
      prependInnerIcon: 'mdi-file-document-outline',
      rules: [v => !!v || '请上传您的附件简历']
    }
  ]
})

// 获取附件
const attachmentList = ref([])
const getList = async () => {
  const data = await getPersonResumeCv()
  attachmentList.value = data
}
getList()

// 选择文件
const uploadFile = ref()
const openFileInput = () => {
  uploadFile.value.trigger()
}

// 上传附件
const handleUploadResume = async (url, title, filename) => {
  const obj = formItems.value.options.find(e => e.key === 'url')
  obj.value = filename
  obj.truthValue = url
}

const showUploadDialog = ref(false)
const handleAdd = () => {
  if (attachmentList.value.length >= 5) return Snackbar.warning(t('resume.uploadFiveCopies'))
  formItems.value.options.forEach(e => {
    e.value = ''
    e.truthValue = ''
  })
  showUploadDialog.value = true
}

// 上传附件
const handleSubmit = async () => {
  const { valid } = await CtFormRef.value.formRef.validate()
  if (!valid) return
  const obj = {}
  formItems.value.options.forEach(e => {
    obj[e.key] = e.truthValue || e.value
  })
  if (!obj.title || !obj.url) return
  await savePersonResumeCv(obj)
  getList()
  showUploadDialog.value = false
  Snackbar.success(t('common.uploadSucMsg'))
}

// 删除
const handleDelete = ({ id }) => {
  Confirm(t('common.confirmTitle'), t('resume.deleteAttachment')).then(async () => {
    await deletePersonResumeCv(id)
    Snackbar.success(t('common.delMsg'))
    getList()
  })
}

// 下载附件
const handleDownload = (k) => {
  getBlob(k.url).then(blob => {
    saveAs(blob, k.title)
  })
}

const fileUrl = ref('')
const checkboxClick = (i, bool) => {
  if (!props.analysis) return
  let item = null
  attachmentList.value.forEach((e, index) => {
    e.choose = i === index ? bool : false
    if (e.choose) item = e
  })
  if (item?.url) fileUrl.value = encodeURIComponent(item.url)
}

const handleAnalysis = () => {
  if (!fileUrl.value) return Snackbar.warning('请选择要解析的简历附件')
  emit('analysis', fileUrl.value)
}

</script>

<style scoped lang="scss">
.position-item {
  display: flex;
  justify-content: space-between;
  cursor: pointer;
  border-radius: 6px;
  line-height: 40px;
  font-size: 15px;
  &:hover {
    background-color: var(--color-f8);
  }
  span {
    font-size: 15px;
  }
  .grey-text {
    color: var(--color-999);
  }
}
.tips {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
