<template>
  <div>
    <div class="accountBox d-flex mb-3 radius white-bgc flex-column">
      <div class="resume-header ml-3 mt-2">
        <div class="resume-title">{{ $t('points.wallet') }}</div>
      </div>
      <div class="d-flex" v-if="userAccount && Object.keys(userAccount).length">
        <div v-for="val in accountList" :key="val.title" class="accountItem cursor-pointer" @click="router.push({ path: '/recruit/personal/myWallet' })">
          <v-icon color="primary">{{ val.icon }}</v-icon>
          <div class="ml-1">
            <div class="title-text">{{ (userAccount[val.key] || 0) + val.desc }}</div>
            <div class="tip-text">{{ val.title }}</div>
          </div>
        </div>
      </div>
      <div v-else class="text-center font-size-14 mb-3">
        请先登录
      </div>
    </div>

    <div class="resume d-flex">
      <div v-for="val in resumeList" :key="val.title" class="topping white-bgc radius" @click="resumeClick(val)">
        <v-icon color="primary">{{ val.icon }}</v-icon>
        <div class="ml-1">
          <div class="title-text">{{ val.title }}</div>
          <div class="tip-text">{{ val.desc }}</div>
        </div>
      </div>
    </div>
    <div class="attachment white-bgc radius mt-3">
      <div>
        <span class="title">{{ $t('resume.attachmentResume') }}</span>
        <span class="upload--text cursor-pointer" @click="openFileInput">
          {{ $t('common.upload') }}
          <input
            type="file"
            ref="fileInput"
            accept=".pdf, .doc, .docx"
            style="display: none;"
            @change="handleUploadFile"
          />
        </span>
      </div>
      <span class="more-text">{{ $t('resume.uploadUpToFiveCopies') }}</span>
      <div v-if="attachmentList.length">
        <div class="d-flex attachment-item my-2 cursor-pointer" v-for="k in attachmentList" :key="k.id">
          <v-icon color="primary">mdi-file-account</v-icon>
          <div class="file-name ellipsis ml-2">{{ k.title }}</div>
          <v-icon color="primary" @click="previewFile(k.url)">mdi-eye-outline</v-icon>
          <v-icon class="mx-2" color="primary" @click="handleDownload(k)">mdi-download-box-outline</v-icon>
          <v-icon color="error" @click="handleDelete(k)">mdi-trash-can-outline</v-icon>
        </div>
      </div>
      <div v-else class="more-text d-flex justify-center">暂无简历，请先上传</div>
    </div>
    <v-navigation-drawer
      v-model="showInterviewSchedule"
      style="height: 100vh; overflow: hidden;"
      temporary
      location="right"
      width="300"
    >
      <interviewSchedule :dataList="invitePageList" @handleMore="interviewScheduleMore()"></interviewSchedule>
    </v-navigation-drawer>
  </div>
</template>

<script setup>
defineOptions({ name: 'personal-center-right'})
import { ref } from 'vue'
import { uploadFile } from '@/api/common'
import { previewFile } from '@/utils'
import { useRouter } from 'vue-router'
import { useRoute } from 'vue-router'; const route = useRoute()
import { getPersonResumeCv, savePersonResumeCv, deletePersonResumeCv } from '@/api/recruit/personal/resume'
import { useI18n } from '@/hooks/web/useI18n'
import { useUserStore } from '@/store/user'
import Snackbar from '@/plugins/snackbar'
import Confirm from '@/plugins/confirm'
import interviewSchedule from './../components/interviewSchedule.vue'
import { getUserInterviewInvitePage } from '@/api/recruit/personal/personalCenter'
import { dealDictObjData } from '@/utils/position'

const { t } = useI18n()
const router = useRouter()
const userStore = useUserStore()

const accountList = [
  { icon: 'mdi-currency-cny', title: t('resume.accountWithdrawal'), desc: t('unit.rmb'), key: 'balance' },
  { icon: 'mdi-octagram-outline', title: t('resume.goldCoins'), desc: t('unit.ge'), key: 'point' }
]
let userAccount = ref(JSON.parse(localStorage.getItem('userAccount')) || {}) // 账户信息
userStore.$subscribe((mutation, state) => {
  userAccount.value = state.userAccount || {}
})

const resumeList = ref([
  // { icon: 'mdi-upload', title: t('resume.topResume'), desc: t('resume.increaseMoreExposure') },
  { name: 'refresh', icon: 'mdi-refresh', title: t('resume.refreshResume'), desc: t('resume.enhanceResumeActivity') },
  { name: 'interview', icon: 'mdi-account-multiple-check-outline', title: t('resume.interviewSchedule'), desc: '' },
])
const showInterviewSchedule = ref(false)
const resumeClick = async (val) => {
  if (val.name === 'interview') {
    await getUserInterviewInvitePageList() // 获取最新数据
    showInterviewSchedule.value = true
  }
}

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

// 选择文件
const fileInput = ref()
const clicked = ref(false)
const openFileInput = () => {
  if (attachmentList.value.length >= 5) return Snackbar.warning(t('resume.uploadFiveCopies'))
  if (clicked.value) return
  clicked.value = true
  fileInput.value.click()
  clicked.value = false
}

// 上传附件
const typeList = ['pdf', 'doc', 'docx']
const handleUploadFile = async (e) => {
  const file = e.target.files[0]
  const size = file.size
  if (size / (1024*1024) > 10) {
    Snackbar.warning(t('common.fileSizeExceed'))
    return
  }
  const arr = file.name.split('.')
  if (typeList.indexOf(arr[arr.length - 1]) < 0) {
    Snackbar.warning(t('common.fileFormatIncorrect'))
    return
  }
  const formData = new FormData()
  formData.append('file', file)
  const { data } = await uploadFile(formData)
  if (!data) return
  Snackbar.success(t('common.uploadSucMsg'))
  await savePersonResumeCv({ title: file.name, url: data })
  getList()
}

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

const getBlob = (url) => {
  return new Promise(resolve => {
    const xhr = new XMLHttpRequest()
    xhr.open('GET', url, true)
    xhr.responseType = 'blob'
    xhr.onload = () => {
      if (xhr.status === 200) resolve(xhr.response)
    }
    xhr.send()
  })
}

const saveAs = (blob, filename) => {
  var link = document.createElement('a')
  link.href = window.URL.createObjectURL(blob)
  link.download = filename
  link.click()
}

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

// 面试日程
const invitePageList = ref([])
const getUserInterviewInvitePageList = async () => {
  const res = await getUserInterviewInvitePage()
  invitePageList.value = res?.list.map(e => {
    e.job = { ...e.job, ...dealDictObjData({}, e.job) }
    e.enterprise = { ...e.enterprise, ...dealDictObjData({}, e.enterprise)}
    return e
  }) || []
  // const interview = resumeList.value.find(f => f.name === 'interview')
  // if (interview) interview.desc = '有' + (res?.total || '0') + '个待面试'
}
// getUserInterviewInvitePageList()
const interviewScheduleMore = () => {
  showInterviewSchedule.value = false
  const path = route.path
  router.push({ path, query: { showInterviewScheduleMore: true } })
}
</script>

<style scoped lang="scss">
.radius {
  border-radius: 8px;
}
.title {
  font-weight: 600;
  font-size: 17px;
}
.accountBox {
  width: 100%;
  .accountItem {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 50%;
    height: 80px;
    padding: 0 12px;
    .tip-text {
      font-size: 13px;
      color: var(--color-666);
    }
    .title-text {
      font-weight: 600;
      font-size: 18px;
      &:hover {
        color: var(--v-primary-base);
      }
    }
  }
}
.resume {
  width: 100%;
  .topping {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 50%;
    height: 90px;
    padding: 12px;
    margin-right: 12px;
    cursor: pointer;
    &:nth-child(2n) {
      margin-right: 0;
    }
    .tip-text {
      font-size: 12px;
      color: var(--color-666);
    }
    .title-text {
      font-weight: 600;
      &:hover {
        color: var(--v-primary-base);
      }
    }
  }
}
.attachment {
  padding: 12px;
  .more-text {
    font-size: 12px;
    color: var(--color-666);
    margin-left: 4px;
  }
  .upload--text {
    float: right;
    color: var(--v-primary-base);
    font-size: 12px;
  }
  .last-update {
    font-size: 12px;
    color: var(--color-666);
  }
  .attachment-item {
    color: #555;
    font-size: 14px;
    .file-name {
      width: 230px;
      &:hover {
        color: var(--v-primary-base);
      }
    }
  }
}
</style>
