import { Button, Checkbox, Form, Image, Input, message, QRCode } from 'antd';
import { useEffect, useState } from 'react';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import Cookies from 'js-cookie';
import './index.scss';
import { InterReqType } from '~/api/interface';
import { BackEndLoginType } from '~/api/interface/commonType';
import { CommonAPI } from '~/api';
import { useDispatch } from 'react-redux';
import { SET_USERINFO } from '~/store/module/userInfo';
import { authRouterList } from '~/router';
import qrCodeIcon from '~/assets/image/qr-code-icon.svg';

// 请求的类型
type ReqType = InterReqType<BackEndLoginType>;

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

function LoginView() {
  const navigate = useNavigate();
  // redux
  const dispatch = useDispatch();
  // 表单钩子
  const [form] = Form.useForm<ReqType>();
  //是否二维码登录
  const [isLoginCode, setIsLoginCode] = useState<boolean>(false);
  //获取小程序二维码唯一标识
  const [randomLoginCode] = useState<string>(parseInt(String(Math.random() * 10001), 10) + '');
  //小程序二维码地址
  const [qrCodeUrl, setQrCodeUrl] = useState<string>('');

  // 提交数据
  const onFinish = async (values: ReqType) => {
    const res = await CommonAPI.BackEndLogin({
      accountNo: values?.accountNo,
      passWord: values?.passWord,
    });
    if (res && res.code === '200') {
      message.success('登录成功');
      const { token } = res.result;
      await Cookies.set('SHAREFLY-TOKEN', token);
      // 记住密码
      Cookies.set('password', values?.passWord || '');
      Cookies.set('username', values?.accountNo || '');
      Cookies.set('remember', String(values?.remember));
      // 存用户信息
      dispatch(SET_USERINFO(res.result));
      localStorage.setItem('roleId', res.result.roleInfo.id.toString());
      authRouterList().then((value: any) => {
        if (value.length) {
          navigate({
            pathname: value[0].children?.find((v: any) => !v.meta.hidden)?.path || value[0].path,
          });
        } else {
          message.warning('请先配置权限');
        }
      });
    } else {
      message.error('登录失败，请检查账号信息');
    }
  };
  //显示二维码登录方式
  const changeLoginUseEvent = () => {
    //第一次二维码
    if (!isLoginCode && !qrCodeUrl) {
      CommonAPI.getAppletQRCode({
        page: 'page-identity/identity-empower/index',
        scene: `randomLoginCode=${randomLoginCode}&port=1`,
      }).then(({ result }) => {
        setQrCodeUrl(result ? `data:image/png;base64,${result}` : '');
        time = setInterval(() => {
          getLoginInfo();
        }, 1000);
      });
    } else if (!isLoginCode && qrCodeUrl) {
      time = setInterval(() => {
        getLoginInfo();
      }, 1000);
    } else {
      if (time) {
        clearInterval(time);
      }
    }
    setIsLoginCode(!isLoginCode);
  };
  //二维码登录
  const getLoginInfo = () => {
    CommonAPI.getLoginInfo({ randomLoginCode }).then(async ({ result, code }) => {
      if (code === '200') {
        clearInterval(time);
        message.success('登录成功');
        const { token } = result;
        await Cookies.set('SHAREFLY-TOKEN', token);
        dispatch(SET_USERINFO(result));
        localStorage.setItem('roleId', result.roleInfo.id.toString());
        authRouterList().then((value: any) => {
          if (value.length) {
            navigate({
              pathname: value[0].children?.find((v: any) => !v.meta.hidden)?.path || value[0].path,
            });
          } else {
            message.warning('请先配置权限');
          }
        });
      }
    });
  };
  // componentDidMount
  useEffect(() => {
    // 是否保存密码
    const remember = Boolean(Cookies.get('remember'));
    if (!remember) return;
    // 如果保存了密码
    form.setFieldsValue({
      accountNo: Cookies.get('username'),
      passWord: Cookies.get('password'),
      remember: Boolean(Cookies.get('remember')),
    });
  }, []);

  return (
    <div className='login-warp'>
      <div className='login-view'>
        <div className='login-flex login-content'>
          <div className='login-title'></div>
          <div className='login-text'>云享飞管理平台</div>
          <div className='login-detail'>让天空为世界所用</div>
        </div>

        <div className='login-flex login-form'>
          {isLoginCode ? (
            <div className='qr-code-wrap'>
              {qrCodeUrl ? (
                <Image src={qrCodeUrl} alt='' width={200} height={200} preview={false} />
              ) : (
                //  加载二维码
                <QRCode value='https://ant.design/' status='loading' />
              )}
            </div>
          ) : (
            <>
              <div className='login-image' />
              <div className='login-input'>
                <Form
                  name='basic'
                  form={form}
                  wrapperCol={{ span: 16, offset: 4 }}
                  initialValues={{ remember: true }}
                  onFinish={onFinish}
                  autoComplete='off'
                >
                  <Form.Item name='accountNo' rules={[{ required: true, message: '请输入用户名' }]}>
                    <Input
                      size='large'
                      prefix={<UserOutlined />}
                      placeholder='请输入账号'
                      allowClear
                    />
                  </Form.Item>

                  <Form.Item
                    name='passWord'
                    className='login-password'
                    rules={[{ required: true, message: '请输入密码' }]}
                  >
                    <Input.Password
                      size='large'
                      prefix={<LockOutlined />}
                      placeholder='请输入密码'
                      allowClear
                    />
                  </Form.Item>

                  <Form.Item
                    name='remember'
                    className='login-remember'
                    valuePropName='checked'
                    wrapperCol={{ offset: 4, span: 8 }}
                  >
                    <Checkbox>记住密码</Checkbox>
                  </Form.Item>

                  <Form.Item wrapperCol={{ offset: 7, span: 15 }}>
                    <Button
                      type='primary'
                      htmlType='submit'
                      shape='round'
                      size='large'
                      className='login-submit'
                    >
                      登录
                    </Button>
                  </Form.Item>
                </Form>
              </div>
            </>
          )}
        </div>

        {isLoginCode ? (
          <div className='account-login-operate'>
            <Button type='link' onClick={changeLoginUseEvent}>
              使用账号登录
            </Button>
          </div>
        ) : (
          <div className='qrCode-icon'>
            <img src={qrCodeIcon} alt='icon' onClick={changeLoginUseEvent} />
          </div>
        )}
      </div>
    </div>
  );
}

export default LoginView;
