import { noEmpty } from '@utils'
const Http = (options = { data: {} }) => {
  return new Promise((resolve, reject) => {
    if (options.loadingStr === 'loading') {
      uni.showLoading({
        mask: true,
        title: '加载中..'
      })
    }
		let token = uni.getStorageSync('MD_token') || ''
    let header = {
      'Content-Type': 'application/json',
			'token': token,
      // 'Content-Type': 'application/x-www-form-urlencoded'
    }
    let params = {...options.data}
    if (uni.getStorageSync('APP_token')) params.token = uni.getStorageSync('APP_token')
    for (let key in options.data) {
      if (options.data[key] === undefined || options.data[key] === 'undefined') {
        params[key] = ''
      }
    }
		let url = uni.baseUrl + options.url
		// let url = options.url
		if (options.queryData) {
			let qStr = ''
			for(let k in options.queryData) {
				qStr += `${k}=${options.queryData[k]}&`
			}
			qStr = qStr.substr(0, qStr.length - 1)
			url += `?${qStr}`
		}
    uni.request({
			url,
			data: {
				...params
			},
			header,
			method: options.method || 'POST',
			complete: res => {
				if (options.loadingStr === 'loading') {
					uni.hideLoading()
				}
			},
			success: res => {
				const { data: cData } = res
				const code = cData.errno
				switch (code) {
					case 0:
						return resolve(noEmpty(cData.data) ? cData.data : cData)
						break
					case 401:
					case 404:
					case 405:
					uni.removeStorageSync('MD_userInfo')
					uni.removeStorageSync('MD_token')
					// 差一个补是否绑定微信
						if (uni.getStorageSync('APP_token')) {
							uni.login({
								success: function (res) {
									if (res.code) {
										uni.api.base.apiwxautologin({code: res.code}).then(cData => {
											if (cData.token === 'error') {
												uni.removeStorageSync('APP_token')
											} else {
												uni.setStorageSync('APP_userInfo', cData)
												uni.setStorageSync('APP_token', cData.token)
											}
										})
									}
								}
							})
						} else {
							uni.showToast({
								title: `请先登录~`,
								icon: 'none',
							})
						}
						uni.navigateTo({
							url: '/pages/user/login/login'
						})
					  break
					default:
						uni.showModal({
							title: '提示',
							content: `${cData.errmsg}(${code})`,
						})
						return reject(cData)
				}
				// resolve()
			},
			fail: err =>  {
				console.log(err)
				reject(err)
			}
		})
  })
}
// export default Http

function request (url, data, loadingStr, queryData) {
  return Http({
    url,
    data,
    loadingStr,
    queryData,
  })
}
export {
  request,
}