import store from '../store/index.js';
import router from '../router/router.js'

// 测试环境
const base_url = 'https://sandbox-api-welfare.wasair.com/api.v1/lite'
// 正式环境
// const base_url = 'https://wxlite-api-scm.wasair.com'

export function post (url, params) {
  let newParams = params || {}
  newParams.timeStamp = getTimeMs()
  newParams.appSign = 12
  let postObj = new Promise((resolve, reject) => {
	uni.request({
		url: base_url + url,
		method: 'POST',
		header: headerCom(params),
		data: newParams,
		success(res) {
			if (res.data.code == 301 && params.refreshToken!=='not') {
				tokenSave('')
				router.push('Login')
				return
			}
			
			if(res.data.code == 302) {
				tokenSave(res.data.token)
				post(url, params)
				return
			}
			let result = res.data
			let tempData = {
				"list": [],
				"paginate": {
				            "currentPage": 1,
				            "prePage": 10,
				            "total": 4,
				            "lastPage": 1
				        }
			}
			result.data = result.data || tempData
			resolve(result)
		},
		fail(err) {
			reject(err)
		}
	})  
  })
  return postObj
}

export function get (url, params) {
  let newParams = params || {}
  newParams.timeStamp = getTimeMs()
  newParams.appSign = 12
  let postObj = new Promise((resolve, reject) => {
	uni.request({
		url: base_url + url,
		method: 'GET',
		header: headerCom(params),
		data: newParams,
		success(res) {
			if (res.data.code == 301 && params.refreshToken!=='not') {
				tokenSave('')
				router.push('Login')
				return
			}
			if(res.data.code == 302) {
				tokenSave(res.data.token)
				post(url, params)
				return
			}
			resolve(res.data)
		},
		fail(err) {
			reject(err)
		}
	})  
  })
  return postObj
}

// 请求header信息 paramsAfter:同post函数的paramsAfter
export function headerCom (params) {
	let param = params || {}
    let token = tokenGet(param.resetToken)
    let headers = {'token': token}
    return headers
}

// 获取时间戳--毫秒
function getTimeMs () {
  return new Date().getTime()
}

// 记录token
export function tokenSave (token) {
  let timeMs = getTimeMs()
  let tokenArr = {token: token, timeMs: timeMs}
  try {
      uni.setStorageSync('tokenArr', JSON.stringify(tokenArr));
  } catch (e) {
      console.log('保存token失败', e);
  }
}

// 清除token
function tokeRemove () {
  localStorage.removeItem('tokenArr')
}

// 获取token resetToken: 获取token是否检测重新获取 not:不获取 其它:重新获取
export function tokenGet (resetToken) {
	let token = ''
	let tokenStr = ''
	try{
		tokenStr = uni.getStorageSync('tokenArr');
		let maxTime = 3600 // token最大时间 秒-一个半小时
		if (tokenStr) {
			let tokenArr = JSON.parse(tokenStr)
			token = tokenArr.token
			let diffTimeMs = tokenDiffTIme(tokenStr)
			if (diffTimeMs > maxTime && resetToken!='not') { // 超过规定时间了，重新获取token
			  refreshToken()
			}
		}
	}catch(e){
		console.log('获取token失败', e);
	}
	return token
}

// token距离现在已存活时间-秒
export function tokenDiffTIme (tokenStr) {
  tokenStr = tokenStr
  if (!tokenStr) {
    return 10000000
  }
  let tokenArr = JSON.parse(tokenStr)
  let timeMsNow = getTimeMs()
  let timeMsOld = tokenArr.timeMs // 记录时的时间
  let diffTime = parseInt((timeMsNow - timeMsOld) / 1000) // 已存活时间-秒
  return diffTime
}

// 重新获取token 并记录
export function refreshToken (token) {
	
}

export function uploadImage (image, name, type) {
	// type 100 头像 200 退货 300 商品 其他type
	let header = headerCom()
	let postObj = new Promise((resolve, reject) => {
		uni.uploadFile({
			url: base_url + '/staff/upload',
			header: header,
			filePath: image,
			name:name,
			formData: {'uploadType': 1000},
			success(res) {
				resolve(JSON.parse(res.data))
			},
			fail(err) {
				reject(err)
			}
		})
	})
	return postObj
}

export default {
	post: post,
	get: get,
	uploadImage: uploadImage,
	tokenSave: tokenSave
}
