<template>
	<view class="w-screen h-screen flex flex-col" :style="themeColor()">
		<view class="mx-[60rpx]">
			<view class="pt-[140rpx] text-[44rpx] font-500 text-[#333]">账号注册</view>
			<view class="flex items-center justify-between mt-[24rpx] mb-[90rpx]">
				<view class="text-[26rpx] text-[#333] leading-[34rpx]" @click="toLink">
					<text>已有账号,</text>
					<text class="text-primary">去登录</text>
				</view>
			</view>
			<u-form labelPosition="left" :model="formData" errorType="toast" :rules="rules" ref="formRef">
				<view class="h-[88rpx] flex w-full items-center px-[30rpx] rounded-[40rpx] box-border bg-[#F6F6F6]">
					<u-form-item label="" prop="purchaseName" :border-bottom="false">
						<u-input v-model="formData.purchaseName" border="none" maxlength="40" placeholder="请输入姓名"
							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="customerName" :border-bottom="false">
						<u-input v-model="formData.customerName" border="none" maxlength="40" placeholder="请输入企业全称"
							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="purchasePhone" :border-bottom="false">
						<u-input v-model="formData.purchasePhone" border="none" maxlength="11" placeholder="请输入手机号"
							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="code" :border-bottom="false">
						<u-input v-model="formData.code" border="none" maxlength="40" placeholder="请输入验证码"
							class="!bg-transparent" :disabled="real_name_input" fontSize="26rpx"
							placeholderClass="!text-[var(--text-color-light9)] text-[26rpx]">
							<template #suffix>
								<up-code ref="uCodeRef" @change="codeChange" seconds="60" changeText="X秒重新获取"></up-code>
								<up-button class="!bg-[var(--primary-color)] !text-[#fff]" @tap="getCode" :text="tips"
									size="mini"></up-button>
							</template></u-input>
					</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="请输入密码" 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>
				<view
					class="h-[88rpx] flex w-full items-center px-[30rpx] rounded-[40rpx] box-border bg-[#F6F6F6] mt-[40rpx]">
					<u-form-item label="" prop="confirmPassword" :border-bottom="false">
						<u-input v-model="formData.confirmPassword" border="none" :password="isConfirmPassword"
							maxlength="40" placeholder="请再次输入密码" class="!bg-transparent" :disabled="real_name_input"
							fontSize="26rpx" placeholderClass="!text-[var(--text-color-light9)] text-[26rpx]">
							<template #suffix>
								<view @click="changeConfirmPassword" v-if="formData.confirmPassword">
									<u-icon :name="isConfirmPassword ? 'eye-off' : 'eye-fill'" color="#b9b9b9"
										size="20"></u-icon>
								</view>
							</template>
						</u-input>
					</u-form-item>
				</view>
			</u-form>
			<view class="mt-[140rpx]">
				<button
					class="w-full h-[80rpx] !bg-[var(--primary-color)] text-[26rpx] rounded-[40rpx] leading-[80rpx] font-500 !text-[#fff]"
					@click="handleRegister">
					注册
				</button>
				<view class="flex items-center mt-[10rpx] mb-[40rpx] py-[14rpx]" @click.stop="agreeChange">
					<u-checkbox-group @change="agreeChange">
						<u-checkbox activeColor="var(--primary-color)" :checked="isAgree" shape="circle" size="24rpx" />
					</u-checkbox-group>
					<view
						class="text-[24rpx] -ml-[4rpx] text-[var(--text-color-light6)] flex items-center flex-wrap leading-[30rpx]">
						<text>我已阅读并同意</text>
						<text @click.stop="
							redirect({ url: '/app/pages/auth/agreement?key=privacy' })
							" class="text-primary">《用户服务协议》</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { usernameRegister, mobileRegister, registerMiniCustomer, getOpenId } from "@/app/api/auth";
import useMemberStore from "@/stores/member";
import useConfigStore from "@/stores/config";
import { t } from "@/locale";
import { redirect, getToken, pxToRpx } from "@/utils/common";
import { onLoad } from "@dcloudio/uni-app";
import { smsCode } from '@/app/api/system'

const formData = reactive({
	purchaseName: "",
	customerName: "",
	purchasePhone: "",
	code: "",
	password: "",
	confirmPassword: "",
	openId: "",
	registerSource: ""
});

onLoad(async (option: any) => {
	// #ifdef MP-WEIXIN
	formData.registerSource = '2'
	// #endif
});

const loading = ref(false)
const real_name_input = ref(true);
onMounted(() => {
	// 防止浏览器自动填充
	setTimeout(() => {
		real_name_input.value = false;
	}, 800);
});
const isPassword = ref(true);
const isConfirmPassword = ref(true);
const changePassword = () => {
	isPassword.value = !isPassword.value;
};

const changeConfirmPassword = () => {
	isConfirmPassword.value = !isConfirmPassword.value;
};
const configStore = useConfigStore();

const tips = ref('');
const uCodeRef = ref<any>(null);
// 获取验证码
const codeChange = (text: any) => {
	tips.value = text;
};
const getCode = () => {
	if (uCodeRef.value.canGetCode) {
		// 模拟向后端请求验证码
		uni.showLoading({
			title: '正在获取验证码',
		});
		smsCode({ phonenumber: formData.purchasePhone }).then((res: any) => {
			if (res.code == 200) {
				uni.hideLoading();
				// 这里此提示会被start()方法中的提示覆盖
				uni.$u.toast('验证码已发送');
				// 通知验证码组件内部开始倒计时
				uCodeRef.value.start();
			}
		}).catch(() => {
			uni.hideLoading();
		});
	} else {
		uni.$u.toast('倒计时结束后再发送');
	}
};

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

const rules = computed(() => {
	return {
		purchaseName: [
			{
				type: "string",
				required: true,
				message: '请输入姓名',
				trigger: ["blur", "change"],
			}
		],
		customerName: [
			{
				type: "string",
				required: true,
				message: '请输入企业全称',
				trigger: ["blur", "change"],
			}
		],
		purchasePhone: [
			{
				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"],
		},
		confirmPassword: [
			{
				type: "string",
				required: true,
				message: "请再次输入密码",
				trigger: ["blur", "change"],
			},
			{
				validator(rule: any, value: any) {
					return value == formData.password;
				},
				message: "两次输入的密码不一致",
				trigger: ["change", "blur"],
			},
		],

		code: {
			type: "string",
			required: true,
			message: "请输入验证码",
			trigger: ["blur", "change"],
		}
	};
});

const isAgree = ref(false);
const formRef: any = ref(null)
const handleRegister = () => {
	formRef.value.validate().then(() => {
		if (!isAgree.value) {
			uni.$u.toast('请勾选并阅读用户协议');
			return false;
		}
		if (loading.value) return;
		loading.value = true;

		// #ifdef MP-WEIXIN
		uni.login({
			provider: 'weixin',
			success: function (loginRes) {
				getOpenId({ code: loginRes.code })
					.then((res1: any) => {
						if (res1.msg) {
							formData.openId = res1.msg
							registerMiniCustomer(formData).then((res: any) => {
								if (res.code == 200) {
									redirect({ url: '/app/pages/auth/login', mode: 'redirectTo' })
								}
							}).catch(() => { loading.value = false; });
						}
					}).catch((res: any) => { });
			},
			fail: function (err) {
				uni.showToast({ title: '微信注册失败', icon: 'none' });
			}
		});
		// #endif

		// #ifndef MP-WEIXIN
		registerMiniCustomer(formData).then((res: any) => {
			if (res.code == 200) {
				redirect({ url: '/app/pages/auth/login', mode: 'redirectTo' })
			}
		}).catch(() => { loading.value = false; });
		// #endif

	});
};
const toLink = () => {
	const pages = getCurrentPages(); // 获取页面栈
	if (pages.length > 1) {
		const currentPage = pages[pages.length - 2].route;
		if (currentPage == "app/pages/auth/login") {
			// 返回上一页
			uni.navigateBack({
				delta: 1, // 默认值是1，表示返回的页面层数
			});
		} else {
			redirect({ url: "/app/pages/auth/login", mode: "redirectTo" });
		}
	} else {
		redirect({ url: "/app/pages/auth/login", mode: "redirectTo" });
	}
};
</script>

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

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

	.u-line {
		display: none;
	}

	.u-input__content__subfix-icon {
		display: flex;
		align-items: center;
	}
}

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

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