import { getOssConfig } from '@/xiaolanbenlib/api/upload'
import Taro from '@tarojs/taro'
import Base64 from './Base64'
import Crypto from './crypto'
import './hmac'
import './sha1'

// Environment configuration for OSS
interface EnvConfig {
  AccessKeySecret: string
  OSSAccessKeyId: string
  timeout: number
}

const env: EnvConfig = {
  AccessKeySecret: '填你自己的AccessKeySecret',
  OSSAccessKeyId: '填你自己的 OSSAccessKeyId',
  timeout: 87600, // This is the expiration time of the upload policy
}

// Function to get the base64-encoded policy
const getPolicyBase64 = (): string => {
  const date = new Date()
  date.setHours(date.getHours() + env.timeout)
  const expirationTime = date.toISOString()

  const policyText = {
    expiration: expirationTime, // Policy expiration time
    conditions: [
      ['content-length-range', 0, 1024 * 1024 * 1024], // File size limit: 1GB
    ],
  }

  return Base64.encode(JSON.stringify(policyText))
}

// Function to get the signature for the policy
const getSignature = (
  accessKeySecret: string,
  policyBase64: string,
): string => {
  const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accessKeySecret, {
    asBytes: true,
  })
  return Crypto.util.bytesToBase64(bytes)
}

// Type definition for the callback
type UploadCallback = (result: { url: string }) => void

// Function to upload a file to Aliyun OSS
export default function uploadFileToAlioss(
  params: Record<string, unknown>,
  file: { path: string },
  cb?: UploadCallback,
): Promise<{ url: string }> {
  return new Promise(async (resolve, reject) => {
    const pathArr = file.path.split('.')

    if (pathArr.length > 1) {
      try {
        Taro.showLoading({
          title: '上传中',
        })
        // Get OSS configuration
        const config = await getOssConfig({ extension: pathArr.pop() })

        const policyBase64 = getPolicyBase64()

        const uploadTask = Taro.uploadFile({
          url: 'https://visitingcard.oss-cn-hangzhou.aliyuncs.com',
          filePath: file.path,
          name: 'file',
          formData: {
            key: config.fullPath,
            policy: policyBase64,
            OSSAccessKeyId: config.accessKeyId,
            signature: getSignature(config.accessKeySecret, policyBase64),
            success_action_status: '200',
            'x-oss-security-token': config.securityToken,
          },
          success() {
            const fileUrl = `https://visitingcard.xiaolanben.com/${config.fullPath}`
            console.log(fileUrl)
            cb?.({ url: fileUrl })
            resolve({ url: fileUrl })
          },
          fail(err) {
            Taro.showToast({
              title: (err && err.errMsg) || '上传失败',
              icon: 'none',
              duration: 1500,
            })
            console.log(err)
            reject(err)
          },
          complete() {
            Taro.hideLoading()
          },
        })

        uploadTask.progress((res) => {
          Taro.showLoading({
            title: `已上传 ${res.progress}%`,
          })
        })
      } catch (error) {
        Taro.showToast({
          title: '上传失败1',
          icon: 'none',
          duration: 1500,
        })
        console.error(error)
        reject(error)
      }
    } else {
      Taro.showToast({
        title: '无法上传',
        icon: 'none',
        duration: 1500,
      })
      reject('无法上传')
    }
  })
}
