<template>
	<view class="container">
		<global-loading />
		<view style="padding: 68upx 0 0 56upx;color: #ffffff;">
			<view style="font-weight: bold;font-style: oblique;">
				<view style="font-size: 58upx;">欢迎来到</view>
				<view style="font-size: 62upx;">巨蜂本地生活</view>
			</view>
			<view style="margin-top: 12upx;;font-size: 30upx;">
				<text>数字化营销的领跑者</text>
			</view>
		</view>

		<view style="display: flex;flex-direction: column;justify-content: center;align-items: center;margin-top: 80upx;">
			<view
				v-if="(wxLoginQuery.terminal === 3) || (wxLoginQuery.terminal === 2)" style="text-align: center;"
				@click="handleWXLogin"
			>
				<image style="width: 118upx;height: 98upx;" src="../../static/images/icon/we-chat.png" mode="" />
				<tui-button type="white" width="480rpx" height="82rpx" margin="40upx 0 0" shape="circle" @click="handleWXLogin">
					微信一键登录
				</tui-button>
			</view>
			<!-- #ifdef MP-ALIPAY -->
			<tui-button
				type="danger" width="480rpx" height="82rpx" margin="70upx 0 0"
				shape="circle"
				@click="GetAliPayUserInfo"
			>
				支付宝登录
			</tui-button>
			<!-- #endif -->
			<tui-button
				type="white" width="480rpx" height="82rpx" margin="70upx 0 0"
				shape="circle"
				@click="$switchTab('/pages/tabbar/index/index')"
			>
				去首页逛逛
			</tui-button>
		</view>

		<view class="otherLoginButton">
			<view class="orderButtonItem">
				<view style="display: flex;flex-direction: column;align-items: center;">
					<view style="width: fit-content;padding: 12upx;background-color: #ffffff;border-radius: 48upx;">
						<tui-icon
							name="wealth-fill" color="#ce2601" :size="24"
							@click="$jump('/pages_category_page2/userModule/register', '', 0, 'redirect')"
						></tui-icon>
					</view>
					<view style="margin-top: 12upx;font-size: 26upx;color: #ffffff;">注册</view>
				</view>
				<view style="display: flex;flex-direction: column;align-items: center;">
					<view style="width: fit-content;padding: 12upx;background-color: #ffffff;border-radius: 48upx;">
						<tui-icon
							name="mail-fill" color="#ce2601" :size="24"
							@click="$jump('/pages_category_page2/userModule/accountLogin?type=verificationCode')"
						></tui-icon>
					</view>
					<view style="margin-top: 12upx;font-size: 26upx;color: #ffffff;">短信登录</view>
				</view>
				<view style="display: flex;flex-direction: column;align-items: center;">
					<view style="width: fit-content;padding: 12upx;background-color: #ffffff;border-radius: 48upx;">
						<tui-icon
							name="pwd" color="#ce2601" :size="24"
							@click="$jump('/pages_category_page2/userModule/accountLogin?type=password')"
						></tui-icon>
					</view>
					<view style="margin-top: 12upx;font-size: 26upx;color: #ffffff;">密码登录</view>
				</view>
			</view>
		</view>
		<view class="agreement">
			登录即同意<text class="colorText">《联通统一认证服务条款》</text>和<text class="colorText">《巨蜂商城用户 服务协议》</text>、<text
				class="colorText"
			>
				《隐私政策》
			</text>并使用本机号码登陆
		</view>
	</view>
</template>

<script>
import { J_STORAGE_KEY } from '../../config/constant'
const NET = require('../../utils/request')
const API = require('../../config/api')
import { updateWXLoginApi } from '../../api/user'
import { isInWx, getUrlCode } from '../../utils'
export default {
	name: 'Login',
	data() {
		return {
			wxLoginQuery: {
				code: '',
				salesId: 0,
				headImage: '',
				terminal: 0
			}
		}
	},
	onLoad(options) {
		if (isInWx()) {
			this.wxLoginQuery.terminal = 3
		} else {
			// #ifdef H5
			this.wxLoginQuery.terminal = 5 // H5包含pc和移动端浏览器和微信浏览器的可能
			// #endif
			// #ifdef APP
			this.wxLoginQuery.terminal = 1
			// #endif
			// #ifdef MP-WEIXIN
			this.wxLoginQuery.terminal = 2
			// #endif
			// #ifdef MP-ALIPAY
			this.wxLoginQuery.terminal = 4
			// #endif
		}
		const pages = getCurrentPages()
		uni.setStorageSync('last_page', pages[pages.length - 2].route)
		if (pages[pages.length - 2].options) {
			uni.setStorageSync('last_page_options', pages[pages.length - 2].options)
		}
	},
	onShow() {
		// 所有需要授权页面进登录页面取消loading
		uni.hideLoading()
		if (isInWx()) {
			const code = getUrlCode().code
			if (code) this.handleWXLogin()
		}
	},
	onBackPress() {
		this.$switchTab('/pages/tabbar/index/index')
		return true
	},
	methods: {
		// 微信登录
		async handleWXLogin() {
			// uni.showLoading({
			// 	title: '正在加载...',
			// 	mask: true
			// });
			// // #ifdef APP
			// uni.login({
			// 	provider: 'weixin',
			// 	success: function(loginRes) {
			// 		// 获取用户信息
			// 		uni.getUserInfo({
			// 			provider: 'weixin',
			// 			success: function(infoRes) {
			// 				let wechatOpenId = infoRes.userInfo.openId
			// 				let avatarUrl = infoRes.userInfo.avatarUrl
			// 				updateWXAppLoginApi({
			// 					'wechatOpenId': wechatOpenId
			// 				}).then(res => {
			// 					let data = {
			// 						wechatOpenId: wechatOpenId,
			// 						headImage: avatarUrl
			// 					}
			// 					that.handleLoginSuccess(res.data, data)
			// 				}).catch(res => {
			// 					console.log('failed: ', res)
			// 				})
			// 			},
			// 			fail: (err) => {
			// 				this.$showToast('微信登录授权失败')
			// 			}
			// 		});
			// 	}
			// });
			// // #endif
			if (this.wxLoginQuery.terminal === 2) {
				uni.login({
					provider: 'weixin',
					success: (res2) => {
						uni.hideLoading()
						this.wxLoginQuery.code = res2.code
					},
					fail: (err) => {
						this.$showToast('微信登录授权失败')
					}
				})
				uni.getUserProfile({
					desc: '正在获取', // 不写不弹提示框
					success: (res) => {
						this.wxLoginQuery.headImage = res.userInfo.avatarUrl
						// this.handleLoginSuccess({'ifFirst': 1}, {'headImg': res.userInfo.avatarUrl})
						updateWXLoginApi(this.wxLoginQuery)
							.then((data) => {
								this.handleLoginSuccess(data, { wechatOpenId: data.wechatOpenId, headImage: data.headImage })
							})
					},
					fail: (err) => {
						this.$showToast('微信登录授权失败')
					}
				})
			} else if (this.wxLoginQuery.terminal === 3) {
				const appid = 'wx603b04a561e4683e' // wxdf390bb4f8a67641
				const local = 'https://nsh5.tuanfengkeji.cn/#/pages_category_page2/userModule/login'
				const code = getUrlCode().code
				// console.log('获取code', code)
				if (code === null || code === undefined || code === '') {
					window.location.href =
						'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
						appid +
						'&redirect_uri=' +
						encodeURIComponent(local) +
						'&response_type=code&scope=snsapi_userinfo#wechat_redirect'
				} else {
					this.wxLoginQuery.code = code
					const { data } = await updateWXLoginApi(this.wxLoginQuery)
					this.handleLoginSuccess(data, { wechatOpenId: data.wechatOpenId, headImage: data.headImage }, 'WX')
				}
			}
		},
		GetAliPayUserInfo() {
			const that = this
			uni.login({
				provider: 'alipay',
				scopes: 'auth_user',
				success(loginRes) {
					that.alipayLogin(loginRes.authCode)
				}
			})
		},
		alipayLogin(authCode) {
			NET.request(API.AlipayLogin, {
				'code': authCode
			}, 'POST').then((res) => {
				this.handleLoginSuccess(res.data, {
					'buyerUserId': res.data.buyerUserId
				})
			})
		},
		handleLoginSuccess(buyerUser, data, type = '') {
			if (type === 'WX') {
				if (buyerUser.ifFirst == 0) {
					uni.setStorageSync(J_STORAGE_KEY, buyerUser)
					this.bindSalesCustomer()
					window.location.replace('https://nsh5.tuanfengkeji.cn/#/pages/tabbar/user/index')
				} else {
					window.location.replace(`https://nsh5.tuanfengkeji.cn/#/pages_category_page2/userModule/bindPhone?data=${JSON.stringify(data)}`)
				}
			} else if (!type) {
				if (buyerUser.ifFirst == 0) {
					uni.setStorageSync(J_STORAGE_KEY, buyerUser)
					this.bindSalesCustomer()
					const last_page = uni.getStorageSync('last_page') || ''
					if (last_page) {
						const last_page_options = uni.getStorageSync('last_page_options') || ''
						const str = JSON.stringify(last_page_options).replaceAll('{', '')
							.replaceAll('}', '')
							.replaceAll('"', '')
							.replaceAll(':', '=')
							.replaceAll(',', '&')
						// 保留其他路由，需跳转2下 到最后登录页面
						// uni.navigateBack({
						//     delta: 1
						// })
						// uni.redirectTo({
						// 	url: `/${last_page}?${str}`,
						// })
						// 清空其他路由，直接跳转最后登录页面
						uni.reLaunch({
							url: `/${last_page}?${str}`
						})
					} else {
						// #ifdef MP-ALIPAY
						uni.navigateTo({
							url: '/pages/tabbar/user/index'
						})
						// #endif
						// #ifndef MP-ALIPAY
						this.$switchTab('/pages/tabbar/user/index')
					// #endif
					}
				} else { // 第一次登录，绑定手机号
					uni.redirectTo({
						url: 'bindPhone?data=' + JSON.stringify(data)
					})
				}
			}
		},
		bindSalesCustomer() {
			const shopId = uni.getStorageSync('shopId')
			const salesId = uni.getStorageSync('salesId')
			if (shopId && salesId && shopId !== '' && salesId !== '') {
				// 多次调用绑定方法，不提示任何信息即可
				NET.request(API.BindSalesCustomer, {
					shopId,
					distributorId: salesId
				}, 'POST').then((res) => {
					uni.removeStorageSync('salesId')
					uni.removeStorageSync('shopId')
				})
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.container {
	background-color: #ce2601;
	min-height: 100vh;

	.otherLoginButton {
		margin-top: 195rpx;
		display: flex;
		flex-direction: column;
		align-items: center;

		.orderButtonItem {
			display: flex;
			justify-content: space-around;
			white-space: nowrap;

			&>view:not(:first-child) {
				padding-left: 48upx;
			}
		}
	}

	.agreement {
		margin-top: 120rpx;
		padding: 75upx;
		font-family: Source Han Sans CN;
		font-size: 24rpx;
		font-weight: 350;
		line-height: 32rpx;
		text-align: center;

		.colorText {
			color: #faf9f9;
		}
	}
}

.loginWxBut::after {
	border-radius: 0 !important;
}
</style>

