/** @format */

import {
	LockOutlined,
	MobileOutlined,
	SafetyOutlined,
	UserOutlined,
	WechatOutlined,
} from "@ant-design/icons";
import { CaptFieldRef, ProFormCaptcha, ProFormText } from "@ant-design/pro-components";
import { Alert, Button, ConfigProvider, Form, Image, message, Space, Spin, Tabs } from "antd";
import { useEffect, useRef, useState } from "react";
import logo from "@/assets/images/logo.png";
// import background from '@/assets/images/background.png'
import styles from "./index.module.less";
import { observer } from "mobx-react";
import FooterComponent from "@/components/Footer";
import { createClientId, generateQRCode, getClientToken, getSms, register } from "@/api/user";
import { TinyColor } from "@ctrl/tinycolor";
import { get, load } from "@/api/captcha";
import RotateCaptcha, { CaptchaInstance, type TicketInfoType } from "react-rotate-captcha";
import { useNavigate } from "react-router-dom";
import { setStorage } from "@/utils/localStorage/config.ts";
import useStore from "@/utils/store/useStore.tsx";
import { TimerManager } from "timer-manager-lib";
// import useStore from '@/utils/store/useStore.tsx'
type LoginType = "phone";

export default observer(() => {
	const [form] = Form.useForm();
	const registerCaptcha = useRef<CaptchaInstance>(null);
	const smsCaptcha = useRef<CaptchaInstance>(null);
	const captchaRef = useRef<CaptFieldRef | null | undefined>();
	const [QRCode, setQRCode] = useState<string>("");
	const navigate = useNavigate();
	const store = useStore("user");
	const colors = ["#6253E1", "#04BEFE"];
	const timerManager = new TimerManager();
	const [loading, setLoading] = useState<boolean>(true);

	const getHoverColors = (colors: string[]) =>
		colors.map((color) => new TinyColor(color).lighten(5).toString());
	const getActiveColors = (colors: string[]) =>
		colors.map((color) => new TinyColor(color).darken(5).toString());

	const items = [
		{
			key: "phone",
			label: (
				<span>
					<MobileOutlined />
					手机号注册
				</span>
			),
		},
	];
	const [loginType, setLoginType] = useState<LoginType>("phone");

	async function smsVerify(token: string, deg: number): Promise<TicketInfoType> {
		const phone = form.getFieldValue("phone");
		const data: any = {
			token: token,
			deg: deg,
			phone: phone,
		};
		const res: any = await getSms(data);
		if (res && res.code === 0) {
			message.open({
				content: res.data,
				type: "success",
				duration: 5,
			});
		} else {
			message.open({
				content: res.data,
				type: "warning",
				duration: 5,
			});
		}
		return res;
	}

	async function openRegisterCaptcha() {
		registerCaptcha.current!.open();
	}

	async function openSmsCaptcha() {
		smsCaptcha.current!.open();
	}

	async function registerVerify(token: string, deg: number): Promise<TicketInfoType> {
		const userName = form.getFieldValue("username");
		const password = form.getFieldValue("password");
		const phone = form.getFieldValue("phone");
		const activeCode = form.getFieldValue("activeCode");
		const data: any = {
			token: token,
			deg: deg,
			userName: userName,
			password: password,
			phone: phone,
			activeCode: activeCode,
		};
		const res: any = await register(data);
		if (res && res.success && res.code === 0) {
			message
				.open({
					content: res.data,
					type: "success",
					duration: 5,
				})
				.then(() => {
					navigate("/login");
				});
		} else if (res.code === 0 && !res.success) {
			message.open({
				content: res.data,
				type: "error",
				duration: 5,
			});
		}
		return res;
	}

	async function wechatLogin() {
		createClientId().then((res: any) => {
			generateQRCode(res.data).then((response: any) => {
				if (response.success) {
					setQRCode(response.data.qrCodeUrl);
					setLoading(false);
					timerManager.add(() => {
						getClientToken(res.data).then((result: any) => {
							if (result.success) {
								timerManager.clear();
								store.setToken(result.data.tokenValue);
								store.setUserId(result.data.loginId);
								setStorage("token", result.data.tokenValue, 24 * 60 * 30);
								setStorage("userId", result.data.loginId, 24 * 60 * 30);
								message
									.open({
										content: "登录成功！",
										type: "success",
									})
									.then();
								if (store.getToken() !== null || store.getUserId() !== null) {
									setTimeout(() => {
										navigate("/main");
									}, 2000);
								}
							}
						});
					}, 3000);
				} else {
					message
						.open({
							content: response.data,
							type: "error",
						})
						.then();
				}
			});
		});
	}

	useEffect(() => {
		wechatLogin().then();
	}, []);

	return (
		<div className={styles.container}>
			<RotateCaptcha get={get} load={load} verify={registerVerify} ref={registerCaptcha} />
			<RotateCaptcha get={get} load={load} verify={smsVerify} ref={smsCaptcha} />
			<div className={styles.content}>
				<Space>
					<Space className={styles.login_content}>
						<Space align="center" className={styles.mp_code}>
							<Space direction="vertical" align="center">
								<span className={styles.mp_code_title}>微信扫码登录</span>
								<Spin tip="Loading" size="large" spinning={loading}>
									<Image
										preview={false}
										height={200}
										width={200}
										className={styles.mp_code_img}
										// src={generateMpRegCodeData.data?.qrCodeUrl}
										src={QRCode}
										fallback="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMIAAADDCAYAAADQvc6UAAABRWlDQ1BJQ0MgUHJvZmlsZQAAKJFjYGASSSwoyGFhYGDIzSspCnJ3UoiIjFJgf8LAwSDCIMogwMCcmFxc4BgQ4ANUwgCjUcG3awyMIPqyLsis7PPOq3QdDFcvjV3jOD1boQVTPQrgSkktTgbSf4A4LbmgqISBgTEFyFYuLykAsTuAbJEioKOA7DkgdjqEvQHEToKwj4DVhAQ5A9k3gGyB5IxEoBmML4BsnSQk8XQkNtReEOBxcfXxUQg1Mjc0dyHgXNJBSWpFCYh2zi+oLMpMzyhRcASGUqqCZ16yno6CkYGRAQMDKMwhqj/fAIcloxgHQqxAjIHBEugw5sUIsSQpBobtQPdLciLEVJYzMPBHMDBsayhILEqEO4DxG0txmrERhM29nYGBddr//5/DGRjYNRkY/l7////39v///y4Dmn+LgeHANwDrkl1AuO+pmgAAADhlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAAAwqADAAQAAAABAAAAwwAAAAD9b/HnAAAHlklEQVR4Ae3dP3PTWBSGcbGzM6GCKqlIBRV0dHRJFarQ0eUT8LH4BnRU0NHR0UEFVdIlFRV7TzRksomPY8uykTk/zewQfKw/9znv4yvJynLv4uLiV2dBoDiBf4qP3/ARuCRABEFAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKI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KC4YMA4TAAAAABJRU5ErkJggg=="
									/>
								</Spin>
								<Alert
									// message={(<span>微信扫码<span>关注公众号</span></span>)}
									description={
										<div>
											<span>
												微信扫码
												<span className={styles.mp_tips}>关注公众号</span>
											</span>
											<br />
											登录更快更安全
										</div>
									}
									// type="success"
									showIcon={true}
									className={styles.alert}
									icon={<WechatOutlined />}
								/>
							</Space>
						</Space>
						<Form
							form={form}
							className={styles.login_form}
							initialValues={{
								autoLogin: true,
							}}>
							<Space direction="vertical" align="center">
								<Space className={styles.logo}>
									<img
										alt="logo"
										src={logo}
										style={{ width: "44px", height: "44px" }}
									/>
									<span>五味子云存储</span>
								</Space>
								<div className={styles.subTitle}>随时随地分享你的美好瞬间</div>
							</Space>

							<Tabs
								centered={true}
								items={items}
								activeKey={loginType}
								onChange={(activeKey) =>
									setLoginType(activeKey as LoginType)
								}></Tabs>

							<>
								<ProFormText
									fieldProps={{
										size: "large",
										prefix: <UserOutlined className={"prefixIcon"} />,
										autoComplete: "off",
									}}
									name="username"
									placeholder="请输入用户名"
									rules={[
										{
											required: true,
											message: "请输入用户名！",
										},
										{
											pattern: /^[a-zA-Z0-9_-]{3,16}$/,
											message:
												"用户名只能是3到16位（字母，数字，下划线，减号）",
										},
									]}
								/>

								<ProFormText
									fieldProps={{
										size: "large",
										prefix: <MobileOutlined className={"prefixIcon"} />,
										autoComplete: "off",
									}}
									name="phone"
									placeholder="请输入手机号"
									rules={[
										{
											required: true,
											message: "请输入手机号！",
										},
										{
											pattern: /^1\d{10}$/,
											message: "手机号格式错误！",
										},
									]}
								/>

								<ProFormCaptcha
									fieldProps={{
										size: "large",
										prefix: <SafetyOutlined className={"prefixIcon"} />,
									}}
									captchaProps={{
										size: "large",
									}}
									placeholder={"请输入验证码"}
									captchaTextRender={(timing: boolean, count: number) => {
										if (timing) {
											return `${count} ${"获取验证码"}`;
											// return `${"获取验证码"}`;
										}
										return "获取验证码";
									}}
									name="activeCode"
									phoneName={"phone"}
									countDown={60}
									rules={[
										{
											required: true,
											message: "请输入验证码！",
										},
									]}
									fieldRef={captchaRef}
									onGetCaptcha={async () => {
										await openSmsCaptcha();
									}}
								/>

								<ProFormText.Password
									name="password"
									fieldProps={{
										size: "large",
										prefix: <LockOutlined className={"prefixIcon"} />,
									}}
									placeholder="请输入密码"
									rules={[
										{
											required: true,
											message: "请输入密码！",
										},
										{
											pattern:
												/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z\\W]{6,18}$/,
											message:
												"密码长度需在6~18位字符，且必须包含字母和数字！",
										},
									]}
								/>

								<ProFormText.Password
									name="confirmPassword"
									dependencies={["password"]}
									fieldProps={{
										size: "large",
										prefix: <LockOutlined className={"prefixIcon"} />,
									}}
									placeholder="请再次确认密码"
									rules={[
										{
											required: true,
											message: "请再次确认密码！",
										},
										({ getFieldValue }) => ({
											validator(_, value) {
												if (!value || getFieldValue("password") === value) {
													return Promise.resolve();
												}
												return Promise.reject(
													new Error("两次输入的密码不一致!"),
												);
											},
										}),
									]}
								/>
							</>
							<ConfigProvider
								theme={{
									components: {
										Button: {
											colorPrimary: `linear-gradient(90deg,  ${colors.join(", ")})`,
											colorPrimaryHover: `linear-gradient(90deg, ${getHoverColors(colors).join(", ")})`,
											colorPrimaryActive: `linear-gradient(90deg, ${getActiveColors(colors).join(", ")})`,
											lineWidth: 0,
										},
									},
								}}>
								<Button
									type="primary"
									block
									size="large"
									onClick={async () => {
										const validateFields = [
											"phone",
											"username",
											"password",
											"activeCode",
											"confirmPassword",
										];
										await form
											.validateFields(validateFields)
											.then(async () => {
												await openRegisterCaptcha();
											})
											.catch((error) => {
												console.error(error);
											});
									}}>
									注册
								</Button>
							</ConfigProvider>
						</Form>
						<a href="/login" className={styles.go_to_register}>
							<span>登录</span>
						</a>
					</Space>
				</Space>
			</div>
			<FooterComponent />
		</div>
	);
});
