import Taro from '@tarojs/taro';
import config from '../config/config';
import {
    DelData,
    GetData,
    JWT
} from './storage';

const loginPages = '/pages/login/index';

function RequestError(message, code) {
    this.name = 'RequestError'
    this.message = message || '请求失败'
    this.code = code
}
// 基础请求
// api/user/center_show , get param == contribution , base
export function baseRequest(
    url,
    method = 'GET',
    data = {},
    base = config.api  // https://api.yidongpaidui.com/
) {
    if (config.debug) { // false
        base = config.debugApi
    }
    let jwt = GetData(JWT);
    jwt = typeof jwt === 'string' ? jwt : ''
    let header = {
        'Content-Type': 'application/json',
        'Jwt': `Bearer ${jwt}`,
        'Authorization': 'Bearer ' + jwt
    }

    return Taro.request({
        url: base + url,
        data: data,
        dataType: "json",
        method: method,
        header: header
    }).then(re => {
        if (config.debug) {
            console.log(`1、${method} debug request url is: ${url}\r\n2、request Data : `, data, '\r\n3、request header:', header, '\r\n4、response Data is :', re);
        }
        let msg = '请求失败'
        if (re.statusCode !== 200 || re.data.error.code != 0) {
            msg = re.data.error.message
            if (!!msg) {
                Taro.showModal({
                    "title": "信息提示",
                    showCancel: false,
                    "content": msg,
                    mask: true
                })
            }


            if (re.data.error.code.toString() === '40101') {
                DelData(JWT)
                const current = Taro.getCurrentPages()
                const route = current[0].route
                if (route != 'pages/login/index') {
                    Taro.navigateTo({
                        url: loginPages
                    })
                }
            }

            RequestError.prototype = Object.create(Error.prototype)
            RequestError.prototype.constructor = RequestError
            return null
        }
        return re.data.data
    })
}

// post
export function p(url, data, base) {
    return baseRequest(url, 'POST', data, base)
}

// get
export function g(url, data, base) {
    // api/user/center_show , get param == contribution , base
    return baseRequest(url, 'GET', data, base)
}

// delete
export function d(url, data, base) {
    return baseRequest(url, 'DELETE', data, base)
}

//put
export function put(url, data, base) {
    return baseRequest(url, 'PUT', data, base)
}



// 上传图片
export const upload = async (file) => {
    let base = config.api
    if (config.debug) {
        // base = config.debugApi
    }
    let jwt = GetData(JWT);
    jwt = typeof jwt === 'string' ? jwt : ''
    let header = {
        // 'Jwt': `Bearer ${jwt}`,
        'Authorization': 'Bearer ' + jwt
    }
    try {
        const re = await Taro.uploadFile({
            url: `${base}/files`,
            filePath: file,
            name: 'file',
            header: header,
            fileName: 'file',
            withCredentials: false
        })

        if (re.statusCode == 200) {
            const resp = JSON.parse(re.data)
            if (resp.hasOwnProperty("data")) {
                return resp.data
            }
        }
    } catch {
        Taro.showModal({
            "title": "信息提示",
            showCancel: false,
            "content": "上传失败",
            mask: true
        })
        return null
    }

    RequestError.prototype = Object.create(Error.prototype)
    RequestError.prototype.constructor = RequestError
    return null

}

