import Taro from '@tarojs/taro';
import api from './server/index';
import { setApp } from './config';
import bookStore from '@src/store/book'
import { enumDictList, getRechargeTemplate } from './server/index/index';
import indexStore from './store/index'
import { getUserInfo } from './server/wx/login';
import { showLoading, hideLoading, showToast } from './utils/compatibility';
export interface ResData {
    code: number,
    data: any,
    fail: boolean,
    msg: string,
    success: boolean
}
//拦截器
let isOpne = false //弹窗是否开启
// 因没有权限等待的请求
let pendingRequests: any[] = [];
// 请求拦截器
const requestInterceptor = (chain) => {
    // 展示loding弹窗逻辑
    if (app.isLoding && !isOpne) {
        isOpne = true
        showLoading({ title: "加载中..." })
    }
    const requestParams = chain.requestParams;
    requestParams.url = requestParams.url?.match(/^http[s]?:\/\//ig) ? requestParams.url : app.apiUrl + requestParams.url
    // 是登录接口token换成inittoken
    let token = requestParams.url.match(/(\/jsCodeLogin)|(\/appComponent\/list)/ig) ? app.initToken : app.token
    //token验证未通过并且不是init和login接口关闭请求
    if (!app.tokenValid && !requestParams.url.match(/(\/jsCodeLogin)|(\/loginInitialize)|(\/refreshUserInfo)/ig)) {
        // 打印日志或执行一些清理操作
        console.log("Token为验证是否有效，取消请求,并存入待请求列表，授权后重新请求");
        // 存入待请求列表
        pendingRequests.push(chain);
        // 返回一个被拒绝的Promise以中断请求
        return new Promise(() => { });
    }
    //分类列表假如上次请求的频道没变就不再获取
    if (requestParams.url.includes('/app/bookCategory/list')) {
        if (requestParams.data.workDirection === bookStore.oldWorkDirection) {
            log("阻止参数不变获取分类")
            return new Promise(() => { });
        } else {
            //赋值本次的请求
            bookStore.setData({ oldWorkDirection: requestParams.data.workDirection })
        }
    }
    requestParams.header = {
        ...requestParams.header,
        "Token": token
    }
    // 继续请求
    return chain.proceed(requestParams);
};

// 响应拦截器
const responseInterceptor = (chain) => {
    return chain.proceed(chain.requestParams).then(async (response) => {
        const { data } = response;
        let { code } = data
        // 在这里处理返回的数据
        switch (code) {
            case 200:
                // 初始化接口调用登录接口，登录接口存在自己的执行判断
                if (chain.requestParams.url.includes("loginInitialize")) {
                    // 存放初始token和app信息
                    setApp({ initToken: data.data.token, appInfo: data.data.appInfo, payVersion: data.data.appInfo.iosPayment })
                    // 获取个人信息接口先验证登录是否过期,如果没过期放行接口请求，过期将token清除重新登录
                    let userInfo = await getUserInfo()
                    let user: any = null
                    if (!userInfo) {
                        setApp({ token: "" })
                        // 登录
                        user = await api.login()
                    } else {
                        console.log("验证token通过")
                        setApp({ tokenValid: true })
                    }
                    // 获取枚举
                    enumDictList()
                    // 存放user信息到本地
                    Taro.setStorageSync("userInfo", user)
                    // 获取充值模板
                    await getRechargeTemplate()
                    // 判断是否需要隐藏支付
                    if (app.system === "ios") {
                        let iosShowPay = app?.proVersion ? app?.payVersion >= app?.proVersion : false
                        console.log("是ios", iosShowPay)
                        setApp({ iosShowPay })
                        // setApp({ iosShowPay: true })
                    } else {
                        setApp({ iosShowPay: true })
                    }
                    console.log("获取当前APP", app);  // 获取当前小程序版本号,
                    // 设置已登录状态让页面刷新接口
                    indexStore.setData({ isLogin: true })
                    // 检测待请求列表中是否存在请求，存在就执行请求
                    while (pendingRequests.length > 0) {
                        console.log("存在待请求")
                        const pendingChain = pendingRequests.shift();
                        Taro.request(pendingChain.requestParams);
                    }
                }
                break;
            case 300:
                if (app.tokenValid) {
                    log("token过期,重新登录", data)
                    setApp({ token: "",tokenValid:false })
                    await api.loginInit(app.appId)
                    // 重新执行当前请求
                    console.log("登录后重新请求===>")
                    const newRequestParams = chain.requestParams;
                    return Taro.request(newRequestParams).then(newResponse => newResponse.data);
                }
                break;
            default:
                log("未知错误", data)
                showToast({
                    title: data.msg,
                    icon: 'error',
                    duration: 1000
                })
                break;
        }
        //关闭login弹窗
        if (isOpne) {
            isOpne = false
            hideLoading()
        }
        return data;
    });
};
// 添加请求拦截器
Taro.addInterceptor(requestInterceptor);
// 添加响应拦截器
Taro.addInterceptor(responseInterceptor);
