<template>
	<view>
		<loginPage v-if="type == 1" @goLogin="goLogin" @backPage="backPage"></loginPage>
		<loginPopup v-if="type == 2" :show='show' @loginShow="loginShow" @empower="empower" @goLogin="goLogin">
		</loginPopup>
	</view>
</template>

<script>
	import loginPopup from './loginPopup.vue'
	import loginPage from './loginPage.vue'
	// #ifdef H5
	import ap from "@/uni_modules/alipayjsapi/alipayjsapi.js"
	// #endif
	export default {
		name: "login",
		components: {
			loginPopup,
			loginPage
		},
		data() {
			return {
				title: "Hello",
				disabled: false,
				show: false
			};
		},
		props: {
			type: Number,
			// show: Boolean,
			wcCode: String,
		},
		created() {
			if (this.wcCode) {
				this.actionLogin(this.wcCode, '', 1);
			}
			// 验证是否需要登录
			if (this.type == 2) {
				this.isLogin()
			}
			// #ifdef H5
			// 如果是支付宝h5自动完成登陆
			if (this.type == 0) {
				if (this.$utils.isInAliBrowser()) {
					this.login()
				}
			}
			// #endif
		},
		methods: {
			async login({
				phone_code
			} = {}) {
				this.disabled = true;
				let that = this
				// #ifdef MP-WEIXIN 
				uni.login({
					provider: "weixin", //使用微信登录
					// onlyAuthorize: '',
					success: (loginRes) => {
						this.actionLogin(loginRes.code, phone_code);
					},
					fail: (res) => {
						uni.$u.toast(res.errMsg);
						this.disabled = false;
					},
				});
				// #endif

				// #ifdef MP-ALIPAY
				my.getAuthCode({
					scopes: 'auth_user',
					success: (loginRes) => {
						if (loginRes.authCode) {
							this.actionLogin(loginRes.authCode);
						} else {
							// uni.$u.toast(loginRes.errMsg ? loginRes.errMsg : '登录失败');
						}
					},
					fail: (res) => {
						uni.$u.toast(res.errMsg);
						this.disabled = false;
					},
				});
				// #endif

				//#ifdef H5
				// 支付宝h5登陆
				if (this.$utils.isInAliBrowser()) {
					const res = await this.$api.common.aliH5();
					// 获取微信应用的 appid
					const appid = res.data.appid;

					ap.getAuthCode({
						appId: appid,
						scopes: ['auth_base'],
					}, function(res) {
						console.log(res, 'resresres')
						if (res.authCode) {
							that.actionLogin(res.authCode, '', 2);
						} else {
							uni.showToast({
								icon: 'none',
								title: res.errorDesc || res.errorMessage
							})
						}
					});
					return;

				} else if (this.$utils.isInWeChatBrowser()) {
					// 微信h5登陆
					// 从后端API获取微信H5相关信息
					const res = await this.$api.common.wechatH5();
					// 获取微信应用的 appid
					const appid = res.data.appid;
					// 获取当前页面的重定向地址并进行编码
					let redirect_uri = window.location.href;
					redirect_uri = encodeURIComponent(redirect_uri);
					// 构建微信授权链接，包含应用的appid、重定向地址等参数
					const wxAuthUrl =
						`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
					// 通过重定向将用户导向微信授权页面
					window.location.href = wxAuthUrl;
					return;
				} else {
					return;
				}
				//#endif

			},
			// 验证是否已经登陆
			async isLogin() {
				const res = await this.$api.user.isLogin();
				if (res.data.is_login > 0) {
					this.$emit('isLogin')
				} else {
					this.show = true;
				}
			},
			async actionLogin(code, phone_code = "", origin_h5 = 0) {
				const foke_parent_user = uni.getStorageSync('distributor_id') || 0
				try {
					const res = await this.$api.user.login({
						code,
						foke_parent_user,
						phone_code,
						origin_h5
					});
					uni.hideLoading();
					if (!res.code) {
						let {
							token,
							user_info,
							store_id
						} = res.data;

						uni.setStorageSync("token_" + store_id, token);
						uni.setStorageSync("user_info", user_info);
						if (this.type != 0) {
							uni.showToast({
								icon: "none",
								title: "登录成功",
							});
						}
						foke_parent_user && this.initDistributor(foke_parent_user)
						this.backPage()
						return;
					}

					uni.$u.toast(res.message);
				} catch (e) {
					uni.hideLoading();
					throw new Error(e);
				}
				this.disabled = false;
			},
			loginShow(e) {
				// this.$emit('loginShow', e);
				this.show = e
			},
			empower(e) {
				this.login()
			},
			goLogin(e, params) {
				this.login(params)
			},

			backPage() {
				if (this.type == 0) {

				} else if (this.type != 2) {
					setTimeout(() => {
						const backPage = uni.getStorageSync("backPage")
						if (backPage) {
							if (backPage.includes('login/login')) {
								this.$utils.toUrl("/pages/index/index", "redirectTo");
							} else {
								this.$utils.toUrl(backPage);
							}
						} else {
							this.$utils.toUrl("/pages/index/index", "redirectTo");
						}
						// this.$emit('loginShow', false);
					}, 200);
				} else {
					this.$emit('isLogin')
					this.loginShow(false)
				}

			}
		},
	};
</script>