<template>
	<view class="ezy-login-page">
		<icon class="login-img"></icon>
		<!-- 手机号 -->
		<view class="login-body-box">
			<view class="phone-input-box">
				<view class="phone-prefix">+86</view>
				<input class="phone-input" type="text" v-model="indexData.phoneNumber" placeholder="请输入手机号"
					maxlength="11" @input="clearTelInput" />
				<view class="close-btn" v-if="indexData.clearTelIcon" @click="clearTel"></view>
			</view>
			<!-- 协议勾选框和按钮 -->
			<view class="agreement-checkbox-box">
				<checkbox-group @change="handleAgreementChange">
					<checkbox class="agreement-checkbox-input" color="#FFFFFF" value="agree"
						:checked="indexData.isAgreed" />
				</checkbox-group>
				<view class="agreement-text-box">
					我已阅读并同意<view class="agreement-text" @click="agreeBtn('yhxy')">《用户协议》</view>和<view
						@click="agreeBtn('ystk')" class="agreement-text">《隐私政策》</view>
				</view>
			</view>
			<ezyActiveVue class="ezy-btn-active login-btn" @aclick="getYzmBtn" :class="indexData.telStatus">发送验证码
			</ezyActiveVue>
			<view class="bottom-btn-box">
				<view class="bottom-tip">其他登录方式</view>
				<view class="btn-box">
					<!-- 		<view v-if="wxFlag" class="wx-btn" @click="wxLoginClick">
						<icon></icon>
						<view>微信登录</view>
					</view> -->
					<view class="yk-btn" @click="ykBtn">
						<icon></icon>
						<view>游客登录</view>
					</view>
					<!-- 	<view class="apple-btn" v-if="showAppleLogin" @click="appleLoginClick">
						<icon></icon>
						<view>苹果登录</view>
					</view> -->
				</view>
			</view>
		</view>
		<agree-content-dialog ref="agreeContentDialogRef" :agreeType="agreeType"></agree-content-dialog>
		<agree-dialog ref="agreeDialogRef" @confirm-btn="confirmBtn"></agree-dialog>
		<agree-dialog ref="agreeYkDialog" @confirm-btn="ykConfirmBtn"></agree-dialog>
		<agree-dialog ref="agreeWxDialog" @confirm-btn="wxConfirmBtn"></agree-dialog>
		<tel-dialog ref="telDialogRef" @telClose="telClose" @bindBtn="bindBtn" v-if="telDialogFlag"></tel-dialog>
		<tipMiddleDialog ref="tipDialogRef" :closeFlag='false' :title="tipTitle" @confirm-btn="BanbenConfirmBtn"
			:notClose="true" :content="tipContent"></tipMiddleDialog>
		<tipMiddleDialog ref="tipDialogRef2" :closeFlag='false' :title="tipTitle" @confirm-btn="BanbenConfirmBtn"
			:showTip="true" :notClose="true" :content="tipContentAndroid">
		</tipMiddleDialog>
	</view>
</template>

<script setup>
	import {
		ref,
		nextTick,
		reactive
	} from "vue"
	import {
		onLoad,
		onReady,
		onBackPress
	} from '@dcloudio/uni-app';
	import agreeContentDialog from './agreeContentDialog.vue';
	import agreeDialog from './agreeDialog.vue'
	import {
		wxLogin,
		getVersion,
		youkeLogin
	} from "@/api/login.js"
	import {
		toast,
		getUserIdentity
	} from "@/utils/common";
	import telDialog from './telDialog.vue'
	import cacheManager from "@/utils/cacheManager.js";
	import config from '../../config.js'
	import {
		error
	} from "uview-plus";
	import ezyActiveVue from "@/components/ezyActive/ezyActive.vue";
	import tipMiddleDialog from '@/components/dialog/tipMiddleDialog.vue';
	import {
		useVersionUpdate
	} from "@/utils/versionUpdate.js";

	let indexData = reactive({
		phoneNumber: null,
		clearTelIcon: false,
		telStatus: 'login-btn-disabled',
		isAgreed: false,
		sliderObj: {},
	})
	const agreeContentDialogRef = ref(null);
	const agreeType = ref(null);
	const agreeDialogRef = ref(null);
	const agreeYkDialog = ref(null);
	const agreeWxDialog = ref(null);
	const telDialogRef = ref(null);
	let telDialogFlag = ref(false);
	let showAppleLogin = ref(false);
	let wxFlag = ref(true);

	const version = config.appInfo.version;
	const tipDialogRef = ref(null);
	const uuid = ref(null);
	const tipTitle = '升级提醒';
	const tipContentAndroid = '您的APP不是最新版本，部分功能不能使用，请升级至最新版本！'
	const tipContent = '您的APP不是最新版本，部分功能不能使用，请升级至最新版本！'
	const tipDialogRef2 = ref(null)
	const updateUrl = ref(null)
	const {
		initDownload
	} = useVersionUpdate()

	onLoad((options) => {
		/* 设备信息打印
		const info = uni.getSystemInfoSync()
		console.log('窗口宽度（逻辑像素）:', info.windowWidth)
		console.log('设备像素比 DPR:', info.pixelRatio)
		console.log('物理分辨率宽:', info.windowWidth * info.pixelRatio) */
		showAppleLogin.value = isIOS13OrAbove();
		getLoginInit()
		getUUid()
		getUUid2()
		if (plus.runtime.isApplicationExist({
				pname: 'com.tencent.mm',
				action: 'weixin://'
			})) {
			console.log('111', "已安装微信");
			wxFlag.value = true
		} else {
			wxFlag.value = false
		}
		console.log('showAppleLogin.value', showAppleLogin.value);

	})

	function BanbenConfirmBtn() {
		const systemInfo = uni.getSystemInfoSync();
		if (systemInfo.platform == 'ios') {
			const appStoreUrl = 'itms-apps://itunes.apple.com/app/6741551741'
			plus.runtime.openURL(appStoreUrl)
		} else {
			initDownload(updateUrl.value)
		}
	}

	function getLoginInit() {
		const systemInfo = uni.getSystemInfoSync();
		getVersion({}).then(res => {
			if (version != res.data.version) {
				updateUrl.value = res.data.updateUrl

				if (systemInfo.platform == 'ios') {
					tipDialogRef.value.handleShow();
				} else {
					tipDialogRef2.value.handleShow();
				}
			}
		})
	}
	const getYzmBtn = () => {
		if (indexData.telStatus === 'login-btn-normal') {
			if (indexData.isAgreed === true) {
				uni.redirectTo({
					url: `/pages/login/login?telNum=${indexData.phoneNumber}`
				})
			} else {
				agreeDialogRef.value.handleShow();
			}
		}
	}
	const isIOS13OrAbove = () => {
		const systemInfo = uni.getSystemInfoSync();
		if (systemInfo.platform == 'ios') {
			const version = systemInfo.system.split(' ')[1].split('.');
			const majorVersion = parseInt(version[0], 10);
			return majorVersion >= 13;
		}
		return false;
	}
	// 用户协议同意
	const confirmBtn = () => {
		indexData.isAgreed = true;
		getYzmBtn();
	}
	const telClose = () => {
		telDialogFlag.value = false;
	}
	const bindBtn = (res) => {
		telDialogFlag.value = false;
		if (res.cardId == 0) {
			uni.redirectTo({
				url: `/pages/selectGradesTerms/index`
			})
		} else {
			uni.redirectTo({
				url: `/pages/study/index`
			})
		}
	}

	const ykConfirmBtn = () => {
		indexData.isAgreed = true;
		ykBtn()
		// uni.redirectTo({
		// 	url: `/pages/selectGradesTerms/index`
		// })
	}

	const wxConfirmBtn = () => {
		wxLoginFun();
	}

	// 手机号校验规则
	const validatePhoneNumber = (value) => {
		const phoneRegex = /^1[3-9]\d{9}$/;
		if (phoneRegex.test(value)) {
			indexData.telStatus = 'login-btn-normal';
		} else {
			indexData.telStatus = 'login-btn-disabled';
		}
	}

	const clearTelInput = (event) => {
		if (event.detail.value.length > 0) {
			indexData.clearTelIcon = true;
			validatePhoneNumber(event.detail.value);
		} else {
			indexData.clearTelIcon = false;
		}
	}

	const clearTel = () => {
		indexData.phoneNumber = '';
		indexData.telStatus = 'login-btn-disabled';
		indexData.clearTelIcon = false;
	}

	const agreeBtn = (data) => {
		if (data === 'yhxy') {
			agreeType.value = 'yhxy'
		} else {
			agreeType.value = 'ystk'
		}
		agreeContentDialogRef.value.handleShow();
	};
	const getUUid = (data) => {
    plus.device.getInfo({
      success: (res) => {
        // res.uuid 是设备的 UUID（iOS 下为 identifierForVendor）
        console.log('res', res);
        uuid.value = res.uuid;
        console.log('iOS 设备 UUID：', uuid.value);
      },
      fail: (err) => {
        console.error('获取设备信息失败：', err);
      }
    });
	};
	
	const getUUid2 = (data) => {
    plus.device.getOAID({
      success: (res) => {
        // res.uuid 是设备的 UUID（iOS 下为 identifierForVendor）
        console.log('res', res);
        uuid.value = res.uuid;
        console.log('iOS 设备 UUID：', uuid.value);
      },
      fail: (err) => {
        console.error('获取设备信息失败：', err);
      }
    });
	};

	const handleAgreementChange = (event) => {
		if (event.detail.value[0] === 'agree') {
			indexData.isAgreed = true;
		} else {
			indexData.isAgreed = false;
		}
	}
	// 游客登录
	const ykBtn = () => {
		const systemInfo = uni.getSystemInfoSync();
		if (indexData.isAgreed === true) {

			if (!uuid.value) {
				toast("设备id丢失")
				getUUid()
				return false
			}
			let req = {
				uuid: uuid.value
			}
			youkeLogin(req).then(res => {
				if (res.code == 0) {
					cacheManager.set('auth', res.data)
					uni.switchTab({
						url: `/pages/chanpinXuanze/index`
					})
				}
			})



			// uni.redirectTo({
			// 	url: `/pages/selectGradesTerms/index`
			// })
		} else {
			agreeYkDialog.value.handleShow();
		}
	}
	const appleLoginClick = () => {
		uni.login({
			provider: 'apple',
			success: function(loginRes) {
				console.log('loginRes', loginRes);
				let req = {
					"apple": true,
					"code": loginRes.appleInfo.user
				}
				console.log(req);
				console.log(req);
				wxLogin(req).then(res => {
					console.log(res);
					if (!res.data.bind) {
						console.log('未绑定');
						cacheManager.set('wxLogin', {
							bind: res.data.bing
						})
						telDialogFlag.value = true;
						nextTick(() => {
							telDialogRef.value.getOpenId(res.data.openId);
						})
					} else {
						uni.showLoading({
							title: '登录中'
						});
						setTimeout(() => {
							cacheManager.set('auth', res.data.loginVo)
							if (res.data.loginVo.subjectId == 0 && res.data.loginVo
								.levelId == 0) {

								uni.redirectTo({
									url: `/pages/selectGradesTerms/index`
								})
								uni.hideLoading();
							} else {

								uni.redirectTo({
									url: `/pages/study/index`
								})
								uni.hideLoading();
							}
						}, 1000)
					}
				}).catch((error) => {
					console.log(error);
				})
			},
			fail: function(err) {
				console.log('err.code', err.code);
				// 登录授权失败
				// err.code错误码参考`授权失败错误码(code)说明`
			}
		});
	}


	// 游客登录
	const wxLoginClick = () => {
		if (indexData.isAgreed === true) {
			wxLoginFun();
		} else {
			agreeWxDialog.value.handleShow();
		}
	}

	const wxLoginFun = () => {
		//获取服务商信息判断手机端是否安装了app
		// uni.getProvider({
		// 	service: 'oauth',// oauth  代表授权登录
		// 	success: function (res) {
		// 	  // 登录
		// 	  uni.login({
		// 		  // 表示授权方式  如果不设置则弹出登录列表选择界面
		// 		  provider: 'weixin',
		// 		 	"onlyAuthorize": true, // 微信登录仅请求授权认证
		// 		  success: function (loginRes) {
		// 			  		console.log('loginRes',loginRes); 

		// 		  }
		// 	  });
		//    }
		// });

		if (plus.runtime.isApplicationExist({
				pname: 'com.tencent.mm',
				action: 'weixin://'
			})) {
			console.log('111', "已安装微信");
			uni.login({
				"provider": "weixin",
				"onlyAuthorize": true, // 微信登录仅请求授权认证
				success: function(event) {
					console.log(event);
					const {
						code
					} = event
					//客户端成功获取授权临时票据（code）,向业务服务器发起登录请求。
					let req = {
						"apple": false,
						"code": code
					}
					console.log(req);
					wxLogin(req).then(res => {
						console.log(res);
						if (!res.data.bind) {
							console.log('未绑定');
							cacheManager.set('wxLogin', {
								bind: res.data.bing
							})
							telDialogFlag.value = true;
							nextTick(() => {
								telDialogRef.value.getOpenId(res.data.openId);
							})
						} else {
							uni.showLoading({
								title: '登录中'
							});
							setTimeout(() => {
								cacheManager.set('auth', res.data.loginVo)
								if (res.data.loginVo.subjectId == 0 && res.data.loginVo
									.levelId == 0) {

									uni.redirectTo({
										url: `/pages/selectGradesTerms/index`
									})
									uni.hideLoading();
								} else {

									uni.redirectTo({
										url: `/pages/study/index`
									})
									uni.hideLoading();
								}
							}, 1000)
						}
					}).catch((error) => {
						console.log(error);
					})
				},
				fail: function(err) {
					console.log(err);
					// 登录授权失败
					// err.code是错误码
				}
			})
		} else {
			toast("请重启应用重试")
			return false
		}
	}
</script>