import store from '@/store'
import config from '@/config/ctms.config.js'
import {
    getToken
} from './auth.js'
import errorCode from './errorCode.json'

import utils from '@/utils/common.js'
const tansParams = utils.tansParams;

const timeout = 10000
const loginPage = config.loginPage
const request = function(param) {
    utils.debug(param);

    //url每次request请求都需要重新组织
    let url = config.apiUrl;
    url = url + config.url_entry + param.url + '.' + config.url_suffix;
    if (param.force_url) {
        url = param.force_url;
    }
    // get请求映射params参数
    if (param.params) {
        url = url + '?' + tansParams(param.params)
        url = url.slice(0, -1)
    }
    // 是否需要设置 token
    const isToken = (param.headers || {}).isToken === false
    config.header = param.headers || {} //TODO,未成功使用
    if (getToken() && !isToken) {
        config.header['Authorization'] = 'hi-ctms-client ' + getToken()
    }

    let postdata = param.data || {};
    postdata.pid = config.pid || 0;

    var user = store.state.user;
    postdata.uid = user.info.id || 0;

    return new Promise((resolve, reject) => {
        uni.request({
            method: param.method || 'GET',
            timeout: param.timeout || timeout,
            url: url,
            data: postdata,
            header: config.header,
            dataType: param.dataType || 'json',
            success: function(res) {
                // utils.debug(res);
                if (res.statusCode === 200) {
                    //请求成功
                    const code = res.data.code || 0
                    //只有0，200这两种状态码可以返回数据，以便下一步操作；其他状态码无法进入到下一步
                    const msg = res.data.msg || errorCode[code] || errorCode['default']
                    switch (code) {
                        default:
                            resolve(false);
                            if (getApp().globalData.config.isDebug) {
                                reject(msg) //调试台显示错误提示
                            }
                            break;
                        case 401:
                            utils.showConfirm('登录状态已过期，您可以继续留在该页面，或者重新登录').then(res => {
                                if (res.confirm) {
                                    store.dispatch('LogOut').then(res => {
                                        uni.reLaunch({
                                            url: loginPage
                                        })
                                    })
                                }
                            })
                            reject('无效的会话，或者会话已过期，请重新登录。')
                            break;
                        case 100:
                        case 101:
                            resolve(false);
                            uni.showToast({
                                title: msg,
                                icon: "error"
                            });
                            break;
                        case 0:
                        case 200:
                            resolve(res.data) //返回的只是数据
                            break;
                    }

                } else if (res.statusCode === 500) {
                    reject('500')
                } else {
                    reject(res.statusCode)
                }
            },
            fail: (error) => {
                let {
                    errMsg
                } = error, message = ""
                if (errMsg == 'request:fail') {
                    message = '云端连接异常'
                } else if (errMsg == 'Network Error') {
                    message = '后端接口连接异常'
                } else if (errMsg.includes('timeout')) {
                    message = '系统接口请求超时'
                } else if (errMsg.includes('Request failed with status code')) {
                    message = '系统接口' + message.substr(message.length - 3) + '异常'
                }
                reject(message)
            }
        })
    })
}

export default request