<template>
	<view class="login-container">
	   <uni-nav-bar title="登录" color="#8B2316" height="160rpx" :border="false" backgroundColor="#eeeeee"></uni-nav-bar>
		<!-- 主要内容区域 -->
		<view class="main-content" >
			
			<!-- 应用图标和名称 -->
			<view class="app-info">
				<view class="app-icon">
					
						<up-image  :src="logo" width="164rpx" height="167rpx" ></up-image>
					
				</view>
				<text class="app-name">专家版</text>
			</view>
           
			<!-- 手机号显示 -->
			<!-- #ifdef APP -->
			<!-- <view class="phone-display">
				<text class="phone-number">176****8628</text>
			</view> -->
           
			<!-- 登录按钮 -->
			<view class="login-button" @click="onOneClickLogin">
				<text class="button-text">本机号码一键登录</text>
			</view>

			<!-- 短信验证码登录 -->
			<view class="sms-login" @click="onSmsLogin">
				<text class="sms-text">短信验证码登录</text>
			</view>

			<!-- 微信登录 -->
			<view class="wechat-login" @click="onWechatLogin">
				<view class="wechat-icon">
					<up-image  :src="wxImg" width="100rpx" height="100rpx" ></up-image>
				</view>
				<text class="wechat-text">微信登录</text>
			</view>
			<!-- #endif -->
			<!-- #ifdef MP-WEIXIN -->
			<up-button
			  v-if="isAgreed"
			  :customStyle="customStyle"
			  class="login-button"
			  type="success"
			  @getphonenumber="getPhoneNumber"
			  open-type="getPhoneNumber"
			  text="手机号快捷登录"
			  color="#3cc7c0"
			  size="large"
			></up-button>
			 <up-button
			  v-else
			  :customStyle="customStyle"
			  class="login-button"
			  type="success"
			  @click="alertAgree"
			  text="手机号快捷登录"
			  color="#3cc7c0"
			  size="large"
			></up-button>
			<view class="sms-login" @click="onSmsLogin" style="margin-top: 20rpx;">
				<text class="sms-text">短信验证码登录</text>
			</view>
			
			<!-- 微信登录 -->
			<view class="wechat-login" @click="onWechatLogin">
				<view class="wechat-icon">
					<up-image  :src="wxImg" width="100rpx" height="100rpx" ></up-image>
				</view>
				<text class="wechat-text">微信登录</text>
			</view>
			
			<!-- #endif -->
			
		</view>
		

		<!-- 底部协议 -->
		<view class="agreement-section">
			<view class="agreement-content">
				
				<view class="checkbox"  @click="toggleAgreement">
					<up-image  :src="checkImg" width="45rpx" height="45rpx" v-if="!isAgreed"></up-image>
					<up-image  :src="checkOnImg" width="45rpx" height="45rpx" v-else></up-image>
				</view>
				<view class="agreement-text">
					<text class="text-content">我已阅读并同意</text>
					<text class="link-text" @click="onServiceTerms">《中国移动认证服务条款》</text>
					<text class="text-content">和</text>
					<text class="link-text" @click="onPrivacyPolicy">《肝胆相照隐私政策》</text>
					<text class="text-content">、</text>
					<text class="link-text" @click="onUserAgreement">《肝胆相照用户服务协议》</text>
					<text class="text-content">并使用本机号码登录并注册</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref, reactive, onMounted } from 'vue';
	import { onShow, onLoad } from "@dcloudio/uni-app";
	import auth from "@/utils/auth";
    import logo from "@/static/icon_login_logo.png"
	import wxImg from "@/static/weixin_login.png"
	import checkImg from "@/static/login_new_unselect.png"
	import checkOnImg from "@/static/login_new_select.png"
	import api from "@/api/api.js"
	import my_api from "@/api/my_api.js"
	import BASE_URL from "@/utils/config.js"
	import { createSignedPostData } from '@/utils/sign.js'
	import navTo from "@/utils/navTo"

	const customStyle = reactive({
	  height: "100rpx",
	  fontSize: "36rpx",
	  backgroundColor:'#8B2316',
	  borderRadius: '50rpx'
	});
	// 协议同意状态
	const isAgreed = ref(false);
		const alertAgree=()=>{
		  uni.showToast({
			title: '请先同意用户协议',
			icon:'none'
		  })
		};
	// 一键登录
	const onOneClickLogin = () => {
		const res = checkUniverifyLogin()
		if(res){
			uni.redirectTo({
				url: '/pages/univerify/univerify'
			});
		}else{
			uni.redirectTo({
				url: '/pages_app/smsLogin/smsLogin'
			});
		}
	};

	// 短信验证码登录
	const onSmsLogin = () => {
		
		uni.redirectTo({
			url: '/pages_app/smsLogin/smsLogin'
		});
	};

	// 微信登录
	const onWechatLogin = () => {
		if (!isAgreed.value) {
			uni.showToast({
				title: '请先同意相关协议',
				icon: 'none'
			});
			return;
		}
		
		// #ifdef APP
		uni.showToast({
			title: '微信登录',
			icon: 'none'
		});
		// #endif
		uni.login({
			provider: 'weixin',
			success: function (loginRes) {
				// 登录成功
				uni.getUserInfo({
					provider: 'weixin',
						success: async function(info) {
						// 获取用户信息成功, info.authResult保存用户信息
						
						// #ifdef APP
						uni.showToast({
							title: info.userInfo.nickName,
							icon: 'none'
						});
						// #endif
						const wechat_user_info = {
							openid:info.userInfo.openId,
							unionid:info.userInfo.unionId,
							nickname:info.userInfo.nickName,
						}
						const { postData, sign } = await createSignedPostData({
							wechat_user_info: JSON.stringify(wechat_user_info),
							current_spec: "uniapp"
						})
						 
						// #ifdef APP
						uni.showToast({
							title: sign,
							icon: 'none'
						});
						// #endif

						my_api.expertWxLogin(postData,{
						 	sign:sign
						 }).then(res=>{
							uni.showToast({
								title: '登录成功',
								icon: 'success'
							})

							if (BASE_URL.indexOf('dev') == -1) {
								uni.setStorageSync('AUTH_TOKEN_App',res.data.access_token);
								uni.setStorageSync('AUTH_YX_ACCID_App', res.data.YX_accid);
								uni.setStorageSync('AUTH_YX_TOKEN_App', res.data.YX_token);
								uni.setStorageSync('userInfo', res.data);
								
							} else {
								uni.setStorageSync('DEV_AUTH_TOKEN_App', res.data.access_token);
								uni.setStorageSync('DEV_AUTH_YX_ACCID_App', res.data.YX_accid);
								uni.setStorageSync('DEV_AUTH_YX_TOKEN_App', res.data.YX_token);
								uni.setStorageSync('userInfo', res.data);
							}
							const app = getApp()
							//app.initNim({appkey: "885dea390870814acf3ba8558c717572", account:result.data.YX_accid, token: result.data.YX_token })
							// 跳转到首页
							uni.redirectTo({
								url: '/pages/index/index'
							})
						}).catch(err=>{
							console.log(err)
							uni.showToast({
								title: res.data.msg || '登录失败',
								icon: 'none'
							})
						})
					}
				})
			},
			fail: function (err) {
				// 登录授权失败
				// err.code是错误码
				console.log(err)
				// #ifdef APP
				uni.showToast({
					title: err,
					icon: 'none'
				});
				// #endif
			}
		});
		
	};

	// 切换协议同意状态
	const toggleAgreement = () => {
		isAgreed.value = !isAgreed.value;
	};

	// 查看服务条款
	const onServiceTerms = () => {
		console.log('查看服务条款');
		uni.navigateTo({
			url: '/pages_app/agreement/service-terms'
		});
	};

	// 查看隐私政策
	const onPrivacyPolicy = () => {
		console.log('查看隐私政策');
		uni.navigateTo({
			url: '/pages_app/agreement/privacy-policy'
		});
	};

	// 查看用户协议
	const onUserAgreement = () => {
		console.log('查看用户协议');
		uni.navigateTo({
			url: '/pages_app/agreement/user-agreement'
		});
	};
	const getPhoneNumber = (e) => {
	  if (e.detail.errMsg === "getPhoneNumber:ok") {
	    console.log(e.target.code)
	    auth().then((res) => {
	      console.log(res);
	      api.wxLogin({
	          phone_code: e.target.code,
	          wx_code: res,
	          source:1
	        })
	        .then((data) => {
				uni.hideKeyboard()
	         let result=data.data.data;
	      if(process.env.UNI_PLATFORM =="h5"){
				if(window.location.href.indexOf('//casedata.igandan.com')>-1){
				   uni.setStorageSync("AUTH_TOKEN_CASEDATA",result.token);
				}else{
					 uni.setStorageSync("DEV_AUTH_TOKEN_CASEDATA",result.token);
				}
			}else{
	         const { envVersion } = uni.getAccountInfoSync().miniProgram;
	          if (envVersion == "release") {
	            uni.setStorageSync("AUTH_TOKEN_CASEDATA",result.token);
	          } else {
	            uni.setStorageSync("DEV_AUTH_TOKEN_CASEDATA",result.token);
	          };
	    }
	          
	         
	            uni.setStorageSync("userInfo",{
	            avatar:result.avatar,
	            user_id:result.user_id,
	            status:result.status,
	            user_name:result.user_name,
	            doctor_id:result.doctor_id,
	           });
	          goPage()
	        })
	    });
	  }
	};
	const goPage=()=>{
		uni.redirectTo({
			url:'/pages/index/index'
		})
	}
	
	const univerify = ref(1)
	// 页面加载
	onLoad(() => {
		console.log('登录页面加载完成');
		onLoad((options) => {
			if(options.univerify){
				univerify.value = options.univerify // 已支持 App-Plus
			}
		})
		const res = checkUniverifyLogin()
		if(res){
			uni.redirectTo({
				url: '/pages/univerify/univerify'
			});
		}else{
			uni.redirectTo({
				url: '/pages_app/smsLogin/smsLogin'
			});
		}
	});

	const checkUniverifyLogin=()=>{
		let res = false
		// #ifdef APP
		 uni.getProvider({
			 service: 'oauth',
			 success: function (res) {
				console.log(res.provider)// ['qq', 'univerify']
				if(res.provider.indexOf('univerify') !== -1){
					uni.preLogin({
						provider: 'univerify',
						success(){ //预登录成功
							// 显示一键登录选项
							if(univerify.value == 1){
								return true
							}
						},
						fail(res){ // 预登录失败
							// 不显示一键登录选项（或置灰）
							// 根据错误信息判断失败原因，如有需要可将错误提交给统计服务器
							console.log(res.errCode)
							console.log(res.errMsg)
							return false
						}
					})
				}else{
					return false
				}
			 }
		 });
		// #endif 
		return res
	}
	
	// 页面显示
	onShow(() => {
	  // #ifdef APP
		// uni.login({
		// 	provider: 'univerify',
		// 	univerifyStyle: {
		//     fullScreen: true
		//   }
		// })
	// #endif 
		console.log('登录页面显示');
	});

	// 组件挂载后
	onMounted(() => {
		console.log('登录页面组件已挂载');
	});
</script>

<style>
	.login-container {
		min-height: 100vh;
		background-color: #ffffff;
		display: flex;
		flex-direction: column;
	}

	/* 状态栏 */
	.status-bar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 30rpx;
		height: 60rpx;
	}

	.status-left {
		display: flex;
		align-items: center;
	}

	.signal-bars {
		display: flex;
		align-items: flex-end;
		gap: 2rpx;
	}

	.bar {
		width: 4rpx;
		background-color: #333;
		border-radius: 2rpx;
	}

	.bar:nth-child(1) { height: 8rpx; }
	.bar:nth-child(2) { height: 12rpx; }
	.bar:nth-child(3) { height: 16rpx; }
	.bar:nth-child(4) { height: 20rpx; }

	.status-right {
		display: flex;
		align-items: center;
		gap: 8rpx;
	}

	.battery-text {
		font-size: 24rpx;
		color: #333;
	}

	.battery-icon {
		width: 40rpx;
		height: 20rpx;
		border: 2rpx solid #333;
		border-radius: 4rpx;
		position: relative;
		display: flex;
		align-items: center;
	}

	.battery-level {
		width: 32rpx;
		height: 12rpx;
		background-color: #333;
		margin: 2rpx;
		border-radius: 2rpx;
	}

	.battery-tip {
		position: absolute;
		right: -6rpx;
		top: 50%;
		transform: translateY(-50%);
		width: 4rpx;
		height: 8rpx;
		background-color: #333;
		border-radius: 0 2rpx 2rpx 0;
	}

	.charging-icon {
		font-size: 20rpx;
		color: #333;
	}

	/* 主要内容区域 */
	.main-content {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 100rpx 60rpx 0;
	}

	/* 页面标题 */
	.page-title {
		margin-bottom: 80rpx;
	}

	.title-text {
		font-size: 48rpx;
		font-weight: bold;
		color: #8B2316;
	}

	/* 应用信息 */
	.app-info {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 60rpx;
	}

	.app-icon {
		
		border-radius: 24rpx;
		
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 20rpx;
		position: relative;
		
	}

	.icon-content {
		position: relative;
		width: 80rpx;
		height: 80rpx;
	}

	.liver-shape {
		width: 100%;
		height: 100%;
		background: linear-gradient(135deg, #FF6B35, #FF8C00);
		border-radius: 50% 50% 50% 50% / 60% 60% 40% 40%;
		position: relative;
	}

	.bird-shape {
		position: absolute;
		top: 20rpx;
		left: 25rpx;
		width: 30rpx;
		height: 20rpx;
		background-color: white;
		border-radius: 50% 50% 50% 50% / 60% 60% 40% 40%;
		transform: rotate(-15deg);
	}

	.app-name {
		font-size: 32rpx;
		font-weight: bold;
		color: #8B2316;
	}

	/* 手机号显示 */
	.phone-display {
		margin-bottom: 60rpx;
	}

	.phone-number {
		font-size: 40rpx;
		font-weight: bold;
		color: #333;
	}

	/* 登录按钮 */
	.login-button {
		width: 100%;
		height: 100rpx;
		background-color: #8B2316;
		border-radius: 50rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 40rpx;
		cursor: pointer;
		transition: background-color 0.2s ease;
	}

	.login-button:active {
		background-color: #6B1A0F;
	}

	.button-text {
		font-size: 32rpx;
		color: white;
		font-weight: bold;
	}

	/* 短信验证码登录 */
	.sms-login {
		width:100%;
		margin-bottom: 80rpx;
		cursor: pointer;
	}

	.sms-text {
		font-size: 28rpx;
		color: #8B2316;
	}

	/* 微信登录 */
	.wechat-login {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 20rpx;
		cursor: pointer;
	}

	.wechat-icon {
		
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
	}

	.chat-bubble {
		position: absolute;
		background-color: white;
		border-radius: 50%;
	}

	.chat-bubble-1 {
		width: 16rpx;
		height: 16rpx;
		top: 20rpx;
		left: 20rpx;
	}

	.chat-bubble-2 {
		width: 20rpx;
		height: 20rpx;
		top: 30rpx;
		right: 20rpx;
	}

	.wechat-text {
		font-size: 28rpx;
		color: #8B2316;
	}

	/* 底部协议 */
	.agreement-section {
		padding: 40rpx 60rpx 60rpx;
	}

	.agreement-content {
		display: flex;
		align-items: flex-start;
		gap: 20rpx;
	}

	.checkbox {
		width: 45rpx;
		height:45rpx;
		/* border: 2rpx solid #ccc; */
		border-radius: 50%;
		display: flex;
		/* background-size:cover;
		background: url("@/static/login_new_unselect.png") no-repeat center center; */
		align-items: center;
		justify-content: center;
		flex-shrink: 0;
		margin-top: 4rpx;
		cursor: pointer;
		transition: all  0.3s ease-in-out;
	}

	/* .checkbox.checked {
		background-size:cover;
		background: url("@/static/login_new_select.png") no-repeat center center;
	} */

	.checkbox-inner {
		width: 16rpx;
		height: 16rpx;
		background-color: white;
		border-radius: 50%;
	}

	.agreement-text {
		flex: 1;
		font-size: 24rpx;
		color: #666;
		line-height: 1.6;
	}

	.text-content {
		color: #666;
	}

	.link-text {
		color: #8B2316;
		
	}

	/* 响应式调整 */
	@media (max-width: 750rpx) {
		.main-content {
			padding: 80rpx 40rpx 0;
		}

		.title-text {
			font-size: 44rpx;
		}

		.app-icon {
			width: 100rpx;
			height: 100rpx;
		}

		.phone-number {
			font-size: 36rpx;
		}

		.login-button {
			height: 90rpx;
		}

		.button-text {
			font-size: 30rpx;
		}

		.agreement-section {
			padding: 30rpx 40rpx 50rpx;
		}

		.agreement-text {
			font-size: 22rpx;
		}
	}
</style>

