/*
 * 手太欠
 * 愿这世界都如故事里一样 美好而动人~
*/

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

// 请求方式配置
// https://apitest.siyuankunlun.com //测试地址
// https://api.siyuankunlun.com //正式地址

// wxecf8786d25af47b3  正式appid
// const api 	 = "https://apitest.siyuankunlun.com/api/"
const api 	 = "https://api.siyuankunlun.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 => {
                console.log(err)
				wx.showToast({
					title : err.errMsg,
					icon  : "none"
				})
				reject(err)
			},
			complete(){
				if(!isToken) isToken = true
			}
		})
	})
}


/**
 * 上传
 * @property {Object} upload 
 */

const upload = (obj) => {
	// header
	header.Authorization = wx.getStorageSync("token") || ""
	// 处理上传信息
	return new Promise((resolve, reject) => {
		wx.showLoading({
			title: "上传中..",
			mask: true
		})
		wx.uploadFile({
			url		: api + obj.url,
			header	: header,
			name	: obj.key || "",
			filePath: obj.path || "",
			formData: obj.data || {},
			success	: res=>{
				wx.hideLoading();
				// 处理返回值
				let jsonData = JSON.parse(res.data)
				// 更新token
				if (res.header.Authorization) updToken(res.header.Authorization)
				// 处理信息
				if (jsonData.status_code == 200) {
					resolve(jsonData.data)
				} else {
					if (jsonData.status_code == 401) {
						reject({
							login: false
						})
					}
					errInfo(jsonData)
				}
			},
			fail	: err=>{
				wx.showToast({
					title : err.errMsg,
					icon  : "none"
				})
				reject(err)
			}
		})
	})
}

module.exports = {
	req,
	upload
}
