<template>
	<view class="w-screen h-screen flex flex-col" :style="themeColor()">
		<!-- #ifdef MP-WEIXIN -->
		<view :style="{ height: headerHeight }">
			<top-tabbar :data="param" :scrollBool="topTabarObj.getScrollBool()" class="top-header" />
		</view>
		<!-- #endif -->
		<view class="mx-[60rpx]">
			<view class="pt-[140rpx] text-[44rpx] font-500 text-[#333]">账号密码登录</view>
			<view class="text-[26rpx] text-[#333] leading-[34rpx] mt-[24rpx] mb-[90rpx]"
				@click="redirect({ url: '/app/pages/auth/register', param: { type } })">
				<text>还没有账号,</text>
				<text class="text-primary">去注册</text>
			</view>
			<u-form labelPosition="left" :model="formData" errorType="toast" :rules="rules" ref="formRef">
				<template v-if="type == 'username'">
					<view class="h-[88rpx] flex w-full items-center px-[30rpx] rounded-[40rpx] box-border bg-[#F6F6F6]">
						<u-form-item label="" prop="username" :border-bottom="false">
							<u-input v-model="formData.username" border="none" maxlength="40" placeholder="请输入账号"
								autocomplete="off" class="!bg-transparent" :disabled="real_name_input" fontSize="26rpx"
								placeholderClass="!text-[var(--text-color-light9)] text-[26rpx]" />
						</u-form-item>
					</view>
					<view
						class="h-[88rpx] flex w-full items-center px-[30rpx] rounded-[40rpx] box-border bg-[#F6F6F6] mt-[40rpx]">
						<u-form-item label="" prop="password" :border-bottom="false">
							<u-input v-model="formData.password" border="none" :password="isPassword" maxlength="40"
								placeholder="请输入密码" autocomplete="new-password" class="!bg-transparent"
								:disabled="real_name_input" fontSize="26rpx"
								placeholderClass="!text-[var(--text-color-light9)] text-[26rpx]">
								<template #suffix>
									<view @click="changePassword" v-if="formData.password">
										<u-icon :name="isPassword ? 'eye-off' : 'eye-fill'" color="#b9b9b9"
											size="20"></u-icon>
									</view>
								</template>
							</u-input>
						</u-form-item>
					</view>
				</template>
				<!-- #ifdef MP-WEIXIN -->
				<template v-if="type == 'wx'">
					<!-- 微信登录按钮始终显示 -->
					<button
						class="w-full h-[80rpx] !bg-[var(--primary-color)] text-[26rpx] rounded-[40rpx] leading-[80rpx] font-500 !text-[#fff] !mx-[0]"
						@click="getOpenid">
						微信登录
					</button>
				</template>
				<!-- #endif -->
				<template v-if="type == 'mobile'">
					<view class="h-[88rpx] flex w-full items-center px-[30rpx] rounded-[40rpx] box-border bg-[#F6F6F6]">
						<u-form-item label="" prop="mobile" :border-bottom="false">
							<u-input v-model="formData.username" type="number" maxlength="11" border="none"
								placeholder="请输入手机号" autocomplete="off" class="!bg-transparent"
								:disabled="real_name_input" fontSize="26rpx"
								placeholderClass="!text-[var(--text-color-light9)] text-[26rpx]" />
						</u-form-item>
					</view>
					<view
						class="h-[88rpx] flex w-full items-center px-[30rpx] rounded-[40rpx] box-border bg-[#F6F6F6] mt-[40rpx]">
						<u-form-item label="" prop="mobile_code" :border-bottom="false">
							<u-input v-model="formData.code" type="number" maxlength="4" border="none"
								class="!bg-transparent" fontSize="26rpx" :disabled="real_name_input"
								placeholder="请输入手机验证码" placeholderClass="!text-[var(--text-color-light9)] text-[26rpx]">
								<template #suffix>
									<sms-code v-if="configStore.login.agreement_show" :mobile="formData.username"
										type="login" v-model="formData.mobile_key" :isAgree="isAgree"></sms-code>
									<sms-code v-else :mobile="formData.username" type="login"
										v-model="formData.mobile_key"></sms-code>
								</template>
							</u-input>
						</u-form-item>
					</view>
				</template>
			</u-form>
			<template v-if="type != 'wx'">
				<view
					class="h-[34rpx] text-right text-[24rpx] text-[var(--text-color-light6)] leading-[34rpx] mt-[20rpx]"
					@click="toResetpwd">忘记密码</view>
				<view class="mt-[106rpx]">
					<button
						class="w-full h-[80rpx] !bg-[var(--primary-color)] text-[26rpx] rounded-[40rpx] leading-[80rpx] font-500 !text-[#fff] !mx-[0]"
						loadingText="登录中" @click="handleLogin">
						登录
					</button>
				</view>
			</template>
		</view>
		<view class="footer w-full">
			<view class="text-[26rpx] leading-[36rpx] text-[#666] text-center mb-[30rpx] font-400" @click="setType">
				{{ type == "wx" ? "短信登录" : "其他登录方式" }}
			</view>
			<view class="flex justify-center gap-[40rpx]"> </view>
		</view>

		<!-- 手机号授权弹窗 -->
		<u-popup v-model:show="showPhoneAuthPopup" mode="bottom" border-radius="24" :mask-closeable="false">
			<view class="p-[60rpx] w-[630rpx] bg-white rounded-[24rpx]">
				<view class="text-center text-[32rpx] font-500 text-[#333] mb-[20rpx]">完善手机号</view>
				<view class="text-center text-[26rpx] text-[#666] mb-[40rpx]">
					为保障您的账户安全，请授权绑定手机号
				</view>
				<button
					class="w-full h-[80rpx] !bg-[var(--primary-color)] text-[26rpx] rounded-[40rpx] leading-[80rpx] font-500 !text-[#fff]"
					open-type="getPhoneNumber" @getphonenumber="getphonenumber">
					授权手机号
				</button>
				<view class="text-center text-[26rpx] text-[#999] mt-[30rpx] cursor-pointer"
					@click="showPhoneAuthPopup = false">
					稍后再说
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { usernameLogin, mobileLogin, clientLogin, wxLogin, loginByPhone } from "@/app/api/auth";
import useMemberStore from "@/stores/member";
import useConfigStore from "@/stores/config";
import { useLogin } from "@/hooks/useLogin";
import { t } from "@/locale";
import { redirect, getToken, pxToRpx, isWeixinBrowser } from "@/utils/common";
import { onLoad } from "@dcloudio/uni-app";
import { topTabar } from '@/utils/topTabbar'
import useSystemStore from "@/stores/system";

const systemStore = useSystemStore();
/********* 自定义头部 - start ***********/
const topTabarObj = topTabar();
const param = topTabarObj.setTopTabbarParam({
	title: "",
	topStatusBar: { bgColor: "#fff", textColor: "#333" },
});
/********* 自定义头部 - end ***********/
const headerHeight = computed(() => {
	return Object.keys(systemStore.menuButtonInfo).length
		? pxToRpx(Number(systemStore.menuButtonInfo.height)) +
		pxToRpx(systemStore.menuButtonInfo.top) +
		pxToRpx(8) +
		"rpx"
		: "auto";
});
const real_name_input = ref(true);
const memberStore = useMemberStore();
const configStore = useConfigStore();
const type = ref("");
const isAgree = ref(false);
const isShowQuickLogin = ref(false); // 是否显示快捷登录
const popupRef = ref();
const isPassword = ref(true);
// 修改：使用弹窗控制变量替代原按钮显示变量
const showPhoneAuthPopup = ref(false);
const openId = ref<any>("");

const changePassword = () => {
	isPassword.value = !isPassword.value;
};

const dialogClose = () => {
	popupRef.value.close();
};

const dialogConfirm = () => {
	isAgree.value = true;
	popupRef.value.close();
	handleLogin();
};



onLoad(async (option: any) => {
	// #ifdef H5
	uni.getStorageSync("openid") &&
		Object.assign(formData, { wx_openid: uni.getStorageSync("openid") });
	// #endif

	// #ifdef MP-WEIXIN
	uni.getStorageSync("openid") &&
		Object.assign(formData, { weapp_openid: uni.getStorageSync("openid") });
	// #endif

	type.value = option.type ? option.type : "username";

	// 重置状态：每次进入页面都从微信登录开始
	showPhoneAuthPopup.value = false;
});

const formData = reactive({
	username: "",
	password: "",
	code: "",
	mobile_key: "",
});

// 第一步
const getOpenid = () => {
	uni.login({
		provider: 'weixin',
		success: function (loginRes) {
			wxLogin({ code: loginRes.code, clientId: '428a8310cd442757ae699df5d894f051' })
				.then((res: any) => {
					// 登录成功，应跳转或处理 token
					memberStore.setToken(res.data.accessToken);
					useLogin().handleLoginBack();
				})
				.catch((res: any) => {
					if (res.code == 601) {
						openId.value = res.data.openId;
						showPhoneAuthPopup.value = true;
					}
				});
		},
		fail: function (err) {
			console.error('uni.login 失败:', err);
			uni.showToast({ title: '微信登录失败', icon: 'none' });
		}
	});
}
const getphonenumber = async (res1: any) => {
	if (res1.detail.errMsg == "getPhoneNumber:ok") {
		loginByPhone({ code: res1.detail.code, openId: openId.value, clientId: '428a8310cd442757ae699df5d894f051' })
			.then((res2: any) => {
				memberStore.setToken(res2.data.accessToken);
				useLogin().handleLoginBack();
			}).catch((res2: any) => {
				if (res2.code == 601) {
					redirect({ url: '/app/pages/auth/register' })
				}
			});
	}


	// getPhoneNumber({ code: res1.detail.code })
	// 	.then((res2: any) => {
	// 		if (res2.msg) {

	// 		} else {

	// 		}
	// 	}).catch(() => { });
	// TODO: 后续可在此处理手机号授权逻辑
	// 授权成功后关闭弹窗并继续登录流程
	showPhoneAuthPopup.value = false;
};

onMounted(() => {
	setTimeout(() => {
		real_name_input.value = false;
	}, 800);
});

const agreeChange = () => {
	isAgree.value = !isAgree.value;
};

const setType = () => {
	if (type.value == "username") {
		// #ifndef MP-WEIXIN
		type.value = "mobile";
		// #endif

		// #ifdef MP-WEIXIN
		type.value = "wx";
		// #endif
	} else if ((type.value == "wx")) {
		type.value = "mobile";
	} else {
		type.value = "username";
	}
	// 切换类型时重置状态
	showPhoneAuthPopup.value = false;
};

const loading = ref(false);

const rules = computed(() => {
	return {
		username: [
			{
				type: "string",
				required: true,
				message: "请输入账号",
				trigger: ["blur", "change"],
			},
			{
				validator(rule: any, value: any) {
					return uni.$u.test.mobile(value);
				},
				message: "请输入正确的手机号",
				trigger: ["change", "blur"],
			},
		],
		password: {
			type: "string",
			required: true,
			message: "请输入密码",
			trigger: ["blur", "change"],
		},
	};
});

const formRef: any = ref(null);

const handleLogin = () => {
	formRef.value.validate().then(() => {
		if (loading.value) return;
		let datas: any = {}
		if (type.value == "username") {
			datas.username = formData.username
			datas.password = formData.password
		}
		loading.value = true;
		clientLogin(datas)
			.then((res: any) => {
				memberStore.setToken(res.data.access_token);
				useLogin().handleLoginBack();
			})
			.catch(() => {
				loading.value = false;
			});
	});
};

const toLink = () => {
	const pages = getCurrentPages();
	if (pages.length > 1) {
		const currentPage = pages[pages.length - 2].route;
		if (currentPage == "app/pages/auth/index") {
			uni.navigateBack({ delta: 1 });
		} else {
			redirect({ url: "/app/pages/auth/index", mode: "redirectTo" });
		}
	} else {
		redirect({ url: "/app/pages/auth/index", mode: "redirectTo" });
	}
};

const toResetpwd = () => {
	uni.showToast({ title: "请联系管理员重置密码", icon: "none" });
};
</script>

<style lang="scss" scoped>
:deep(.u-input) {
	background-color: transparent !important;
}

:deep(.u-checkbox) {
	margin: 0 !important;
}

:deep(.u-form-item) {
	flex: 1;

	.u-line {
		display: none;
	}
}

.footer {
	margin-top: 200rpx;
	bottom: 0;
	left: 0;
	right: 0;
	padding-bottom: calc(151rpx + constant(safe-area-inset-bottom));
	padding-bottom: calc(151rpx + env(safe-area-inset-bottom));
}
</style>