import Taro from '@tarojs/taro'
import Tip from '../utils/tip'
import { reloadlogin } from '../api/user'
import { errorKey, errorCode, baseUrl as BASEURL } from './config'

type paramsType = {
    baseUrl?: string,
    url: string,
    method?: "OPTIONS" | "GET" | "HEAD" | "POST" | "PUT" | "DELETE" | "TRACE" | "CONNECT",
    data?: Record<string, any>,
    header?: Record<string, any>,
    timeout?: number,
    responseType?: "text" | "arraybuffer"
}

// 错误处理
const errorHandle = (statusCode: number, code: number,  message: string, url: string, params: paramsType) => {
    console.log(message, 'code');
    if (code === errorCode) {
        // 请求很不错
    } else if (code === 403) {

    }
    else if (statusCode !== 200) {
        Tip.toast('啊哦, 您的网络出了一点小问题')
        throw new Error(`${url} ---> 接口请求失败`)
    }  else if (code !== errorCode) {
        Tip.toast(message)
        throw new Error(`${url} ---> 接口请求失败`)
    }
}


// 请求

export type responseType = {
    readonly [key: string]: any
}

// Promise< responseType | responseType[]>

export const request =  (params: paramsType): Promise<any> => {
    
    const { baseUrl, url, method, data, header, timeout, responseType} = params
    return new Promise( async resolve => {
        const result = await Taro.request({
            url: (baseUrl || BASEURL) + url,
            method: method || 'GET',
            data,
            header: {
                'Content-Type': 'application/json',
                token: Taro.getStorageSync('token'),
                ...header
            },
            timeout,
            responseType
        });
        
        // eslint-disable-next-line no-shadow
        const { statusCode  } = result
        const { msg, data: Data } = result.data
    
        errorHandle (statusCode, result.data[errorKey], msg, (baseUrl || BASEURL) + url, params)

        if (result.data.status === 403) {
          // token失效, 刷新token， 并重发请求
          console.log('????');
            Tip.loading()
            Taro.login({
                success: res => {
                    console.log(res);
                    const { code: Code } = res
                    reloadlogin(Code).then ( async _ => {
                        Taro.setStorageSync('token', _.id)
                        resolve(await request(params))
                    })
                }
            })
            Tip.loaded()

            return 
        }

        resolve(Data)
    }).catch( e => e) 


    // return Data
    
}

 