import React, { useEffect, useState } from 'react';
import { ReloadOutlined } from '@ant-design/icons';
import { message, Modal } from 'antd';
import Cookies from 'js-cookie';
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';

export const LoginModalWrap = styled.div`
  position: relative;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  flex-direction: column;
  box-sizing: border-box;
  padding: 0.68rem 0;
  .qrcode {
    position: relative;
    width: 10.68rem;
    height: 10.68rem;
    margin: 1.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;
      }
    }
  }
  .title {
    color: #222;
    font-size: 16px;
    font-weight: bold;
  }
  .text {
    color: #333;
    font-size: 12px;
    line-height: 20px;
    text-align: center;
  }
  .action {
    color: #999;
    font-size: 12px;
    line-height: 20px;
    text-align: center;
    margin: 1rem 0;
    text-decoration: underline;
    cursor: pointer;
    &:hover,
    &:active {
      color: #ff552d;
    }
  }
`;

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

const LoginModalView = ({
  open,
  onCancel,
}: {
  open: boolean;
  onCancel: () => void;
}) => {
  // system
  const globalData = useSelector(
    (state: RootState) => state.globalData,
  ) as GlobalDataState;
  // store
  const dispatch = useDispatch();
  // 获取小程序二维码唯一标识
  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);
  };
  // 组件挂载
  useEffect(() => {
    if (!open) {
      // 关闭定时器
      if (timer) clearInterval(timer);
      return;
    }
    // 获取二维码
    getQrcodeLogin().then(() => {
      setQrCodeExpired(false);
      setLoginInfoTimer();
    });
  }, [open]);
  return (
    <Modal open={open} footer={null} onCancel={handleClose}>
      <LoginModalWrap>
        <div className="title">
          {globalData?.loginModalTitle || `微信扫码登录`}
        </div>
        <div className="qrcode">
          {qrCodeData && (
            <img src={qrCodeData} alt="登录二维码" className="image" />
          )}
          {qrCodeExpired && (
            <div className="shadow flex-center animate__animated animate__fast animate__fadeIn">
              <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 className="text">「云享飞，让天空为世界所用」</div>
      </LoginModalWrap>
    </Modal>
  );
};

export default LoginModalView;
