import { useGlobSetting } from 'hooks/setting/env'
import config from '@/config'
import { ACCESS_TOKEN_KEY } from '@/constants/storage'

export const useUpload = () => {
  const { api, prefix } = config
  const baseURL = api + prefix
  const { clientId } = useGlobSetting()

  const uploadFile = (tempFilePaths, cb) => {
    const [tempFilePath] = tempFilePaths
    const authorization = uni.getStorageSync(ACCESS_TOKEN_KEY)
    uni.uploadFile({
      url: `${baseURL}/resource/oss/upload`,
      filePath: tempFilePath,
      name: 'file',
      formData: {},
      header: {
        Authorization: `Bearer ${authorization}`,
        Clientid: clientId
      },
      success: ({ data }) => {
        let result = {}
        try {
          result = JSON.parse(data)
        } catch (error) {
          result = {}
        }
        if (result.code === 401) {
          uni.$u.toast('登录失效，请登录后重试')
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/views/login/index'
            })
          }, 1500)
        } else {
          cb && cb(result.data)
        }
      }
    })
  }

  return {
    uploadFile
  }
}
