<template>
	<view class="content">
		<!-- #ifdef MP-WEIXIN -->
		<view class="top" style="margin-top: 20px;">
			<view class="touxiang">
				<image src="../../static/xinlogo.png" mode=""></image>
			</view>
			<u-button text="手机号快捷登录" class="dl" :customStyle="{color:'#ffffff'}" color="#0D2E8D"
				open-type='getPhoneNumber' @getphonenumber="getPhone"></u-button>
		</view>
		<!-- #endif -->
		<!-- #ifdef APP-PLUS || H5 -->
		<view class="top">
			<view class="touxiang">
				<image src="../../static/xinlogo.png" mode=""></image>
			</view>
			<view class="twotap">
				<view :class="{'blck':activeid == index}" v-for="(item,index) in qh " :key="index"
					@click="getxz(index)">{{item.text}}</view>
			</view>
			<view class="inputs" v-if="activeid == 0 || activeid == 2 ">
				<input type="text" v-model="tel" placeholder="请输入手机号">
			</view>
			<view class="inputs" v-if="activeid == 1">
				<input type="text" v-model="tel" placeholder="请输入手机号">
			</view>
			<view class="inputs" style="justify-content: space-between; " v-if="activeid == 1">
				<input type="text" v-model="yzm" placeholder="请输入验证码">
				<button class="jsq" :disabled="isButtonDisabled" @click="sendVerificationCode">{{ buttonText }}</button>
			</view>
			<view class="inputs" v-if="activeid == 0 || activeid == 2 ">
				<input type="password" v-model="wrod" placeholder="请输入密码">
			</view>
			<view class="wjworb" v-if="activeid == 0 || activeid == 2" @click="goforgot()">
				<view class="">忘记密码</view>
			</view>
		</view>
		<view class="jiuzhong">
			<view class="dist" v-for="(item,index) in  sfa" :key="index" @click="setidentity(item.identity)">
				<view class="d-qian" v-if="sfindex != item.identity"></view>
				<view class="d-qian-lan" v-if="sfindex == item.identity">
					<u-icon name="checkbox-mark" color="#ffffff"></u-icon>
				</view>
				<view class="d-zi">{{item.name}}</view>
			</view>
			<!-- <view class="dist">
				<view class="d-qian"></view>
				<view class="d-zi">交警</view>
			</view> -->

		</view>

		<view class="dl" @click="getlogin()">
			<text>登 录</text>
		</view>
		<view class="hging">
			<text>没有账号？</text>
			<text style="color: #0078FF;" @click="goregister()">立即注册</text>
		</view>

		<!-- #endif -->

		<!-- 	<view class="wx">
			<image src="../../static/wwwx.png" mode=""></image>
		</view>
		<view class="hui">
			<text>微信登录</text>
		</view> -->
		<view class="dbottom">
			<view class="quanzi" v-if="qindex == false " @click="qindex =! qindex"></view>
			<view class="lanquanzi" v-if="qindex == true" @click="qindex =! qindex"><u-icon name="checkbox-mark"
					color="#ffffff" size="14"></u-icon></view>
			<text>请仔细阅读</text>
			<text class="lan">《用户协议》</text>
			<text>和</text>
			<text class="lan">《隐私政策》</text>
		</view>
	</view>
</template>

<script>
	import request from '../../utils/request';
	import { loginApp } from '@/api/login.js';
	import {
		setToken,
    setTenantId
	} from '@/utils/auth.js'
  import {
    login,
    getInfo,
    getTenantIdByWebsite
  } from '@/api/login.js'
	export default {
		data() {
			return {
				phoneNumber: "",
				baseUrl: this.$baseUrl,
				isButtonDisabled: false,
				countdownTime: 60,
				qh: [{
						text: '密码登录'
					},

					{
						text: '验证码登录'
					},

					// traffic police
				],
				sfa: [{
						name: '用户',
						identity: 'user'
					},
					{
						name: '交警',
						identity: 'police'
					}
				],
				qindex: false,
				sfindex: 'user',
				tel: '',
				yzm: '',
				wrod: '',
				activeid: 0,
        tenantCode: 'lighting'
			}
		},
		computed: {
			groupChange(n) {
				console.log('groupChange', n);
			},
			radioChange(n) {
				console.log('radioChange', n);
			},
			buttonText() {
				if (this.isButtonDisabled) {
					return `${this.countdownTime}s 后重新发送`;
				} else {
					return "获取验证码";
				}
			},
		},
    created(){
      getTenantIdByWebsite(this.tenantCode).then(res => {
        const tenantId = res.data;
        if (tenantId && tenantId >= 0) {
          setTenantId(tenantId)
        }
      })
    },
		methods: {

			setidentity(text) {
				this.sfindex = text

			},
			wxlogin() {
				uni.login({
					provider: 'weixin',
					success(res) {

						if (res.code) {
							uni.setStorageSync('c1', res.code);
							console.log('wxlogin:', res.code);
						} else {
							console.log('登录失败！' + res.errMsg)
						}
					}
				})
			},
			// 小程序 登录请求
			getPhone(e) {
				console.log('获取电话号', e);

				if (this.qindex != true) {
					uni.showToast({
						icon: "none",
						title: "请阅读并勾选用户协议",
						duration: 2000
					})
					return;
				}
				let that = this
				uni.login({
					provider: 'weixin',
					success(res) {
						if (res.code) {
							uni.setStorageSync('identity', that.sfindex);
							uni.checkSession({
								success: () => {
									console.log(1);
									uni.request({
										url: that.baseUrl + "/wxLoginRescue",
										method: "POST",
										data: {
											code: res.code,
											encryptedIv: e.detail.iv,
											encryptedData: e.detail.encryptedData,
											inviteId: uni.getStorageSync('inviteId') ? uni
												.getStorageSync('inviteId') : null
										},
										success: (rex) => {
											console.log('wxLoginRescue返回', rex)
											if (rex.data.code == 200) {
												if (that.loginStatus) {
													clearInterval(that.loginStatus)
												}
												// uni.setStorageSync('App-Token', rex.atoken);
												setToken(rex.data.token)
												console.log('rex.token:', rex.data.token);
												if (that.returnUrl) {

													uni.navigateBack()
												} else {
													// this.userinfo()
													// uni.setStorageSync('App-Token', rex.token);
													setToken(rex.data.token)
													that.userinfo()

													console.log('成功');
												}
											}
											if (rex.data.code == 500) {
												uni.clearStorageSync();
												uni.showToast({
													icon: 'none',
													title: rex.data.msg
												})
												console.log('走错误请求');
												that.wxlogin()
											}
										},
										fail: (res) => {
											console.log("fail", res);
											uni.showToast({
												icon: "error",
												title: "登录失败，请重新点击并授权！",
												duration: 2000
											})
										}
									})
								},
								fail: () => {
									uni.showToast({
										icon: 'error',
										duration: 2000,
										title: "登录状态过期，重新登录"
									});
								}
							})
						} else {
							console.log('登录失败！' + res.errMsg)
						}
					}
				})

			},
			//登录请求
			getlogin() {
				if (this.qindex != true) {
					uni.showToast({
						icon: "none",
						title: "请阅读并勾选用户协议",
						duration: 2000
					})
					return;
				}
				if (this.tel == '') {
					uni.showToast({
						title: '输入框不能为空！',
						icon: 'none'
					})
					return
				}

				uni.setStorageSync('identity', this.sfindex);

				if (this.activeid == 0) {
					const data = {
						username: this.tel,
						password: this.wrod,
						type: 0
					}
					loginApp(data).then(res => {
						setToken(res.data.accessToken)
						this.userinfo()
					})
				}
				if (this.activeid == 1) {
					const data = {
						phone: this.tel,
						code: this.yzm,
						type: 1
					}
					request({
						url: '/loginApp',
						method: 'post',
						data: data
					}).then((res) => {
						console.log('验证码请求', res);
						if (res.code == 0) {
							uni.showToast({
								title: '登录成功',
								icon: 'none'
							})
              setToken(res.data.accessToken)
							this.userinfo()

						}

					})
				}
			},
			userinfo() {
				if (this.sfindex == 'user') {
          getInfo().then((res) => {
						let userJson = {}
						userJson.userId = res.data.user.id
            let userInfo = res.data.user.info
            userInfo.id = res.data.user.id
						uni.setStorageSync('userInfo', userInfo)
						uni.setStorageSync('userId', res.data.user.id)
						uni.setStorageSync('role', res.data.roles)
						this.goselect()
					})
				}
				if (this.sfindex == 'police') {
					request({
						url: '/rescue/getJjInfo',
						method: 'get',
					}).then((res) => {
						let userJson = {}
						userJson.userId = res.data.user.id
						uni.setStorageSync('userInfo', res.data.user)
            let roles = res.data.role.map(item=>{item.name})
						uni.setStorageSync('role', roles)
						uni.setStorageSync('userId', res.data.user.id)
						this.goselect()
					})
				}


			},
			getxz(index) {
				this.activeid = index
			},
			goregister() {
				uni.navigateTo({
					url: '/pages/login/register'
				})
			},
			goforgot() {
				uni.navigateTo({
					url: '/pages/login/forgot'
				})
			},
			goselect() {
				console.log('执行去救援', this.sfindex);
				// pages/rescue/trafficPolice
				if (this.sfindex == 'police') {
					uni.reLaunch({
						url: '/pages/rescue/trafficPolice'
					})
				} else {
					uni.reLaunch({
						url: '/pages/rescue/rescue'
					})
				}

			},
			// 验证码方法
			sendVerificationCode() {
				let reg = /^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\d{8}$/;
				if (!reg.test(this.tel)) {
					uni.showToast({
						icon: 'none',
						title: '请输入正确的11位手机号'
					})
					this.tel = '';
					return false;
				}
				if (this.isButtonDisabled) {
					return; // 如果按钮已禁用，则直接返回
				}
				const data = {
					phone: this.tel,
				}
				request({
					url: '/loginSmsCode',
					method: 'post',
					params: data
				}).then((res) => {
					console.log('验证码', res);
					if (res.code == 200) {
						uni.showToast({
							title: '验证码已发送 请注意查收',
							icon: 'none'
						})
					} else {
						uni.showToast({
							title: '网络不佳请稍后再试',
							icon: 'none'
						})
					}
				})


				this.disableButton(); // 禁用按钮
				this.startCountdown(); // 启动倒计时

			},
			disableButton() {
				this.isButtonDisabled = true;
			},
			enableButton() {
				this.isButtonDisabled = false;
			},
			startCountdown() {
				let countdown = setInterval(() => {
					this.countdownTime--;
					if (this.countdownTime === 0) {
						clearInterval(countdown);
						this.enableButton(); // 启用按钮
					}
				}, 1000);
			},
		}
	}
</script>

<style scoped lang="scss">
	.jsq {
		border: none !important;
		font-size: 14px;
		font-weight: 400;
		color: #0078FF;
	}

	button {
		border: none !important;
		background: none !important;
		margin: 0px;
		display: block;
	}

	button:focus {
		color: #0078FF;
		outline: none;
		box-shadow: none;
	}

	.content {
		box-sizing: border-box;
	}

	.top {
		box-sizing: border-box;
		padding: 0px 27px;
		padding-top: 100px;
		background-image: url('../../static/loginbj.png');
		// background-color:lightseagreen;
		// background-image: url('../../static/loginbj.png');
		background-size: cover;
		background-position: center;
		width: 100%;
		// height: 385px;
	}

	.touxiang {
		width: 88px;
		height: 88px;
		border-radius: 10px;
		background: #D7D7D7;
		margin: 0 auto;
		margin-bottom: 40px;
		overflow: hidden;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.twotap {
		width: 100%;
		display: flex;
		align-items: center;

		view {
			font-size: 15px;
			font-family: Microsoft YaHei;
			font-weight: 400;
			color: #666666;
			margin-right: 38.5px;
		}
	}

	.blck {
		color: #333333 !important;
		font-weight: bold !important;
	}

	.inputs {
		box-sizing: border-box;
		padding: 16px 0px;
		display: flex;
		align-items: center;
		border-bottom: 2px solid #E8E8E8;
		margin-top: 20px;
	}

	.wjworb {
		margin-top: 5px;
		width: 100%;
		display: flex;
		font-size: 12px;
		color: #0078FF;
		justify-content: flex-end;
		align-items: center;

	}

	.dl {
		width: 90%;
		height: 44px;
		background: linear-gradient(-46deg, #0853C4 0%, #4282D8 80%);
		border-radius: 5px;
		margin: 0 auto;
		font-size: 16px;
		color: #FFFFFF;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-top: 22px;
	}

	.hging {
		width: 100%;
		text-align: center;
		font-size: 14px;
		font-weight: 400;
		color: #636363;
		margin-top: 20px;
	}

	.wx {
		width: 38px;
		height: 38px;
		overflow: hidden;
		box-sizing: border-box;
		margin: 0px auto;
		margin-top: 20px;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.hui {
		font-size: 10px;
		width: 100%;
		text-align: center;
		font-weight: 400;
		color: #666666;
	}

	.dbottom {
		width: 100%;
		text-align: center;
		font-size: 12px;
		color: #333333;
		margin-top: 40px;
		position: fixed;
		bottom: 25px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.quanzi {
		width: 14px;
		height: 14px;
		border: 1px solid #666666;
		border-radius: 50%;
		margin-right: 10px;
	}

	.lanquanzi {
		width: 14px;
		height: 14px;
		border: 1px solid #0078FF;
		border-radius: 50%;
		margin-right: 10px;
		background: #0078FF;
		color: white;
	}

	.lan {
		color: #0078FF;
	}

	.jiuzhong {
		width: 90%;
		margin: 10px auto;
		display: flex;
		align-items: center;
	}

	.dist {
		display: flex;
		align-items: center;
		margin: 0px 10px;
	}

	.d-zi {
		font-size: 14px;
	}

	.d-qian {
		width: 14px;
		height: 14px;
		margin-right: 5px;
		overflow: hidden;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		border: 1px solid #666666;
		color: white;
	}

	.d-qian-lan {
		width: 14px;
		height: 14px;
		margin-right: 5px;
		overflow: hidden;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		background: #0078FF;
		border: 1px solid #0078FF;
		color: white;
	}
</style>
