import MD5 from './md5.js'
import env from '../config/env.js'
const md5key = "3Jr8S1K18rcC1wAfv8"

function getSignUrl(url, data, timestamp) {
	function randomStr20() {
		for (var e = "0123456789abcdef", t = "", n = 0; n < 20; n++) t += e[Math.floor(16 * Math.random())]
		return t
	}
	let nonce = randomStr20()
	let signStr = JSON.stringify(data) + 'nonce' + timestamp + '' + md5key
	const fulUrl = `${ env.apiBase }${ url }`
	return `${ fulUrl }${ fulUrl.indexOf('?') > -1 ? '&' : '?' }sign=${ MD5(signStr) }&nonce=${ nonce }`
}

const $http = (url, data, methods) => {
	return new Promise((reslove, reject) => {
		let timestamp = parseInt(new Date().getTime())
		uni.request({
			url: getSignUrl(url, data, timestamp),
			header: {
				'Content-Type': 'application/json;charset=utf-8',
				'Authorization': uni.getStorageSync('token') && !data.noToken ?
					`Bearer ${uni.getStorageSync('token')}` : '',
				'x-zz-timestamp': timestamp
			},
			data: data || {},
			method: methods,

			success: res => {
				if (res.data && res.data.code === 401) {
					// uni.showToast({
					// 	title: res.data.msg || '授权过期，请重新登录。',
					// 	icon: 'none',
					// 	duration: 2000
					// })
					uni.removeStorageSync('token')
					uni.navigateTo({
						url: "/pages/login/index"
					})	
				} else if (res.data && res.data.code !== 0 && res.data.code !== 1016 && res.data.code !== 1018 && res.data.code !== 1023 && res.data.code !== 1022) {
					uni.showToast({
						title: res.data.msg || '请求错误，请重试。',
						icon: 'none',
						duration: 2000
					})
				}
				reslove(res.data)
			},
			fail: () => {
				uni.showToast({
					title: '网络错误，请重试。',
					icon: 'none',
					duration: 2000
				})
				reject()
			}
		})
	})
}

const $upload = (fileUrl, type) => {
	return new Promise((reslove, reject) => {
		let timestamp = parseInt(new Date().getTime())
		uni.uploadFile({
			url: getSignUrl(`/api/v1/mp/image/remote/upload/post/${type || 0}`, {}, timestamp),
			header: {
				'Content-Type': 'multipart/form-data',
				'Authorization': uni.getStorageSync('token') ?
					`Bearer ${uni.getStorageSync('token')}` : '',
				'x-zz-timestamp': timestamp
			},
			filePath: fileUrl,
			name: 'file',
			success: res => {
				reslove(JSON.parse(res.data))
			},
			fail: reject
		})
	})
}

const $put = (url, data) => {
	var formData = new FormData()
	Object.keys(data).forEach(key => {
		formData.append(key, data[key])
	})
	return new Promise((reslove, reject) => {

		let timestamp = parseInt(new Date().getTime())
		uni.uploadFile({
			url: getSignUrl(url, formData, timestamp),
			headers: {
				'Content-Type': 'multipart/form-data',
				'Authorization': uni.getStorageSync('token') ?
					`Bearer ${uni.getStorageSync('token')}` : '',
				'x-zz-timestamp': timestamp
			},
			fileType: formData || {},
			name: 'file',

			success: res => {

				reslove(res.data)
			},
			fail: () => {

				reject()
			}
		})
	})
}

module.exports = {
	get: (url, data) => {
		return $http(url, data, 'GET')
	},
	post: (url, data) => {
		return $http(url, data, 'POST')
	},
	put: (url, data) => {
		return $put(url, data)
	},
	upload: (file, type) => {
		return $upload(file, type)
	},
}
