import {
	loginApi,
	loginCodeApi,
	loginByZfbCode
} from "@/api/api.js"
import {
	init
} from '@/utils/sok.js';


export const login = async (params, type = 1) => {
	if (type == 1) {
		var {
			code: loginCode
		} = await uni.login({
			provider: 'weixin'
		});
		try {
			let {
				token,
				userInfo
			} = await loginCodeApi({
				loginCode
			})
			uni.setStorageSync('token', token);
			uni.setStorageSync('user', userInfo);
			uni.setStorageSync('isInvest', false);
		} catch (err) {
			if (err.code == 10) {
				uni.setStorageSync('token', false);
			}
		}
	} else if (type == 2) {
		
		
		
		var {
			code: phoneCode
		} = params.detail;
		var {
			code: loginCode
		} = await uni.login({
			provider: 'alipay'
		});
		try {
			// #ifdef MP-WEIXIN
			let {
				token,
				user
			} = await loginApi({
				phoneCode,
				loginCode
			});
			// #endif
			// #ifdef MP-ALIPAY
			let {
				token,
				user
			} = await loginByZfbCode({
				phoneCode,
				loginCode
			});
			// #endif


			uni.setStorageSync('token', token);
			uni.setStorageSync('user', user);
			uni.setStorageSync('isInvest', false);
			
			uni.reLaunch({
				url: '/pages/home/home'
			});
			
			// uni.navigateBack()
			// uni.navigateBack()
			init()
		} catch (err) {
			console.log(err);
		}
	}
}


const download = (e, type) => {
	const base64 = uni.arrayBufferToBase64(e.data);
	const fs = wx.getFileSystemManager()
	var imgPath = ''11
	if (type == 'video') {
		imgPath = wx.env.USER_DATA_PATH + '/base64Video' + '.mp4' //自定义下载图片的名称
	} else {
		imgPath = wx.env.USER_DATA_PATH + '/base64img' + '.png' //自定义下载图片的名称
	}
	fs.writeFile({
		filePath: imgPath, //设置下载图片的地址
		data: base64, //slice(22)的目的是去掉data:image/png;base64,如果本身就不带的话，就直接this.data.codeImg就好了
		encoding: 'base64',
		success: function(res) {
			//读取文件
			wx.getImageInfo({
				src: imgPath,
				success: function(ret) {
					console.log("请求到了");
					var path = ret.path;
					wx.saveImageToPhotosAlbum({
						filePath: imgPath, //设置下载图片的地址
						success(result) {
							console.log("保存成功"); //保存成功
						}
					})
				}
			})
			// console.log(res);
			// console.log("请求到了");
			// wx.saveImageToPhotosAlbum({
			// 	filePath: imgPath, //设置下载图片的地址
			// 	success: function() {
			// 		console.log("保存成功"); //保存成功
			// 	}
			// })
		}
	})
}