import { BASE_URL, appId } from "../env";
import { base64Encode } from "./crypto";
type RequestProps = {
    options: WechatMiniprogram.RequestOption;
    loadingTitle?: string;
    isLoading?: boolean;
    needLogin?: boolean;
};

// 生成设备指纹字符串
const generateFingerprint = (): string => {
    const info = wx.getSystemInfoSync();
    return [
        String(info.system),
        String(info.platform),
        String(info.SDKVersion),
        String(info.screenWidth),
        String(info.screenHeight),
    ].join("&");
};


export const request = <T = any>(
    { options, loadingTitle = "加载中", isLoading = true, needLogin = true }: RequestProps
): Promise<T> => {
    const app = getApp<IAppOption>();
    const header: any = {
        "X-Fingerprint": generateFingerprint(),
    };
    if (needLogin) {
        if (!app.checkLoginState()) {
            return Promise.reject(new Error('请先登录'));
        }
        const openId = wx.getStorageSync("openId") || "";
        header.Authorization = `Basic ${base64Encode(`${openId}:${appId}`)}`
    }


    return new Promise((resolve, reject) => {
        let showToast = false;
        if (isLoading) {
            wx.showLoading({
                title: loadingTitle,
                mask: true // 防止触摸穿透
            });
        }

        wx.request({
            header,
            method: options.method || "POST",
            ...options,
            url: `${BASE_URL}/api${options.url}`,
            success(res: any) {
                if (res.statusCode == 200) {
                    if (!res.data.code || res.data.code === 200) {
                        resolve(res.data as T);
                    } else if (res.data.code === 401) {
                        wx.showModal({
                            title: "登录提示",
                            content: "请先登录",
                            confirmText: "去登录",
                            success: (options) => {
                                if (options.confirm) {
                                    wx.navigateTo({ url: "/pages/login/login" });
                                }
                            }
                        });
                        reject(res);
                    } else {
                        if (isLoading) {
                            showToast = true;
                            wx.showToast({
                                icon: "none",
                                title: `${res.data.msg ? res.data.msg : res.errMsg}`,
                                duration: 2000,
                            });
                        }
                        reject(res);
                    }
                } else {
                    if (isLoading) {
                        showToast = true;
                        wx.showToast({
                            icon: "none",
                            title: `请求错误：${res.data.msg ? res.data.msg : res.errMsg}`,
                            duration: 2000,
                        });
                    }
                    reject(res);
                }
            },
            fail(err) {
                if (isLoading) {
                    showToast = true;
                    wx.showToast({
                        icon: "none",
                        title: "网络异常，请检查网络",
                        duration: 2000,
                    });
                }
                reject(err);
            },
            complete() {
                if (isLoading && !showToast) {
                    wx.hideLoading();
                }
            },
        });
    });
};