import config from "@/config/config.js";
import CryptoJS from "crypto-js";
// 带 Token 请求
const httpTokenRequest = (opts) => {
    uni.onNetworkStatusChange(function(res) {
        if (!res.isConnected) {
            uni.showToast({
                title: '网络连接不可用！',
                icon: 'none'
            });
        }
        return false
    });

    let keyStr = randomString(32,'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
    let ivStr = '8Z2wMy7amABbqsRC';
    let str = keyStr +'/' + new Date().getTime();
    let token = encrypt(str, keyStr, ivStr)

    if (token === '' || token === undefined) {
        uni.reLaunch({
            url: '/pages/login/index'
        });
    } else {
        let httpDefaultOpts = {
            url: config.baseUrl + opts.url,
            data: opts.data,
            method: opts.method || 'GET',
            header: opts.method === 'get' ? {
				'tenantId':2,
                'key':keyStr,
                'X-Access-Token':  token,
                'X-Requested-With': 'XMLHttpRequest',
                "Accept": "application/json",
                "Content-Type": "application/json; charset=UTF-8"
            } : {
				'tenantId':2,
                'key':keyStr,
                'X-Access-Token': token,
                'X-Requested-With': 'XMLHttpRequest',
                'Content-Type': 'application/json; charset=UTF-8'
            },
            dataType: 'json',
        }
        let promise = new Promise(function(resolve, reject) {
            uni.request(httpDefaultOpts).then(
                (res) => {
                    if (res.statusCode == 200) {
                        //默认api接口正常返回0，不正常返回1，并给出错误提示
                        if (res.data.code == 0) {
                            resolve(res)
                        }else{
                            resolve(res)
                            uni.showToast({
                                icon:'none',
                                title:res.data.message
                            })
                        }
                    } else {
                        if (res.statusCode == 401) {
                            uni.showModal({
                                title: '提示',
                                content: '无权访问',
                                success: function (res) {
                                    if (res.confirm) {
                                        uni.reLaunch({
                                            url: '/pages/login/index'
                                        });
                                        uni.clearStorageSync();
                                    }
                                }
                            });
                            uni.clearStorageSync();
                        } else {
                            resolve(res)
                        }
                    }
                }
            ).catch(
                (response) => {
                    reject(response)
                }
            )
        })
        return promise
    }
};

/**
     * 随机字符串
     * @param length
     * @param chars
     * @returns {string}
     */
    const randomString = (length, chars) => {
        var result = '';
        for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
        return result;
    }

    /**
     * 加密
     * @param str
     * @param keyStr
     * @param ivStr
     * @returns {*}
     */
    const encrypt = (str, keyStr, ivStr) => {
        const data = JSON.stringify(str);
        const key = CryptoJS.enc.Utf8.parse(keyStr);   // 密钥key   后台提供 - cbc模式 32位字符
        const iv = CryptoJS.enc.Utf8.parse(ivStr);   // iv   后台提供 - cbc模式 16位字符

        const encryptedData = CryptoJS.AES.encrypt(data, key, {
            iv,
            mode: CryptoJS.mode.CBC, // 使用 CBC 模式
            padding: CryptoJS.pad.Pkcs7, // 使用 PKCS7 填充
        }).toString(); // 执行加密操作

        return encryptedData;
    }

// 导出去
export default httpTokenRequest;
