import dayjs from 'dayjs'
import { ossPolicy } from '@/api/oss'

export const formatDate = (date: any, format = 'YYYY-MM-DD HH:mm') => {
  return dayjs(date).format(format)
}

export const isAbsolutePath = (path: string) => {
  return path.startsWith('http')
}

export const uuid = (len = 16) => {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
  const uuid = []

  if (len) {
    // 如果指定uuid长度,只是取随机的字符,0|x为位运算,能去掉x的小数位,返回整数位
    for (let i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * chars.length)]
  } else {
    let r
    // rfc4122标准要求返回的uuid中,某些位为固定的字符
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
    uuid[14] = '4'

    for (let i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | (Math.random() * 16)
        uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r]
      }
    }
  }

  return uuid.join('')
}

// oss上传
export const ossUpload = (param: any) => {
  const { file } = param

  return ossPolicy()
    .then(async (res: any) => {
      const id = file.uid
      const type = file.type.split('/')[1]
      const ossKey = res.dir + id + '.' + type

      const formData = new FormData()
      formData.append('OSSAccessKeyId', res.accessKeyId)
      formData.append('policy', res.policy)
      formData.append('Signature', res.signature)
      formData.append('success_action_status', '200')
      formData.append('key', ossKey)
      formData.append('name', id + '.' + type)
      formData.append('file', file)

      const data = await fetch(res.host, {
        method: 'post',
        body: formData
      })
      if (data.status == 200) {
        return {
          success: true,
          file: file,
          url: ossKey
        }
      } else {
        return {
          success: false,
          msg: '上传失败'
        }
      }
    })
    .catch((err: any) => {
      return {
        success: false,
        msg: err.message
      }
    })
}
