import { baseURL, api } from './index.js'
export const httpRequest = (params) => {
	return new Promise(async (resolve, reject) => {
		await getNetWork()
		let { url, method, data } = params
		// uni.showLoading({
		//     title: '加载中'
		// });
		uni.request({
			url: baseURL + url,
			method: method || 'GET',
			data: data || {},
			header: {
				'token': uni.getStorageSync('token')
			},
			success(res) {
				if(res.statusCode === 200){
					if(res.data.code == "200"){
						resolve(res.data)
					}else{
						if(res.data.code == 602 || res.data.code == 603|| res.data.code == 605 || res.data.code == 6004){
							resetLogin()
						}else{
							const urls = [api.listEntLicense]
							if(!urls.includes(url)){
								setTimeout(()=>{
									console.log('报错提示 -->',url,res)
									uni.showToast({
										title: res.data.message,
										icon: 'none'
									})
								},500)
							}
						}
						resolve(res.data)
					}
				}else{
					resolve({})
				}
			},
			complete(err) {
				// console.log('err--->', err)
				if(err.statusCode === 500 || err.statusCode === 502){
					uni.showToast({
						title: '服务器异常！',
						icon: 'none'
					})
				}else{
					// uni.hideLoading()
				}
			}
		})
	})
}

const getNetWork = () => {
	return new Promise((resolve, reject) => {
		uni.getNetworkType({
			success(res) {
				if(res.networkType != 'none'){
					resolve()
				}else{
					uni.showToast({
						title: '网络异常',
						icon: 'none'
					})
				}
			}
		})
	})
}

const resetLogin = () => {
	uni.login({
		success: async ({ code }) =>  {
			console.log('小程序登录过期，自动重新登录---->', code)
			uni.request({
				url:baseURL + api.appletAuth,
				method: 'POST',
				data: {
				    code,
					portType:0
				},
				success(res) {
					if (res.code == 200)  {
						console.log('登录成功')
						uni.setStorageSync('checked', res?.result.phoneNum?true:false);
						uni.setStorageSync('token', res?.result.token);
						uni.setStorageSync('phoneNum', res?.result.phoneNum);
						uni.setStorageSync('repoAccountId',res?.result.repoAccountId)
						uni.setStorageSync('accountType',res?.result.accountType)
						uni.setStorageSync('sessionKey',res?.result.sessionKey)
						uni.setStorageSync('unionId',res?.result.unionId) 
						uni.showToast({
							title: '登录过期，已自动为您重新登录',
							icon:'none'
						})
					}
				},
				complete: c => {
					console.log('c----->', c)
				}
			})
			
		}
	})
}

export const uploadFile = (url, file) => {
	return new Promise((resolve, reject) => {
		uni.showLoading({
		    title: '上传中'
		});
		uni.uploadFile({
			url: baseURL + url,
			filePath: file,
			name: 'uploadFile',
			header: {
				'token': uni.getStorageSync('token')
			},
			success: (res) => {
				let data = JSON.parse(res.data)
				resolve(data)
			},
			fail() {
				uni.showToast({
					title:'上传失败',
					icon:'none'
				})
			},
			complete() {
				uni.hideLoading()
			}
		})
	})
}