<template>
  <div style="width: 100%;">
    <div class="color-666 mb-3" style="font-size: 13px;">* 仅支持.doc, .docx, .pdf文件</div>
    <CtForm ref="formPageRef" :items="items"></CtForm>
  </div>
</template>

<script setup>
defineOptions({name: 'shareJob-form-upload'})
import { reactive, ref } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { uploadFile } from '@/api/common'
import Snackbar from '@/plugins/snackbar'

const { t }  = useI18n()
const formPageRef = ref()
let query = reactive({})

// 上传简历
const typeList = ['pdf', 'doc', 'docx']
const handleUpload = async (e) => {
  const file = e
  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
  const urlItem = items.value.options.find(e => e.key === 'url')
  if (urlItem) urlItem.data = data
  query.fileName = file.name
}

const items = ref({
  options: [
    // {
    //   type: 'text',
    //   key: 'name',
    //   value: '',
    //   clearable: true,
    //   label: '姓名 *',
    //   rules: [v => !!v || '请填写姓名']
    // },
    // {
    //   type: 'phoneNumber',
    //   key: 'phone',
    //   value: '',
    //   clearable: true,
    //   label: '手机号码 *',
    //   rules: [v => !!v || '请填写手机号码']
    // },
    {
      type: 'upload',
      key: 'url',
      value: null,
      data: '',
      label: '简历 *',
      accept: '.doc, .docx, .pdf',
      placeholder: '请上传简历',
      rules: [v => !!v || '请上传简历'],
      change: handleUpload
    }
  ]
})


const getQuery = async () => {
  const { valid } = await formPageRef.value.formRef.validate()
  if (!valid) return
  const obj = {}
  items.value.options.forEach(e => {
    if (Object.prototype.hasOwnProperty.call(e, 'data')) return obj[e.key] = e.data
    obj[e.key] = e.value
  })
  query = Object.assign(query, obj)
  return query
}

defineExpose({
  getQuery
})
</script>