
// Create axios instance
import { APP_GAME_APK, BASE_API } from "./config";
import axios from "axios";
import { getHttpMsg, isDebugEnv, localStorageGet } from "@utils/helpers";
import { LOCAL_ACTIVITY_C, LOCAL_SIGN, LOCAL_WHEEL_INVITE_CODE } from "@constants/localkey";
import { toast } from "react-toastify";
import LZString, { compress, compressToEncodedURIComponent, compressToUTF16, decompressFromBase64 } from "lz-string";
import { isStandalone, isTWA } from "@utils/UAUtils";

// axios.defaults.withCredentials = true
const getSign = () => {
    const sign = localStorageGet(LOCAL_SIGN, "");
    return sign;
}
const getC = () => {
    let c = localStorageGet(LOCAL_ACTIVITY_C, "");
    return c;
}
const getComParams = () => {
    let params = {};
    if (global.BFP != null) params.bfp = global.BFP;
    if (global.FF != null) params.ff = global.FF;
    let sign = getSign();
    if (!!sign) params.sign = sign;
    let c = getC();
    if (!!c) params.c = c;
    params._d = global.device;
    params._t = Date.now() + "_" + global.width + "_" + global.height;
    if (isStandalone() || isTWA()) {
        params.pwa = 1;
    }
    let act = localStorageGet(LOCAL_WHEEL_INVITE_CODE);
    if (act != null && act !== "") {
        params.act = act;
    }
    // if (window.navigator&&window.navigator.userAgent){
    //     params.ua=window.navigator.userAgent;
    // }
    return params;
}
const checkResponse = (data) => {
    if (data) {
        //登录失效
        if (data.code === 404) {
            let msg = getHttpMsg(data);
            toast.error(msg, {
                onClose: () => {
                    window.location.replace(window.location.origin)
                }, toastId: "checkResponse"
            });
        }
        else if (data.code === 777) {
            let action = {
                type: "main/updateOpenPay",
                payload: 1,
            }
            setTimeout(() => {
                if (global.dispatch) global.dispatch(action);
            }, 1000)
        }
    }
}
const service = axios.create({
    baseURL: BASE_API,
    withCredentials: true,
    timeout: 10000, // Request timeout
    retry: 2,//重复5次
    retryDelay: 1000,
    compress: !isDebugEnv()
});
//出错重试 retry
const checkRetryRequest = (error) => {
    let config = error.config;
    if (!config || !config.retry) return Promise.reject(error);
    config.__retryCount = config.__retryCount || 0;
    if (config.__retryCount >= config.retry) {
        // Reject with the error
        return Promise.reject(error);
    }
    config.__retryCount += 1;
    // Create new promise to handle exponential backoff
    let backoff = new Promise(function (resolve) {
        setTimeout(function () {
            resolve();
        }, config.retryDelay || 1);
    });

    // Return the promise in which recalls axios to retry the request
    return backoff.then(function () {
        return service(config);
    });
}
// Request intercepter
service.interceptors.request.use(
    config => {
        if (config.compress) {
            let data = config.ori_data;
            if (data == null) data = config.data;
            if (data) {
                let compressData = LZString.compressToBase64(JSON.stringify(data));
                config.data = {
                    lz: compressData
                }
                config.ori_data = data;
            }
            let params = config.ori_params;
            if (params == null) params = config.params;
            if (params) {
                let compressParams = LZString.compressToBase64(JSON.stringify(params));
                config.params = {
                    lz: compressParams
                }
                config.ori_params = params;
            }
        }
        return config;
    },
    error => {
        // Do something with request error
        // console.log(error); // for debug
        Promise.reject(error);
    }
);

// response pre-processing
service.interceptors.response.use(
    response => {
        let data = response.data;
        if (typeof data === "string") {
            data = LZString.decompressFromBase64(data);
            try {
                response.data = JSON.parse(data);
            }
            catch (error) {
                console.log(error);
            }
        }
        let host = window.location.host;
        if (host.startsWith("localhost")) console.log(response.request.responseURL, response.data);
        checkResponse(response.data);
        return response.data;
    },
    error => {
        let message = error.message;
        // console.log(error);
        //重试
        // return Promise.reject(error);
        return checkRetryRequest(error);
    }
);


const get = (params = {}) => {
    if (params.params == null) params.params = {};
    let comParmas = getComParams();
    params.params = Object.assign(params.params, comParmas);
    return service({
        method: 'get',
        ...params
    });
}
const post = (params = {}) => {
    if (params.data == null) params.data = {};
    let comParmas = getComParams();
    params.data = Object.assign(params.data, comParmas);
    console.warn(`post params: ${JSON.stringify(params.data)}  url:${params.url}`)
    return service({
        method: 'post',
        ...params
    });
}
const put = (params = {}) => {
    if (params.data == null) params.data = {};
    let comParmas = getComParams();
    params.data = Object.assign(params.data, comParmas);
    return service({
        method: 'put',
        ...params
    });
}
const adelete = (params = {}) => {
    if (params.data == null) params.data = {};
    let comParmas = getComParams();
    params.data = Object.assign(params.data, comParmas);
    return service({
        method: 'delete',
        ...params
    });
}
const buildQuery = (param) => {
    if (param != null) {
        if (typeof (param) == "string") {

        } else {
            var query = [];
            for (var k in param) {
                let v = param[k];
                if (typeof (v) == "object") v = JSON.stringify(v);
                query.push(k + "=" + escape(v));
            }
            param = query.join("&");
        }
    }

    return param;
}
const getAPKUrl = (apkUrl = null) => {
    let params = getComParams();
    let url = apkUrl == null ? BASE_API + APP_GAME_APK : apkUrl;
    if (!isDebugEnv()) {
        url += "?lz=" + LZString.compressToBase64(JSON.stringify(params));
    }
    else {
        url += "?" + buildQuery(params);
    }
    return url;
}
const Http = {
    get,
    post,
    put,
    delete: adelete,
    getAPKUrl
}
export default Http;
