import {errInfo} from './err'
import {updToken} from './updateToken'

// 请求方式配置
// https://lifetest.ysd-bs.com //测试地址
// https://card.ysd-bs.com

// wx8e424dbdc443381f  测试appid
// wxb2e3e8091d9feac3  正式appid
const api 	 = "https://lifetest.ysd-bs.com/api/"  //正式地址
const header = {
	"Accept"	: "application/json"
}
let isToken = true

/**
 * 请求
 * @property {Object} req 
 */

const req = (obj, noToken) => {

	// 检查是否无需要token
	if(noToken != undefined){
		isToken = noToken
	}

	// header
	if(obj.token){
		header.Authorization = obj.token || ''
	} else {
		header.Authorization = wx.getStorageSync("token") || ""
	}

	// 处理请求信息
	return new Promise((resolve, reject) => {
		// 组合header
		obj.header = {
			"Accept"		: "application/json",
			"Authorization"	: wx.getStorageSync("token") || ""
		}

		if(!isToken){
			obj.header.Authorization = ''
		}

		wx.request({
			url		: api + obj.url,
			header	: obj.header || {},
			method	: obj.method || 'GET',
			data	: obj.data   || {},
			success	: res => {
				// 更新token
				if (res.header.Authorization) updToken(res.header.Authorization)
				// 处理信息
				if (res.data.status_code == 200) {
					resolve(res.data)
				} else {
					if (res.data.status_code == 401 || res.data.status_code == 400) {
						reject({
							login	: false,
							codeBeen: false
						})
					}
					errInfo(res.data)
				}
			},
			fail: err => {
				wx.showToast({
					title : err.errMsg,
					icon  : "none"
				})
				reject(err)
			},
			complete(){
				if(!isToken) isToken = true
			}
		})
	})
}

module.exports = {
	req
}
