import Crypto from 'crypto-js'
import {Base64} from 'js-base64'
import {i18n} from "@/locale";

const env = {
    uploadImageUrl: 'https://wendy123.oss-ap-southeast-1.aliyuncs.com/', // 默认存在根目录，可根据需求改
    accessKeySecret: 'TSZOD1jULKPFsNp2zKhAopLe3c3AiH', // accessKeySecret 去你的阿里云上控制台上找
    ossAccessKeyId: 'LTAI5tQq1bSBFCfsbvwX6DqQ', // AccessKeyId 去你的阿里云上控制台上找
    timeout: 87600, // 这个是上传文件时Policy的失效时间
}

const getPolicyBase64 = function (): string {
    const date = new Date()
    date.setHours(date.getHours() + env.timeout)
    const expirationTime = date.toISOString()
    const policyText = {
        expiration: expirationTime, // 设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
        conditions: [
            ['content-length-range', 0, 2000 * 1024 * 1024], // 设置上传文件的大小限制,2G
        ],
    }

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

const getSignature = function (policyBase64: string): string {
    const bytes = Crypto.HmacSHA1(policyBase64, env.accessKeySecret)
    return Crypto.enc.Base64.stringify(bytes)
}

// 上传图片到阿里云oss
const upload = function (filePath: string, suffix = '.png', dir = 'app/image/') {
    return new Promise((resolve, reject) => {
        if (!filePath) {
            return uni.showToast({icon: "none", title: i18n.global.t('common.prompt.picture-wrong-please-try-again')})
        }

        // 图片名字 可以自行定义，这里是采用当前的时间戳 + 150内的随机数来给图片命名的
        const fileKey = dir + new Date().getTime() + Math.floor(Math.random() * 150) + suffix

        const aliyunServerURL = env.uploadImageUrl // OSS地址，需要https
        const policyBase64 = getPolicyBase64()
        const signature = getSignature(policyBase64) // 获取签名

        uni.uploadFile({
            url: aliyunServerURL, // 开发者服务器 url
            filePath: filePath, // 要上传文件资源的路径
            name: 'file', // 必须填file
            timeout: 20000,
            formData: {
                key: fileKey,
                policy: policyBase64,
                OSSAccessKeyId: env.ossAccessKeyId,
                signature: signature,
                success_action_status: '200',
            },
            success: function (res) {
                console.log(res)
                if (res.statusCode !== 200) {
                    reject(new Error('upload error:' + JSON.stringify(res)))
                    return
                }
                resolve(aliyunServerURL + fileKey)
            },
            fail: function (err) {
                console.log(err)
                uni.hideLoading()
                uni.showToast({icon: "none", title: i18n.global.t('common.prompt.up-failed')})
                reject(err)
            },
        })
    })
}

export {upload}
