import config from './config'
import Qs from 'qs'
let arr = []
export default (options = {}) => {
    if (options.data == undefined) {
        options.data = {}
    }
    options.debounce = options.debounce === undefined ? true : options.debounce
    // 防止接口重复点击
    if (options.debounce) {
        if (arr.indexOf(options.url) === -1) {
            arr.push(options.url)
        } else {
            return new Promise((resolve, reject) => {
                reject({
                    code: -1,
                    msg: '请勿重复提交',
                    data: options.url,
                })
            })
        }
    }
    return new Promise((reslove, reject) => {
        let url = options.url.indexOf('http') === -1 ? config.domain + options.url : options.url
        if (options.params) {
            url = url + '?' + Qs.stringify(options.params)
        }
        uni.request({
            url,
            timeout: 1000 * 60,
            data: {
                ...options.data,
            },
            header: {
                // 'Content-Type': 'application/json;charset=UTF-8',
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                Authorization: uni.getStorageSync('access_token'),
                ...options.header,
            },
            method: options.method || 'GET',
            success: async (res) => {
                // console.log(res)
                if (arr.indexOf(options.url) > -1) {
                    setTimeout(() => {
                        arr.splice(arr.indexOf(options.url), 1)
                    }, 500)
                }
                if (res.data.resultCode !== 10000 && res.data.code !== 'A0000') {
                    errHandler(res.data)
                    reject(res.data)
                } else {
                    reslove(res.data)
                }
            },
            fail: (err) => {
                if (arr.indexOf(options.url) > -1) {
                    setTimeout(() => {
                        arr.splice(arr.indexOf(options.url), 1)
                    }, 500)
                }
                reject(err)
                uni.showToast({
                    icon: 'none',
                    title: '网络异常，请稍后再试',
                })
            },
        })
    })
}

/**
 * 错误处理
 * @param {Number} code 错误码
 */
function errHandler(res) {
    console.log(res)
    switch (res.code) {
        case 'A0024':
            uni.reLaunch({ url: '/pages/user/login' })
            break
        case 'A0202':
            uni.reLaunch({ url: '/pages/user/login' })
            break
        default:
            uni.showToast({
                title:
                    res.message.substring(res.message.indexOf(',') + 1) ||
                    res.msg.substring(msg.indexOf(',') + 1) ||
                    '网络异常，请稍后再试',
                duration: 2000,
                icon: 'none',
            })
            break
    }
}
