<template>
	<view class="wrap">
		<view class="top"></view>
		<u-image :src="imageURL" mode="scaleToFill" height="300rpx"></u-image>
		<view class="content">
			<u-form :model="loginForm" :rules="rules" ref="uForm" :errorType="errorType">
				<u-form-item label="手机号" prop="phone" label-width="150">
					<u-input placeholder="请输入手机号" v-model="loginForm.phone" type="text">
					</u-input>
				</u-form-item>
				<u-form-item label="验证码" prop="code" label-width="150">
					<u-input placeholder="请输入验证码" v-model="loginForm.code" type="number"></u-input>
					<u-button slot="right" type="success" size="mini" @click="getCode">{{codeTips}}</u-button>
				</u-form-item>
			</u-form>
			<!-- <button  :style="[inputStyle]" class="getCaptcha">登录</button> -->
			<!-- 			<u-gap height="0.5" bg-color="#bbb"></u-gap> -->
			<view style="margin-top: 16rpx;">
				<u-button @click="submit" type="warning">登录</u-button>
			</view>
			<view class="alternative">
				<navigator url="login_password" class="password" open-type="navigate">密码登录</navigator>
			</view>
		</view>
		<u-verification-code seconds="30" ref="uCode" @change="codeChange"></u-verification-code>
		<view style="text-align: center;">
			<view class="icon">
				<u-icon size="70" name="weixin-fill" color="rgb(83,194,64)" @click="mpLogin"></u-icon>
			</view>
			微信登录
		</view>
		<!-- <view class="buttom">
			<view class="loginType">
				<view class="wechat item">
					<view class="icon"><u-icon size="70" name="weixin-fill" color="rgb(83,194,64)"></u-icon></view>
					微信登录
				</view>
				<view class="QQ item">
					<view class="icon"><u-icon size="70" name="qq-fill" color="rgb(17,183,233)"></u-icon></view>
					QQ
				</view>
			</view>
		</view> -->
	</view>
</template>

<script>
	export default {
		data() {
			return {
				wxcode: null,
				imageURL: '/static/banner3.jpg',
				testUrl: 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf7d6140f507466be&redirect_uri=http%3A%2F%2Fqyjy.ctc-zc.com&response_type=code&scope=snsapi_base#wechat_redirect',
				loginForm: {
					phone: "",
					code: ""
				},
				codeTips: "获取验证码",
				rules: {
					phone: [{
							required: true,
							message: '请输入手机号',
							trigger: ['change', 'blur'],
						},
						// {
						// 	// 正则不能含有两边的引号
						// 	pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
						// 	message: '格式有误',
						// 	trigger: ['change', 'blur'],
						// }
						// {
						// 	// 此为同步验证，可以直接返回true或者false，如果是异步验证，稍微不同，见下方说明
						// 	validator: (rule, value, callback) => {
						// 		// 调用uView自带的js验证规则，详见：https://www.uviewui.com/js/test.html
						// 		return this.$u.test.idCard(value);
						// 	},
						// 	message: '格式有误',
						// 	// 触发器可以同时用blur和change，二者之间用英文逗号隔开
						// 	trigger: ['change','blur'],
						// }
					],
					code: [{
						required: true,
						message: '请输入验证码',
						trigger: ['change', 'blur'],
					}, ]
				},
				errorType: ['message'],
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
			// #ifdef MP-WEIXIN
			uni.hideHomeButton()
			// #endif
		},
		onLoad() {
			// #ifdef H5
			this.wxcode = this.getUrlCode('code')
			// 微信公众号自动登录
			if(this.wxcode) {
			    this.wxcodeLogin()
			}
			// #endif
			
		},
		computed: {
			inputStyle() {
				let style = {};
				if (this.loginForm.phone && this.loginForm.code) {
					style.color = "#fff";
					style.backgroundColor = this.$u.color['warning'];
				}
				return style;
			},
			submitEnable() {
				if (this.loginForm.phone && this.loginForm.code) {
					return false;
				}
				return true;
			}
		},
		methods: {
			submit() {
				this.$refs.uForm.validate(valid => {
					if (valid) {
						uni.showLoading({})
						this.$u.api.codeLogin(this.loginForm).then(res => {
							this.$u.vuex('vuex_token', res.access)
							// #ifdef MP-WEIXIN
							let data = {openid: uni.getStorageSync('wxmp_openid')}
							this.$u.api.bindmp(data).then(res=>{})
							// #endif
							// #ifdef H5
							let data = {openid: uni.getStorageSync('wx_openid')}
							if(data){
								this.$u.api.bindwx(data).then(res=>{})
							}
							// #endif
							this.$u.api.getUserInfo().then(res => {
								this.$u.vuex('vuex_user', res)
								// 修改资源请求地址
								// this.$u.vuex('vuex_user.avatar', this.vuex_user.avatar +
								// 	'?token=' + this.vuex_token)
								uni.hideLoading()
							})
							uni.reLaunch({
								url: '/pages/home/home'
							})
						}).catch(e => {
							uni.hideLoading()
						})
					}
				});
			},
			codeChange(text) {
				this.codeTips = text;
			},
			// 获取验证码
			getCode() {
				if (this.$refs.uCode.canGetCode && this.loginForm.phone) {
					uni.showLoading({
						title: '正在获取验证码',
						mask: true
					})
					this.$u.api.getCode(this.loginForm).then(res => {
						setTimeout(() => {
							uni.hideLoading();
							// 这里此提示会被this.start()方法中的提示覆盖
							this.$u.toast('验证码已发送');
							// 通知验证码组件内部开始倒计时
							this.$refs.uCode.start();
						}, 2000);
					})
				} else {
					this.$u.toast('倒计时结束后再发送');
				}
			},
			wxcodeLogin(){
				uni.showLoading({
					title: '微信登录中...',
					mask: true
				})
				this.$u.api.wxLogin({
					code: this.wxcode
				}).then(res => {
					this.$u.vuex('vuex_token', res.access)
					this.$u.api.getUserInfo().then(res => {
						uni.hideLoading()
						uni.showToast({
							title: "登录成功",
							icon: "none"
						})
						uni.reLaunch({
							url: "/pages/home/home"
						})
						this.$u.vuex('vuex_user', res)
						// 修改资源请求地址
						// this.$u.vuex('vuex_user.avatar', this.vuex_user.avatar +
						// 	'?token=' + this.vuex_token)
					})
				}).catch(e => {
					uni.setStorageSync('wx_openid', e.data.wx_openid)
					uni.hideLoading()
					uni.showToast({
						title: "暂未绑定微信!",
						icon: "none"
					})
				})
			},
			mpLogin() {
				// #ifdef H5
				this.getWxCode()
				// #endif
				// #ifdef MP-WEIXIN
				uni.showLoading({
					title: '微信登录中...',
					mask: true
				})
				uni.login({
					provider: 'weixin',
					success: (loginRes) => {
						this.$u.api.wxmplogin({
							code: loginRes.code
						}).then(res => {
							this.$u.vuex('vuex_token', res.access)
							this.$u.api.getUserInfo().then(res => {
								uni.hideLoading()
								uni.showToast({
									title: "登录成功",
									icon: "none"
								})
								uni.reLaunch({
									url: "/pages/home/home"
								})
								this.$u.vuex('vuex_user', res)
								// 修改资源请求地址
								// this.$u.vuex('vuex_user.avatar', this.vuex_user.avatar +
								// 	'?token=' + this.vuex_token)
							})
						}).catch(e => {
							uni.setStorageSync('wxmp_openid', e.data.wxmp_openid)
							uni.hideLoading()
							uni.showToast({
								title: "暂未绑定微信!",
								icon: "none"
							})
						})
					}
				});
				// #endif
			},
			// 获取code
			    // 先判断url中有没有code，如果有code，表明已经授权，如果没有code，跳转微信授权链接
			    getWxCode () {
					// const isWechat = () => {
					//     return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
					// }
			  //       if(isWechat()) {
			            // 截取地址中的code，如果没有code就去微信授权，如果已经获取到code了就直接把code传给后台获取openId
			            let code = this.getUrlCode('code')
			            if (code === null || code === '') {
			                window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+this.vuex_appid+'&redirect_uri=' + encodeURIComponent(this.vuex_login) + '&response_type=code&scope=snsapi_base&state=1#wechat_redirect'
			                // redirect_uri是授权成功后，跳转的url地址，微信会帮我们跳转到该链接，并且通过？的形式拼接code，这里需要用encodeURIComponent对链接进行处理。
			                // 如果配置参数一一对应，那么此时已经通过回调地址刷新页面后，你就会再地址栏中看到code了。
			                // http://127.0.0.1/pages/views/profile/login/login?code=001BWV4J1lRzz00H4J1J1vRE4J1BWV4q&state=1
			            }else{
							this.wxcode = code
							this.wxcodeLogin()
						}
			        // }
			    },
			    
			    getUrlCode (name) {
			        return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1].replace(/\+/g, '%20')) || null
			    },
			    
		}
	};
</script>

<style lang="scss" scoped>
	.wrap {
		font-size: 28rpx;

		.content {
			width: 90%;
			margin: 40rpx auto 0;

			.title {
				text-align: center;
				font-size: 40rpx;
				font-weight: 500;
				margin-bottom: 100rpx;
			}

			input {
				text-align: left;
				margin-bottom: 10rpx;
				padding-bottom: 6rpx;
			}

			.tips {
				color: $u-type-info;
				margin-bottom: 60rpx;
				margin-top: 8rpx;
			}

			.getCaptcha {
				background-color: rgb(253, 243, 208);
				color: $u-tips-color;
				border: none;
				font-size: 30rpx;
				padding: 12rpx 0;
				margin-top: 6rpx;

				&::after {
					border: none;
				}
			}

			.alternative {
				color: $u-tips-color;
				display: flex;
				justify-content: space-between;
				margin-top: 30rpx;
			}
		}

		.buttom {
			.loginType {
				display: flex;
				padding: 350rpx 150rpx 150rpx 150rpx;
				justify-content: space-between;

				.item {
					display: flex;
					flex-direction: column;
					align-items: center;
					color: $u-content-color;
					font-size: 28rpx;
				}
			}

			.hint {
				padding: 20rpx 40rpx;
				font-size: 20rpx;
				color: $u-tips-color;

				.link {
					color: $u-type-warning;
				}
			}
		}
	}
</style>
