import React, { useEffect, useState } from 'react';
import { ReloadOutlined } from '@ant-design/icons';
import { Button, Checkbox, Form, Input, message, Modal } from 'antd';
import Cookies from 'js-cookie';
import { useRouter } from 'next/router';
import { useDispatch, useSelector } from 'react-redux';
import styled from 'styled-components';
import { CommonAPI } from '@/api';
import { RootState } from '@/store';
import { GlobalDataState } from '@/store/module/globalData';
import { setSystem } from '@/store/module/system';
import { setUserInfo } from '@/store/module/userInfo';

// 定时器暂存
let timer: NodeJS.Timer;

const LoginModalView = ({
  open,
  onCancel,
}: {
  open: boolean;
  onCancel: () => void;
}) => {
  // 路由钩子
  const router = useRouter();
  // system
  const globalData = useSelector(
    (state: RootState) => state.globalData,
  ) as GlobalDataState;
  // store
  const dispatch = useDispatch();
  // 表单钩子
  const [formRef] = Form.useForm<{
    password: string;
    username: string;
  }>();
  // 是否选择协议
  const [checkValue, setCheckValue] = useState<boolean>(false);
  // 获取小程序二维码唯一标识
  const [randomLoginCode, setRandomLoginCode] = useState<string>(
    `${parseInt(String(Math.random() * 10001), 10)}`,
  );
  // 二维码是否过期
  const [qrCodeExpired, setQrCodeExpired] = useState<boolean>(false);
  // 登录二维码的地址
  const [qrCodeData, setQrCodeData] = useState<string>();
  // 获取登录二维码
  const getQrcodeLogin = async () => {
    // 获取二维码
    const res = await CommonAPI.getAppletQRCode({
      page: 'page-identity/identity-empower/index',
      scene: `randomLoginCode=${randomLoginCode}&port=0`,
    });
    if (res && res.code === '200') {
      if (!res.result) {
        message.warning('获取登录二维码失败');
        return;
      }
      // 设置当前登录的二维码
      setQrCodeData(`data:image/png;base64,${res.result}`);
      // 设置二维码倒计时
      setQrCodeExpiredTimer();
    }
  };
  // 跳转管理平台
  const handleBackEnd = () => {
    window.open('https://admin.iuav.com');
  };
  // 刷新二维码
  const handleRefresh = () => {
    setRandomLoginCode(`${parseInt(String(Math.random() * 10001), 10)}`);
    getQrcodeLogin().then(() => {
      setQrCodeExpired(false);
    });
  };
  // 定时器设置二维码过期
  const setQrCodeExpiredTimer = () => {
    setTimeout(
      () => {
        setQrCodeExpired(true);
        // 关闭定时器
        if (timer) clearInterval(timer);
      },
      1000 * 60 * 5,
    );
  };
  // 获取登录信息
  const getLoginInfo = async () => {
    if (!randomLoginCode) return;
    const res = await CommonAPI.getLoginInfo({
      randomLoginCode,
    });
    // console.log('获取登录信息 --->', res);
    if (res && res.code === '200') {
      // 关闭定时器
      if (timer) clearInterval(timer);
      // 刷新二维码
      setQrCodeExpired(true);
      // 关闭弹窗
      onCancel?.();
      // 设置用户信息
      dispatch(setUserInfo(res.result));
      // 设置token
      dispatch(setSystem({ token: res.result.token }));
      // 设置token
      Cookies.set('SHAREFLY-WEB-TOKEN', res.result.token);
      message.success('登录成功');
      // 刷新当前页面
      window.location.reload();
    }
  };
  // 设置定时器轮询获取信息
  const setLoginInfoTimer = () => {
    timer = setInterval(async () => {
      await getLoginInfo();
    }, 2500);
  };
  // 关闭弹窗
  const handleClose = () => {
    onCancel?.();
    // 关闭定时器
    if (timer) clearInterval(timer);
  };
  // 提交数据
  const handleSubmit = async () => {
    if (!checkValue) {
      await message.warning('请先阅读并接受用户协议和隐私协议');
      return;
    }
    const valid = await formRef.validateFields().catch((err) => {
      Promise.all(
        err?.errorFields?.map((i: { errors: string[] }) =>
          message.warning(i?.errors[0]),
        ),
      );
    });
    if (!valid) return;
    if (valid?.password !== '123456') {
      await message.warning('密码错误');
      return;
    }
    // 获取token
    const res = await CommonAPI.testPhoneLogin({
      phone: valid?.username,
    });
    if (res && res.code === '200') {
      handleClose();
      // 设置用户信息
      dispatch(setUserInfo(res.result));
      // 设置token
      dispatch(setSystem({ token: res.result.token }));
      // 设置token
      Cookies.set('SHAREFLY-WEB-TOKEN', res.result.token);
      message.success('登录成功');
      // 刷新当前页面
      window.location.reload();
    }
  };
  // 跳转注册页面
  const handleSignup = async () => {
    await router.push('/user/signup');
    handleClose();
  };
  // 组件挂载
  useEffect(() => {
    if (!open) {
      // 关闭定时器
      if (timer) clearInterval(timer);
      return;
    }
    // 获取二维码
    getQrcodeLogin().then(() => {
      setQrCodeExpired(false);
      setLoginInfoTimer();
    });
  }, [open]);
  return (
    <Modal open={open} footer={null} onCancel={handleClose} width={720}>
      <LoginModalWrap>
        {/* 扫描二维码 */}
        <div className="qrcode-box flex-start relative w-1/2 flex-col">
          <div className="title">
            {globalData?.loginModalTitle || `云享飞登录`}
          </div>
          <div className="qrcode">
            {qrCodeData && (
              <img src={qrCodeData} alt="登录二维码" className="image" />
            )}
            {qrCodeExpired && (
              <div className="flex-center animate__animated animate__fast animate__fadeIn shadow">
                <div className="refresh flex-center" onClick={handleRefresh}>
                  <ReloadOutlined style={{ fontSize: '20px' }} />
                </div>
                <div className="text">二维码已过期，请重新扫描</div>
              </div>
            )}
          </div>
          <div className="text">微信扫一扫，打开小程序</div>
          <div className="text">即可登录/注册</div>
          <div
            className="action"
            onClick={handleBackEnd}
            style={{ visibility: 'hidden' }}
          >
            管理平台登录 {'>'}
          </div>
        </div>
        <div className="login-box flex-start relative w-1/2 flex-col">
          <div className="title">账号登录</div>
          <Form
            name="loginForm"
            form={formRef}
            autoComplete="off"
            className="w-full"
            size="large"
          >
            <Form.Item
              name="username"
              rules={[{ required: true, message: '请输入登录的账号' }]}
            >
              <Input placeholder="请输入手机号" maxLength={11} allowClear />
            </Form.Item>
            <Form.Item
              name="password"
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <Input
                placeholder="请输入密码"
                type="password"
                maxLength={20}
                allowClear
              />
            </Form.Item>
          </Form>
          <div className="forget flex w-full justify-end">
            <Button className="action" type="link">
              忘记密码
            </Button>
          </div>
          <div
            className={`submit cursor-pointer ${checkValue && 'active'}`}
            onClick={handleSubmit}
          >
            登录
          </div>
          <div className="checkbox mt-4">
            <Checkbox
              checked={checkValue}
              onChange={(e) => setCheckValue(e.target?.checked)}
            >
              <span>阅读并接受</span>
              <span className="bold cursor-pointer">云享飞用户协议</span>
              <span>和</span>
              <span className="bold cursor-pointer">隐私协议</span>
            </Checkbox>
          </div>
          <div className="signup">
            <Button className="action" type="link" onClick={handleSignup}>
              没有账号？立即注册
            </Button>
          </div>
        </div>
      </LoginModalWrap>
    </Modal>
  );
};

export default LoginModalView;
export const LoginModalWrap = styled.div`
  position: relative;
  box-sizing: border-box;
  width: 100%;
  display: flex;
  flex-wrap: nowrap;
  justify-content: space-between;
  &::after {
    position: absolute;
    content: '';
    left: 50%;
    top: calc((100% - 15.38rem) / 2);
    width: 0.02rem;
    height: 15.38rem;
    background: #e0e0e0;
  }
  .qrcode-box {
    .title {
      position: absolute;
      top: 0;
      left: 0;
      color: #222;
      font-size: 16px;
      font-weight: bold;
    }
    .qrcode {
      position: relative;
      width: 9.68rem;
      height: 9.68rem;
      margin: 3.5rem 0 1rem 0;
      //background-image: url('https://file.iuav.com/file/sharefly-qrcode-wx.jpg');
      //background-size: 100% 100%;
      //background-size: cover;
      //background-position: center;
      .image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      .shadow {
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        flex-direction: column;
        background: rgba(0, 0, 0, 0.68);
        .refresh {
          position: relative;
          width: 3rem;
          height: 3rem;
          border-radius: 50%;
          background: #fff;
          margin-bottom: 1rem;
          &:active {
            filter: brightness(0.9);
            transform: rotate(360deg);
            transition: all 0.3s ease-in-out;
          }
        }
        .text {
          color: #fff;
        }
      }
    }
    .action {
      color: #999;
      font-size: 12px;
      line-height: 20px;
      text-align: center;
      margin: 1rem 0;
      text-decoration: underline;
      cursor: pointer;
      &:hover,
      &:active {
        color: #ff552d;
      }
    }
  }
  .login-box {
    padding: 5rem 1.63rem 0 1.63rem;
    .title {
      position: absolute;
      top: 0.2rem;
      left: 1.63rem;
      font-size: 16px;
      font-weight: bold;
      color: #333333;
      letter-spacing: 1px;
      &::after {
        position: absolute;
        content: '';
        bottom: -0.25rem;
        left: 1%;
        width: 96%;
        height: 0.15rem;
        background: #ff7202;
      }
    }
    .forget {
      transform: translateY(-0.58rem);
    }
    .submit {
      position: relative;
      box-sizing: border-box;
      width: 16.25rem;
      height: 2.25rem;
      background: #ffab95;
      border-radius: 0.25rem;
      text-align: center;
      line-height: 2.25rem;
      color: #ffffff;
    }
    .active {
      background: #fd562c;
    }
    .checkbox {
      .bold {
        color: #fd562c;
        margin: 0 0.25rem;
      }
    }
    .signup {
      position: absolute;
      bottom: 0;
      right: 0;
    }
  }
`;
