import {body, get} from "@/utils/https";

// const _tokenQueue: {
//     pending: boolean;
//     list: {
//         resolve: (value: string) => void;
//         reject: (err: any) => void;
//     }[];
// } = {
//     pending: false,
//     list: [],
// };
//
// let _onTokenListener: {
//     cb: (token: string) => void;
// }[] = [];
//
// const _resolveTokenQueue = function (res: any) {
//     _tokenQueue.pending = false;
//     uni.hideLoading();
//     if (res.errMsg) {
//         console.log(res);
//         uni.showModal({
//             title: "登录失败",
//             content: `${res.errMsg}`,
//         });
//         _tokenQueue.list.forEach((item) => {
//             item.reject(res);
//         });
//     } else {
//         uni.showToast({
//             icon: "success",
//             title: "登录成功",
//         });
//         setToken(res as string);
//         _onTokenListener.forEach((item) => {
//             item.cb(res as string);
//         });
//         _tokenQueue.list.forEach((item) => {
//             item.resolve(res as string);
//         });
//     }
//     _onTokenListener = [];
//     _tokenQueue.list = [];
// };

export function login(e: any): Promise<string> {
    return new Promise((resolve, reject) => {
        if (/deny|cancel/.test(e.errMsg)) {
            reject(e.errMsg);
            return;
        }
        if (!e.code) {
            uni.showModal({
                title: `${e.errMsg},请重试`,
            });
            reject(e);
            return;
        }
        // _tokenQueue.list.push({
        //     resolve,
        //     reject,
        // });
        // if (_tokenQueue.pending) {
        //     return;
        // }
        // _tokenQueue.pending = true;
        uni.showLoading({
            title: "登录中",
            mask: true,
        });
        uni.login({
            success: (res) => {
                let data = {
                    phoneCode: e.code,
                    code: res.code,
                    avatar: "",
                    nickname: "",
                    shortId: e.shortId
                }
                body(`/user/wxLogin`, data).then(async (res: any) => {
                    let {satoken, userId} = res;
                    if (satoken) {
                        getApp<any>().globalData.user={
                            id : userId
                        }
                        // _resolveTokenQueue(satoken);
                        setToken(satoken);
                        await loadUserInfo();
                        resolve(satoken)
                        uni.hideLoading();
                    } else {
                        uni.showModal({
                            title: `登录失败`,
                            icon: 'none',
                            duration: 2000
                        });
                        uni.hideLoading();
                        // _resolveTokenQueue({
                        //     errMsg: `${JSON.stringify(res)}`,
                        // });
                    }
                }).catch(e => {
                    uni.showModal({
                        title: `${e}`,
                        icon: 'none',
                        duration: 2000
                    });
                    uni.hideLoading();
                })
            },
            fail: () => {
                uni.showModal({
                    title: `登录失败`,
                    icon: 'none',
                    duration: 2000
                });
                uni.hideLoading();
            },
        });
    });
}

export function tryLogin() {
    return new Promise(((resolve, reject) => {
        let ftoken = fetchToken();
        // console.log("ftoken", ftoken)
        if (ftoken) {
            resolve(ftoken)
            return;
        }
        uni.showLoading()
        uni.login({
            success: (res) => {
                let data = {
                    phoneCode: "",
                    code: res.code,
                    avatar: "",
                    nickname: "",
                }
                body(`/user/wxLogin`, data).then(async (res: any) => {
                    const {satoken, userId} = res;
                    if (satoken) {
                        getApp<any>().globalData.user={
                            id: userId
                        }
                        setToken(satoken);
                        await loadUserInfo();
                        resolve(satoken)
                    } else {
                        reject('fail')
                        getApp<any>().globalData.user =null;
                    }
                    uni.hideLoading()
                }).catch(e => {
                    console.error("tryLogin",e)
                    getApp<any>().globalData.user =null;
                    reject(e)
                    uni.hideLoading()
                })
            },
            fail: function () {
                reject('fail')
                uni.hideLoading()
            },
        });
    }))
}


export function checkLogin() {
    return new Promise((resolve, reject) => {
        let user = getApp<any>().globalData.user;
        if (!user || !user.id) {
            uni.showToast({
                icon: "none",
                title: "请先登录",
            });
            reject('未获取到用户登录信息');
        } else {
            resolve(user);
        }
    })
}

export async function loadUserInfo() {
    getApp<any>().globalData.manualLogout = false;
    return new Promise(async (resolve, reject) => {
        let res = await get(`/user/me`);
        getApp<any>().globalData = Object.assign({}, {...getApp<any>().globalData}, {user: res, isLogin: true, manualLogout: false})
        uni.$emit('login', {isLogin: true})
        resolve(res)
    })

}

export function refresh(): Promise<string> {
    return new Promise((resolve, reject) => {
        uni.getStorage({key: "token"}).then((token) => {
            if (!token) {
                clearToken();
                reject({
                    errMsg: "请登录",
                });
                uni.reLaunch({
                    url: "/pages/map/index",
                });
            } else {
                getApp<any>().globalData.token = "";
                uni.removeStorageSync("token");
                get(`/user/refresh`).then((res: any) => {
                    const {statusCode, data} = res;
                    if (
                        statusCode === 200 &&
                        data &&
                        data.msg === "OK" &&
                        data.code === 200
                    ) {
                        resolve(data.data.access_token);
                    } else {
                        if (data.code === 21005) {
                            uni.reLaunch({
                                url: "/pages/map/index",
                            });
                        }
                        reject({
                            errMsg: `${JSON.stringify(res)}`,
                        });
                    }
                }).catch(() => {
                    reject()
                })
            }
        });
    });
}


export function fetchToken() {
    let tk = uni.getStorageSync("token");
    // console.log(tk)
    if (tk.length > 16) {
        return tk;
    }
    return null;
}

export function setToken(token: string) {
    if (!token) {
        console.error("empty token")
        return;
    }
    getApp<any>().globalData = Object.assign({}, {...getApp<any>().globalData}, {token, isLogin: true})
    uni.setStorageSync("token", token)
}

export function clearToken() {
    let device = uni.getWindowInfo();
    let initGlobalData = {
        token: "",
        user: {},
        isLogin: false,
        last: {},
        device: {
            windowWidth: device.windowWidth,
            windowHeight: device.windowHeight,
            screenTop: device.screenTop,
            windowTop: device.windowTop,
        },
        deviceId: null,
        manualLogout: false
    }
    uni.$emit('logout')
    uni.removeStorageSync("token")
    getApp<any>().globalData = Object.assign({}, initGlobalData)
}
