import { logoutSuccess } from "@/store/user";
import Taro from "@tarojs/taro";
import { useDispatch } from "react-redux";


interface RequestParam {
    url: string;
    method: 'POST' | 'GET' | 'DELETE' | 'PUT';
    data?: Record<string, any>;
    showAlert?: boolean;
}

interface Resp {
    statusCode?: number;
    header?: any;
    data?: any;
    errMsg?: string;
};

async function getStorage(key: string) {
    try {
        const res = await Taro.getStorage({ key });
        return res.data;
    } catch {
        return '';
    }
}

//X-Language:语言，X-Device-Id:设备唯一码，X-Platform:小程序/android/ios,X-Location:地区，X-Device:登录设备
// header['X-Language'] = ''
// header['X-Device-Id'] = ''
// header['X-Platform'] = ''
// header['X-Location'] = ''
// header['X-Device'] = ''
// header['X-Time-Zone-Id'] = Intl.DateTimeFormat().resolvedOptions().timeZone
// header['Authorization'] = 'Bearer ' + wx.getStorageSync('token');
// header['Authorization'] = 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJhY2NvdW50Iiwic3ViIjoiMmQ5OWNlYzI0ZDFlMzE0Y2U1MjhlODM4MWMzYzk0MzgiLCJpc3MiOiJDT0RFUEFBUy5DT00iLCJuaWNrbmFtZSI6IueOi-a4nSIsInR5cCI6IkJlYXJlciIsInNlc3Npb25fc3RhdGUiOiIyN2RjNmU4ZDdjMWU1MTVmNDQwNzVjZTFlODk2ZmUzNCIsImV4cCI6MTcxNjY0Mzk5MSwiaWF0IjoxNjg1MDIxNTkxfQ.fmFj0OVNRzjLkdebSyGJyk8EScPJFpDiz0L25W35zoA'


export async function request<T>(param: RequestParam): Promise<T> {
    const { url, method, data } = param;
    let header: any = {};

    const token = global.token ? global.token : ''; //await getStorage('token')

    var split = new Date().toString().split(' ');
    var timeZoneFormatted = split[split.length - 2];

    header['X-Time-Zone'] = timeZoneFormatted; //new Date().getTimezoneOffset() / 60
    if (token.length > 0) {
        header['Authorization'] = `Bearer ${token}`;
    }

    const kTimeout = 5000;
    const kRetryCount = 3;
    return new Promise<T>((resolve, reject,complete?:any) => {
        const requestWithRetry = (retryCount: number) => {
            Taro.request({
                url: url,
                method: method,
                header: header,
                timeout: kTimeout,
                data: data || {},
                success: (response: Resp | { [key: string]: any }) => {
                    const { statusCode, data } = response;
                    
                    if (statusCode >= 200 && statusCode < 300) {
                        //正常数据返回
                        var resp = {} as T;
                        if (response.data) {
                            resp = response.data as T;
                        }
                        resolve(resp);

                    } else if (statusCode == 401) {
                        //未登录或挤下线处理
                        global.dispatch(logoutSuccess());
                    } else if (statusCode == 500 && response.data.error_code == 'WX_STEP_PARSE_FAIL') {
                        //单独对计步第一次请求失败处理
                        resolve(response.data);
                    } else {
                        //通用错误处理
                        Taro.showToast({
                            icon: 'none',
                            title: data.error_message,
                        });
                        reject(data);
                    }
                },
                fail: err => {
                    //超时、无网等情况的处理
                    if (err) {
                        if (retryCount < kRetryCount) {
                            // Retry the request
                            console.log(`Retrying request (${retryCount + 1}/3)...`);
                            requestWithRetry(retryCount + 1);
                            return;
                        }
                    }
                    reject(err);
                },
                complete: () => { 
                    complete && complete()
                    // console.log('complete');
                },
            });
        };

        requestWithRetry(0);
    });
}
