let wxApi = {}

const tips = (title) => {
	uni.showToast({
		title,
		icon: "none"
	});
}

const getScopeDesc = (name) => {
	let title = ''
	switch (name) {
		case 'userInfo':
			title = '用户信息'
			break;
		case 'userLocation':
			title = '地理位置'
			break;
		case 'userLocationBackground':
			title = "后台定位"
			break;
		case 'address':
			title = "通讯地址"
			break;
		case 'record':
			title = "录音功能"
			break;
		case 'writePhotosAlbum':
			title = "添加到相册"
			break;
		case 'camera':
			title = "摄像头"
			break;
		case 'invoice':
			title = "获取发票"
			break;
		case 'invoiceTitle':
			title = "发票抬头"
			break;
		case 'werun':
			title = "微信运动步数"
			break;
		default:
			break;
	}
	return title
}

const settingModal = (content) => {
	uni.showModal({
		title: '提示',
		content,
		confirmText: '去设置',
		cancelText: '暂不设置',
		confirmColor: '#EF9944',
		success: data => {
			if (data.confirm) {
				uni.openSetting();
			}
		}
	});
}

//打开设置
const openSetting = (authName) => {
	return new Promise((resolve, reject) => {
		const scopeDesc = getScopeDesc(authName)
		let content = `请先在设置页面打开“${scopeDesc}”使用权限`
		authName = `scope.${authName}`
		uni.getSetting({
			success: (res) => {
				console.log(res.authSetting);
				let status = res.authSetting[authName]
				if (status == undefined) {
					//首次授权
					uni.authorize({
						scope: authName,
						success: (res) => {
							//成功授权
							resolve(res)
						}
					})
					return
				}
				if (status) {
					// 已授权
					resolve(res)
				} else {
					//未授权
					settingModal(content)
				}
			}
		})
	})
}
// 微信登陆
wxApi.wxLogin = () => {
	return new Promise((resolve, reject) => {
		uni.login({
			success: function(res) {
				resolve(res)
			},
			fail: function(err) {
				console.warn(err)
				reject(err)
			}
		})
	})
}

//选择图片 res.tempFilePaths[0]
wxApi.chooseImage = (count = 1, size = 2) => {
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count,
			//最多可以选择的图片张数，默认9
			sourceType: ['album', 'camera'],
			sizeType: ['compressed'],
			//可选择原图或压缩后的图片
			success: res => {
				if (res.tempFiles[0].size > size * 1024 * 1024) {
					uni.showToast({
						title: `上传的照片不能超过${size}m`,
						icon: "none"
					})
					return
				}
				resolve(res.tempFilePaths)
			},
			fail(err) {
				reject(err)
			}
		});

	})
}


wxApi.downloadFile = (url) => {
	return new Promise((resolve, reject) => {
		uni.downloadFile({
			url, //仅为示例，并非真实的资源
			success: (res) => {
				if (res.statusCode === 200) {
					resolve(res.tempFilePath)
				} else {
					reject(res)
				}
			},
			fail: function(err) {
				reject(err)
			}
		});
	})
}

wxApi.saveImg = (filePath) => {
	return new Promise((resolve, reject) => {
		openSetting('writePhotosAlbum').then(() => {
			uni.saveImageToPhotosAlbum({
				filePath,
				success: function(res) {
					uni.showToast({
						title: "保存成功",
						icon: "none"
					});
					resolve(res)
				},
				fail: function(err) {
					tips('保存失败，请稍后重试')
					reject(err)
				}
			});
		})
	})
}


wxApi.chooseLocation = () => {
	return new Promise((resolve, reject) => {
		openSetting('userLocation').then(() => {
			uni.chooseLocation({
				success(res) {
					resolve(res)
				},
				fail(err) {
					reject(err)
				}
			})
		})
	})
}

wxApi.getLocation = () => {
	return new Promise((resolve, reject) => {
		uni.getLocation({
			type: 'gcj02',
			success: function(res) {
				resolve(res)
			},
			fail: function(err) {
				reject(err)
			}
		});
	})
}

wxApi.getConnectedWifi = () => {
	return new Promise((resolve, reject) => {
		uni.startWifi({
			success: function(res) {
				wx.getConnectedWifi({
					success: res => {
						resolve(res)
					},
					fail: err => {
						reject(err)
					}
				})
			},
			fail: function(err) {
				reject(err)
			}
		});
	})
}
/**
 * 订阅认证信息
 */
wxApi.subscribe = (tmplIds) => {
		return new Promise((resolve, reject) => {
			uni.requestSubscribeMessage({
				tmplIds,
				success(res) {
					console.log(res);
					resolve(res)
				},
				fail(err) {
					console.log(err);
					reject(err)
				}
			})
		})
	},


	// 获取用户信息
	wxApi.wxGetUserInfo = () => {
		return new Promise((resolve, reject) => {
			uni.getUserInfo({
				withCredentials: true,
				success: function(res) {
					resolve(res)
				},
				fail: function(err) {
					reject(err)
				},
			})
		})
	}

//新版本的获取用户信息
wxApi.getUserProfile = () => {
	return new Promise((resolve, reject) => {
		uni.getUserProfile({
			desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
			success: (res) => {
				resolve(res)
			},
			fail: (err) => {
				reject(err)
			}
		})
	})
}

let compareVersion = (v1, v2) => {
	v1 = v1.split('.')
	v2 = v2.split('.')
	const len = Math.max(v1.length, v2.length)

	while (v1.length < len) {
		v1.push('0')
	}
	while (v2.length < len) {
		v2.push('0')
	}

	for (let i = 0; i < len; i++) {
		const num1 = parseInt(v1[i])
		const num2 = parseInt(v2[i])

		if (num1 > num2) {
			return 1
		} else if (num1 < num2) {
			return -1
		}
	}
	return 0
}

wxApi.versioning = (minVersion) => {
	const version = wx.getSystemInfoSync().SDKVersion
	return new Promise((resolve, reject) => {
		if (compareVersion(version, minVersion) >= 0) {
			resolve()
		} else {
			uni.showModal({
				content: "当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。"
			})
		}
	})
}
export default wxApi
