import React, { useState, useEffect, useRef } from 'react';
import { Form, Input, Button, Row, Col, Space, Image, message } from 'antd';
import { CloseOutlined, UserOutlined, LockOutlined } from '@ant-design/icons';

import { useNavigate } from 'react-router-dom';

import { checkSSOLogin } from '../request/request';

import './index.less';
import loginBtn from '@/assets/images/loginBtn.png';
import loginBtn2 from '@/assets/images/loginBtn2.png';

import Icon1 from '@/assets/login/1.png';
import Icon2 from '@/assets/login/2.png';
import Icon3 from '@/assets/login/3.png';
import Icon4 from '@/assets/login/4.png';
import Icon5 from '@/assets/login/5.png';
import Icon6 from '@/assets/login/6.png';
import Icon7 from '@/assets/login/7.png';
import Icon8 from '@/assets/login/8.png';
import Icon9 from '@/assets/login/9.png';
import Icon10 from '@/assets/login/10.png';
import Icon11 from '@/assets/login/11.png';
import Icon12 from '@/assets/login/12.png';
import Icon13 from '@/assets/login/13.png';
import Icon14 from '@/assets/login/14.png';
import Icon15 from '@/assets/login/15.png';
import Icon16 from '@/assets/login/16.png';
import Icon17 from '@/assets/login/17.png';
import Icon18 from '@/assets/login/18.png';
import Icon19 from '@/assets/login/19.png';
import Icon20 from '@/assets/login/20.png';
import Icon21 from '@/assets/login/21.png';
import Icon22 from '@/assets/login/22.png';
import Icon23 from '@/assets/login/23.png';
import { login } from './request';
import logo from '@/assets/images/icon_logo_login.png';

import { RotateVerify } from '../../../utils/captcha';

const Login = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [isActive, setIsActive] = useState(0);

  const [loading, setLoading] = useState(false);
  const [captchaURL, setCaptchaURL] = useState('');
  const [captchaStatus, setCaptchaStatus] = useState(false);
  const [captchaText, setCaptchaText] = useState('发送验证码');
  const [showCaptcha, setShowCaptcha] = useState(false);
  const [isLoggedIn, setIsLoggedIn] = useState(false); //登录图片切换
  const [isLoginBtn, setIsLoginBtn] = useState(false); //是否点击了登录按钮
  const [code, setCode] = useState('');
  const [disLf, setDisLf] = useState('');

  const [initialValues, setinitialValues] = useState({
    tel: '',
    password: '',
  });

  const timer = useRef();

  const getSSOInfo = async () => {
    const isSSOData = await checkSSOLogin();
    if (isSSOData.run === 'login') {
    } else if (isSSOData.token) {
      localStorage.setItem('kiwi.token', isSSOData.token);
      navigate('/');
      return;
    }
  };

  useEffect(() => {
    getSSOInfo();
  }, []);

  // 登录
  const toLayout = async (obj) => {
    setLoading(true);
    if (isLoginBtn) {
      const data = await login({
        ...obj,
        code: code,
        disLf: disLf,
      });

      if (data.code === 200) {
        localStorage.setItem('kiwi.token', data.token);
        navigate('/');
        return;
      } else {
        form.setFields([{ name: 'password', errors: [data.msg] }]);
      }
    } else {
      message.error('请先完成按钮验证');
    }

    // 刷新验证码
    // await refreshCaptcha();
    setLoading(false);
  };

  const handleStartVerification = () => {
    setShowCaptcha(true);
  };

  // 点击×
  const handleGoBack = () => {
    setShowCaptcha(false);
  };

  useEffect(() => {
    if (showCaptcha) {
      const rotateWrapEle = document.querySelector('#rotateWrap1');
      // 确保 DOM 元素存在之后再进行初始化
      if (rotateWrapEle) {
        const myRotateVerify = new RotateVerify('#rotateWrap1', {
          initText: '滑动将图片转正',
          slideImage: [
            Icon1,
            Icon2,
            Icon3,
            Icon4,
            Icon5,
            Icon6,
            Icon7,
            Icon8,
            Icon9,
            Icon10,
            Icon11,
            Icon12,
            Icon13,
            Icon14,
            Icon15,
            Icon16,
            Icon17,
            Icon18,
            Icon4,
            Icon19,
            Icon20,
            Icon21,
            Icon22,
            Icon23,
          ],
          initUrl: '/user/login/initData',
          verifyUrl: '/user/login/checkVerify',
          getSuccessState: function (data) {
            console.log('验证成功', data);
            setDisLf(data.disLf);
            setCode(data.code);

            if (data.disLf) {
              setShowCaptcha(false);
              setIsLoggedIn(true);
              setIsLoginBtn(true);
            }
          },
        });

        // 如果需要，在这里处理卸载时清理资源
        return () => {
          console.log(myRotateVerify.initUrl);
          // 清理或销毁 RotateVerify 实例等操作
          if (myRotateVerify && typeof myRotateVerify.destroy === 'function') {
            myRotateVerify.destroy();
          }
        };
      }
    }
  }, [showCaptcha]);

  return (
    <div className={showCaptcha ? 'captcha-container' : 'normal-container'}>
      {showCaptcha && (
        <div className='rotateWrap'>
          <div className='cuo' onClick={handleGoBack}>
            <CloseOutlined />
          </div>

          <span className='top-s'>身份验证</span>
          <span className='top-x'>拖动滑块，使图片角度为正</span>
          <div id='rotateWrap1'>
            <div className='rotateverify-contaniner'>
              <div className='rotate-can-wrap'>
                <canvas className='rotateCan rotate-can' width='200' height='200'></canvas>
                <div className='statusBg status-bg'></div>
              </div>
              <div className='control-wrap slideDragWrap'>
                <div className='control-tips'>
                  <p className='c-tips-txt cTipsTxt'>滑动将图片转正</p>
                </div>
                <div className='control-bor-wrap controlBorWrap'></div>
                <div className='control-btn slideDragBtn'>
                  {/* <i className='control-btn-ico'></i> */}
                  <div className='control-btn-ico'></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
      {!showCaptcha && (
        <div className='img-logo'>
          <img src={logo} className='img' />
        </div>
      )}
      {!showCaptcha && <div className='login-header'>欢迎登录</div>}{' '}
      {!showCaptcha && (
        <div className='form-data-container'>
          <Form form={form} onFinish={toLayout} autoComplete='off' initialValues={initialValues}>
            <>
              <Form.Item
                name='tel'
                rules={[
                  { required: true, message: '请输入手机号!' },
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确格式的手机号' },
                ]}
              >
                <Input
                  autoComplete='off'
                  prefix={<UserOutlined />}
                  size='large'
                  placeholder='请输入手机号'
                />
              </Form.Item>
              <Form.Item name='password' rules={[{ required: true, message: '请输入密码!' }]}>
                <Input.Password
                  autoComplete='off'
                  prefix={<LockOutlined />}
                  size='large'
                  placeholder='请输入密码'
                />
              </Form.Item>
              {/* <Form.Item name='verify' rules={[{ required: true, message: '请输入验证码!' }]}>
                <Row gutter={16}>
                  <Col span={16}>
                    <Input
                      prefix={<SetIcon src={IconCaptcha} />}
                      size='large'
                      placeholder='请输入验证码'
                    />
                  </Col>
                  <Col span={8}>
                    <img
                      src={captchaURL}
                      alt='图形验证码'
                      className='captcha'
                      onClick={refreshCaptcha}
                    />
                  </Col>
                </Row>
              </Form.Item> */}

              <Form.Item name='verify' onClick={handleStartVerification}>
                <div style={{ width: '100%', height: '100%', pointerEvents: 'none' }}>
                  {isLoggedIn ? (
                    <Image
                      src={loginBtn2}
                      style={{
                        width: '100%',
                        height: '100%',
                      }}
                    />
                  ) : (
                    <Image
                      src={loginBtn}
                      style={{
                        width: '100%',
                        height: '100%',
                      }}
                    />
                  )}
                </div>
              </Form.Item>
            </>
            <Form.Item className='login-submit-btn'>
              <Button htmlType='submit' loading={loading} type='primary' size='large'>
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      )}
    </div>
  );
};

export default Login;
