<template>
	<div class="login-wrapper bglogin">
		<up-navbar title="登录" placeholder>
			<template #left>
<!--        <view-->
<!--            v-if="appStore?.$wxConfig?.auditModeEnabled"-->
<!--            @click="backHome"-->
<!--        >-->
<!--          <image src="@/static/images/tabbar/1-001.png" style="height: 40rpx;width: 40rpx;"></image>-->
<!--        </view>-->
        <view
            class="back_extend"
            v-if="appStore?.$wxConfig?.auditModeEnabled"
            @click="backHome"
        >
          {{ "<" }} 回到首页
        </view>
			</template>
		</up-navbar>
		<div class="shading">
			<view class="">Hello！</view>
			<view class="">欢迎来到水贝搬运工</view>
		</div>
		<div class="whiteBg" v-if="formItem === 1">
			<view class="whiteBg-tab whiteBg-tabimg" :class="{'whiteBg-tabs whiteBg-tabsimg':current == 1}">
				<view @click="current = item.type" :class="{active:current != index,noActive:current == index}" class="whiteBg-tab-li" v-for="(item,index) in navList" :key="index">
					<view class="">{{ item.name }}</view>
				</view>
			</view>
			<div class="list">
				<div class="item">
					<input type="text" maxlength="11" class="texts" placeholder="输入手机号码" v-model="account" required />
				</div>
				<template v-if="current == 0">
					<div class="item">
						<input type="password" class="texts" placeholder="填写登录密码" v-model="password" required />
					</div>
				</template>
				<template v-else-if="current == 1">
					<div class="item">
						<input type="number" placeholder="填写验证码" class="texts" v-model="captcha" maxlength="6" />
						<button class="code" :disabled="disabled" :class="disabled === true ? 'on' : ''" @click="code">
							{{ text }}
						</button>
					</div>
					<div class="item">
						<input type="text" class="texts" placeholder="输入邀请码(非必填)" v-model="inviteCode" />
					</div>
				</template>
				
			</div>
			<div class="privacy-box" @click="aloneChecked = !aloneChecked">
				
				<image v-if="aloneChecked" src="/static/images/select-active@2x.png" mode=""></image>
				<image v-else src="/static/images/select@2x.png" mode=""></image>
				<view class="">我已阅读并同意</view>
				<view class="privacy-text" @click.stop="openPrivacy">《用户协议》</view>
				<view class="privacy-text" @click.stop="openPrivacy">《隐私政策》</view>
			</div>
			<view class="footer">
				<div class="logon" @click="loginMobile" v-if="current !== 0">登录</div>
				<div class="logon" @click="submit" v-if="current === 0">登录</div>
			</view>
		
		</div>
	</div>
</template>

<script setup>
	import {
		ref,
		watch,
		onMounted
	} from "vue";
	import {
		onLoad
	} from "@dcloudio/uni-app";
	import {
		useAppStore
	} from "@/stores/app";
	import {
		loginH5,
		loginMobile as loginMobileApi,
		registerVerify,
		register,
		getUserInfo,
	} from "@/api/user";
	import {
		getLogo,
		appAuth,
		appleLogin
	} from "@/api/public";
	import {
		VUE_APP_API_URL
	} from "@/utils";
	import {
		useSendCode
	} from "@/hooks/useSendCode";
	import Cache from "@/utils/cache";
	import {
		useToast
	} from "@/hooks/useToast.js";
	// import {
	// 	useGoEasy
	// } from "@/plugin/goeasy";
	// import {
	// 	getGroupchatList
	// } from "@/api/customerService";
  import { footprintScan } from "@/api/merchant.js";
	import {
		EXPIRES_TIME
	} from "@/config/cache";
	const appStore = useAppStore();
	const {
		Toast
	} = useToast();
	// const {
	// 	connect,
	// 	GoEasy
	// } = useGoEasy();


	const BACK_URL = "login_back_url";

	// Reactive state
	const navList = ref([{name:"快速登录",type:1}, {name:"账号登录",type:0}]);
	const current = ref(1);
	const account = ref("");
	const inviteCode = ref(""); // 邀请码
	const password = ref("");
	const captcha = ref("");
	const formItem = ref(1);
	const type = ref("login");
	const logoUrl = ref("");
	const keyCode = ref("");
	const codeUrl = ref("");
	const codeVal = ref("");
	
	const platform = ref("");
	
	
	
	
	const appleShow = ref(false);
	const aloneChecked = ref(false);

  const merchantId = ref('');
  const userInfo = ref({});

	// Watch formItem to update type
	watch(formItem, (newVal) => {
		type.value = newVal === 1 ? "login" : "register";
	});

	const {
		disabled,
		text,
		sendCode
	} = useSendCode();
	

	function openPrivacy() {
		void plus.runtime.openWeb("https://www.shuibeibyg.com/shenhe.html");
	}


	// Get logo image
	const getLogoImage = async () => {
		try {
			const res = await getLogo();
			logoUrl.value = res.data.logoUrl || "/static/images/logo2.png";
		} catch (err) {
			console.error(err);
		}
	};

	// 验证码登录
	const loginMobile = async () => {
		if (!account.value)
			return uni.showToast({
				title: "请填写手机号码",
				icon: "none"
			});
		if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(account.value))
			return uni.showToast({
				title: "请输入正确的手机号码",
				icon: "none"
			});
		if (!captcha.value)
			return uni.showToast({
				title: "请填写验证码",
				icon: "none"
			});
		if (!/^[\w\d]+$/i.test(captcha.value))
			return uni.showToast({
				title: "请输入正确的验证码",
				icon: "none"
			});
		if (!aloneChecked.value) {
			return Toast({
				title: "请阅读并同意用户协议和隐私政策",
				icon: "none"
			});
		}
		try {
			const res = await loginMobileApi({
				phone: account.value,
				captcha: captcha.value,
				platformType: "app",
				spread_spid: Cache.get("spread"),
				inviteCode: inviteCode.value,
			});
			// 使用 LOGIN action 保存 token 到缓存
			appStore.LOGIN({
				token: res.data.token
			});
			// 保存过期时间（999天后过期）
			const expiresTime = Math.round(new Date() / 1000) + 999 * 24 * 60 * 60;
			Cache.set(EXPIRES_TIME, expiresTime, 0);
			await getUserInfoFn(res.data);
		} catch (res) {
			const message = typeof res === "object" ? res.message : res;
			uni.showToast({
				title: message,
				icon: "none"
			});
		}
	};

	// 注册
	const registerFn = async () => {
		if (!account.value)
			return uni.showToast({
				title: "请填写手机号码",
				icon: "none"
			});
		if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(account.value))
			return uni.showToast({
				title: "请输入正确的手机号码",
				icon: "none"
			});
		if (!captcha.value)
			return uni.showToast({
				title: "请填写验证码",
				icon: "none"
			});
		if (!/^[\w\d]+$/i.test(captcha.value))
			return uni.showToast({
				title: "请输入正确的验证码",
				icon: "none"
			});
		if (!password.value)
			return uni.showToast({
				title: "请填写密码",
				icon: "none"
			});
		// 正则1：验证长度6-18位
		const lengthReg = /^.{6,18}$/;
		// 正则2：必须包含至少1个数字（\d）和至少1个字母（a-zA-Z）
		const hasNumAndLetterReg = /(?=.*\d)(?=.*[a-zA-Z])/;
		if (!lengthReg.test(password.value)) {
			return uni.showToast({
				title: "密码长度必须为6-18位",
				icon: "none"
			});
		} else if (!hasNumAndLetterReg.test(password.value)) {
			return uni.showToast({
				title: "密码必须同时包含数字和字母",
				icon: "none"
			});
		}
		try {
			const res = await register({
				account: account.value,
				captcha: captcha.value,
				password: password.value,
				spread: Cache.get("spread"),
			});
			uni.showToast({
				title: res.message,
				icon: "none"
			});
			formItem.value = 1;
		} catch (res) {
			uni.showToast({
				title: res.message,
				icon: "none"
			});
		}
	};

	// 发送验证码
	const code = async () => {
		if (!account.value)
			return uni.showToast({
				title: "请填写手机号码",
				icon: "none"
			});
		if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(account.value))
			return uni.showToast({
				title: "请输入正确的手机号码",
				icon: "none"
			});

		if (formItem.value === 2) type.value = "register";
		try {
			const res = await registerVerify(account.value);
			uni.showToast({
				title: res.message,
				icon: "none"
			});
			sendCode();
		} catch (err) {
			uni.showToast({
				title: err.message,
				icon: "none"
			});
		}
	};

	// Navigation tab switch
	const navTap = (index) => {
		current.value = index;
	};

	// 账号密码登录
	const submit = async () => {
		if (!account.value) return Toast({
			title: "请填写账号",
			icon: "none"
		});
		if (!/^[\w\d]{5,16}$/i.test(account.value))
			return Toast({
				title: "请输入正确的账号",
				icon: "none"
			});
		if (!password.value) return Toast({
			title: "请填写密码",
			icon: "none"
		});
		if (!aloneChecked.value) {
			return Toast({
				title: "请阅读并同意用户协议和隐私政策",
				icon: "none"
			});
		}
		try {
			const {
				data
			} = await loginH5({
				account: account.value,
				password: password.value,
				platformType: "app",
				spread: Cache.get("spread"),
			});
			appStore.LOGIN({
				token: data.token
			});
			// 保存过期时间（999天后过期）
			const expiresTime = Math.round(new Date() / 1000) + 999 * 24 * 60 * 60;
			Cache.set(EXPIRES_TIME, expiresTime, 0);

			await getUserInfoFn(data);
		} catch (err) {
			const message = typeof err === "object" ? err.message : err;
			uni.showToast({
				title: message,
				icon: "none",
			});
		}
	};
	// 订阅已加入的群组
	// function getGroupchatListFn(uid) {
	// 	getGroupchatList({
	// 		userId: uid
	// 	}).then((res) => {
	// 		if (res && res.data && res.data.length > 0) {
	// 			//订阅群消息
	// 			var groupIds = res.data;
	// 			GoEasy.im.subscribeGroup({
	// 				groupIds: groupIds,
	// 				onSuccess: function() {
	// 					//订阅成功
	// 					console.log("Group message subscribe successfully.");
	// 				},
	// 				onFailed: function(error) {
	// 					//订阅失败
	// 					console.log(
	// 						"Failed to subscribe group message, code:" +
	// 						error.code +
	// 						" content:" +
	// 						error.content
	// 					);
	// 				},
	// 			});
	// 		}
	// 	});
	// }
	const getUserInfoFn = async (data) => {
		try {
			appStore.SETUID(data.uid);
			const res = await getUserInfo();
			appStore.UPDATE_USERINFO(res.data);
      userInfo.value = res.data;

			// connect({
			// 	id: appStore.uid?.toString(),
			// 	data: {
			// 		avatar: appStore.$userInfo?.avatar,
			// 		nickname: appStore.$userInfo?.nickname,
			// 		phone: appStore.$userInfo?.phone,
			// 		uid: appStore.uid?.toString(),
			// 	},
			// });
			// 订阅已加入的群组
			// await getGroupchatListFn(data.uid);

      if(merchantId.value != ''){
        let obj ={
          merchantId:merchantId.value,
          userId:res.data.userId
        }
        await footprintScanFn(obj)
      }else{
        console.log('============')
        appStore.UPDATE_MERCHANT_ID('')
        Toast({ title: "登录成功" });
        backHome();
      }
		} catch (err) {
			console.error(err);
			uni.showToast({
				title: err.msg,
				icon: "none"
			});
		}
	};
  const backHome = () => {
    if(userInfo.value.merchant && userInfo.value.merchant.id){
      uni.navigateTo({
        url:"/pages/merchantCenter/index"
      })
    }else{
      uni.switchTab({
        url: "/pages/index/index",
      });
    }
  };
  const footprintScanFn =async (data) => {
    const res = await footprintScan(data);
    Toast({ title: "登录成功" });
    backHome();
  }
	onLoad(() => {
    console.log(appStore.$wxConfig)
    merchantId.value = appStore.merchantId || '';
		getLogoImage();
	});

	onMounted(() => {
		uni.getSystemInfo({
			success(res) {
				platform.value = res.platform.toLowerCase();
				if (platform.value === "ios" && res.system.split(" ")[1] >= 13) {
					appleShow.value = true;
				}
			},
		});
	});
</script>

<style lang="scss" scoped>
	::v-deep .u-status-bar {
		background: transparent;
		background-color: transparent !important;
	}
	
	::v-deep .u-navbar__content {
		background: transparent;
		background-color: transparent !important;
	}
	.login-wrapper {
		//background: url('https://sb-admin.oss-cn-shenzhen.aliyuncs.com/shuibei-mini/new-mini/login@2x.png');
		background-repeat: no-repeat;
		background-size: 100% 624rpx;
		background-color: #FFFFFF;
	}
	.appLogin {
		

		.hds {
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 24rpx;
			color: #b4b4b4;

			.line {
				width: 68rpx;
				height: 1rpx;
				background: #cccccc;
			}

			p {
				margin: 0 20rpx;
			}
		}

		.btn-wrapper {
			display: flex;
			align-items: center;
			justify-content: center;
			margin-top: 30rpx;

			.btn {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 68rpx;
				height: 68rpx;
				border-radius: 50%;
			}

			.apple-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				margin-left: 30rpx;
				background: #000;
				border-radius: 34rpx;
				font-size: 40rpx;

				.icon-s-pingguo {
					color: #fff;
					font-size: 40rpx;
				}
			}

			.iconfont {
				font-size: 40rpx;
				color: #fff;
			}

			.wx {
				margin-right: 30rpx;
				background-color: #61c64f;
			}

			.mima {
				background-color: #28b3e9;
			}

			.yanzheng {
				background-color: #f89c23;
			}
		}
	}

	.code img {
		width: 100%;
		height: 100%;
	}

	.acea-row.row-middle {
		input {
			margin-left: 20rpx;
			display: block;
		}
	}

	.login-wrapper {


		.shading {
			padding: 72rpx 78rpx;
			display: flex;
			justify-content: center;
			flex-direction: column;
			view {
				color: #333333;
				font-size: 36rpx;
				font-weight: bold;
				&:first-child {
					font-size: 48rpx;
					margin-bottom: 16rpx;
				}
			}
		}

		.whiteBg {
			margin-top: 100rpx;
			background: #FFFFFF;
			border-radius: 48rpx 48rpx 0rpx 0rpx;
			.whiteBg-tab {
				color: #666666;
				display: flex;
				align-items: center;
				height: 88rpx;
				text-align: center;
				//background: url('https://sb-admin.oss-cn-shenzhen.aliyuncs.com/shuibei-mini/new-mini/logintab1.png');
				background-repeat: no-repeat;
				background-size: cover;
				.active {
					width: 407rpx;
					
					view {
						color: #F8C008;
						font-weight: bold;
						position: relative;
						&::after {
							left: 50%;
							bottom: -12rpx;
							content: '';
							transform: translateX(-50%);
							position: absolute;
							width: 32rpx;
							height: 8rpx;
							background: #F8C008;
							border-radius: 4rpx;
						}
					}
				}
				.noActive {
					flex: 1;
				}
			}
			.whiteBg-tabs {
				//background: url('https://sb-admin.oss-cn-shenzhen.aliyuncs.com/shuibei-mini/new-mini/logintab.png');
				background-repeat: no-repeat;
				background-size: cover;
			}
			.list {
				padding: 0 80rpx;
				margin-top: 120rpx;

				.item {
					display: flex;
					height: 88rpx;
					align-items: center;
					justify-content: space-between;
					padding: 0 8rpx 0 24rpx;
					background: #F9F7F0;
					border-radius: 16rpx;
					margin-bottom: 32rpx;
					.texts {
						flex: 1;
						font-size: 28rpx;
					}
					
					.code {
						padding: 0;
						margin: 0;
						width: 188rpx;
						display: flex;
						align-items: center;
						height: 72rpx;
						justify-content: center;
						background: #FFFFFF;
						border-radius: 16rpx;
						color: #F8C008;
						font-size: 28rpx;
						font-weight: bold;
						border: none;
						&::after {
							width: 0;
							border: none;
						}
					}
				}
			}

			.logon {
				display: flex;
				align-items: center;
				justify-content: center;
				height: 88rpx;
				background-color: #F8C008;
				border-radius: 16rpx;
				color: #333333;
				font-size: 32rpx;
				font-weight: bold;
			}

			
		}

		.privacy-box {
			font-size: 24rpx;
			padding: 0 80rpx;
			display: flex;
			align-items: center;
			
			image {
				width: 28rpx;
				height: 28rpx;
				margin-right: 8rpx;
			}

			.privacy-text {
				color: #F8C008;
				
				vertical-align: top;
			}
		}
	}
	.footer {
		padding: 48rpx 80rpx;
	}
  .back_extend {
    //position: fixed;
    //top: 50px;
    //left: 10px;
    //font-size: 26rpx;
    //color: #999;
  }
</style>
