import 'kit_utils/lib/format';

import React, {
  forwardRef,
  useEffect,
  useRef,
  useState,
} from 'react';

import {
  Alert,
  Checkbox,
  Form,
  Modal,
  Popover,
} from 'antd';
import classNames from 'classnames';
import { encode } from 'js-base64';
import Cookies from 'js-cookie';
import { dom } from 'kit_utils';
import QRCode from 'qrcode.react';
import {
  Helmet,
  HelmetProvider,
} from 'react-helmet-async';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';

import {
  LOGIN_DISPLAY,
  LOGIN_WAY,
} from '@/constants';
import { actionCreators } from '@/containers/App/store';
import {
  FormattedMessage,
  useIntl,
} from '@/locales/localeExports';

import defaultSetting from '../../../../../config/defaultSetting';
import LoginForm from '../components/Login';
import WxLogin from '../components/WxLogin';
import LoginAction from '../login';
import LoginMessage from '../js/loginMessage';
import useRenderQcode from '../js/useRenderQcode';
import styles from '../style.less';

const {
  UserName,
  NewYearPassword,
  NewYearMobile,
  NewYearCaptcha,
  Submit,
} = LoginForm;

/* eslint-disable */
const Account = props => (
  <LoginForm onSubmit={props.onSubmit}>
    {props.status === 'error' &&
    props.type === 'account' &&
    !props.submitting && (
      <LoginMessage content={props.intl.formatMessage({id: 'pages.login.accountLogin.errorMessage'})} />
    )}
    <UserName
      name="userName"
      placeholder={props.intl.formatMessage({id: 'pages.login.username.placeholder'})}
      rules={[
        {
          required: true,
          message: <FormattedMessage
            id="pages.login.username.required"
            defaultMessage="请输入用户名!"
          />
        },
      ]}
    />
    <NewYearPassword
      name="password"
      placeholder={props.intl.formatMessage({id: 'pages.login.password.placeholder'})}
      rules={[
        {
          required: true,
          message: props.intl.formatMessage({id: 'pages.login.password.required'}),
        },
      ]}
    />
    <div>
      <Checkbox
        checked={props.autoLogin}
        onChange={e => props.setAutoLogin(e.target.checked)}
      >
        {props.intl.formatMessage({id: 'pages.login.rememberMe'})}
      </Checkbox>
    </div>
    <Submit loading={props.submitting}>{props.intl.formatMessage({id: 'pages.login.submit'})}</Submit>
  </LoginForm>
);

const IOTQRCode = () => {
  const REDIRECT_URI = 'https://panda-water.com/civbase/user/login';
  const APPID = 'wx8bfa8b02cb95010b';
  const [rstate, setRstate] = useState(() =>
    encode(
      `panda_${Math.round(Math.random() * 10000 + Date.now()).toString(16)}`,
    ),
  );

  useEffect(() => {
    Cookies.set('redirect_state', rstate, {
      expires: 5 * 60 * 1000,
      path: '/',
    });
  }, []);

  const props = Object.assign(
    {},
    {
      self_redirect: false,
      scope: 'snsapi_login',
      appid: APPID,
      state: rstate,
      redirect_uri: REDIRECT_URI,
      href: 'https://panda-water.cn/web4/styles/PandaIOTQrcodeStyle.css',
    },
  );
  return <WxLogin {...props} />;
};

const Phone = props => {
  const [form] = Form.useForm();
  return (
    <LoginForm form={form} onSubmit={props.onSubmit}>
      {props.status === 'error' &&
      props.type === 'account' &&
      !props.submitting && <LoginMessage content="手机号码未注册" />}
      <NewYearMobile name="mobile" placeholder="请输入手机号码" />
      <NewYearCaptcha
        name="captcha"
        placeholder="请输入短信验证码"
        countDown={60}
        getCaptchaButtonText=""
        getCaptchaSecondText="秒"
        autoComplete="off"
        rules={[
          {
            required: true,
            message: '请输入短信验证码！',
          },
        ]}
      />
      <Submit loading={props.submitting} style={{ marginTop: '0px' }}>
        登录
      </Submit>
    </LoginForm>
  );
};

const IotComponent = props => {
  const handlerType = type => {
    props.setType(LOGIN_DISPLAY[type]);
    props.updateLoginMode(LOGIN_WAY[type]);
    Cookies.set('loginMode', LOGIN_WAY[type], {
      expires: 5 * 60 * 1000,
      path: '/',
    });
  };
  return (
    <div className={styles.wechatQRcode}>
      {props.type === LOGIN_DISPLAY.Account ? (
        <Account {...props} />
      ) : props.type === LOGIN_DISPLAY.WeChart ? (
        <IOTQRCode {...props} />
      ) : props.type === LOGIN_DISPLAY.Mobile ? (
        <Phone {...props} />
      ) : (
        <Account {...props} />
      )}
      <div className={styles.loginDisplay}>
        <a
          onClick={() => handlerType('Account')}
          style={{
            display: props.type === LOGIN_DISPLAY.Account ? 'none' : 'block',
          }}
        >
          {props.intl.formatMessage({id: 'pages.login.accountLogin.tab'})}
        </a>
        <a
          onClick={() => handlerType('WeChart')}
          style={{
            display: props.type === LOGIN_DISPLAY.WeChart ? 'none' : 'block',
          }}
        >
          {props.intl.formatMessage({id: 'pages.login.weChart.tab'})}
        </a>
        <a
          onClick={() => handlerType('Mobile')}
          style={{
            display: props.type === LOGIN_DISPLAY.Mobile ? 'none' : 'block',
          }}
        >
          {props.intl.formatMessage({id: 'pages.login.phoneLogin.tab'})}
        </a>
      </div>
    </div>
  );
};

const Login = forwardRef((props, _ref) => {
  const videoRef = useRef();
  const loginRef = useRef();
  const timeRef = useRef();
  const titleRef = useRef();
  const sliVerify = useRef();
  const loginFormRef = useRef();
  const loginWrapper = useRef();
  const formRef = useRef(null);
  const footerRef = useRef();
  const [status, setStatus] = useState('normal');
  const [autoLogin, setAutoLogin] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [currentDate, setCurrentDate] = useState({});
  const [type, setType] = useState('Account');
  const [visible, setVisible] = useState(false);
  const [action, setAction] = useState(
    () => new LoginAction(props, setVisible, true),
  );

  const intl = useIntl();

  useEffect(() => {
    action.globalConfig = props.global;
  }, [props.global]);

  const handleSubmit = values => {
    /* eslint-disable */
    action &&
    (type === 'Account'
      ? action.loginHandler(
        values.userName,
        values.password,
        null,
        autoLogin,
        sliVerify,
      )
      : type === 'Mobile'
        ? action.phoneLoginFormHandler(values.mobile, values.captcha)
        : null);

    setSubmitting(true);
    props.updateCurrentIndex && props.updateCurrentIndex(-1);
    action &&
    action.events.on('loginSuccess', event => {
      setSubmitting(false);
      props.updateCurrentIndex && props.updateCurrentIndex(0);
      props.history.push(`/?client=${props.global.client}`);
      window.share.event.emit('triggerMicro', props.global);
    });
    action &&
    action.events.on('loginError', event => {
      setVisible(false);
      setSubmitting(false);
    });
    action &&
    action.events.on('loginVisible', status => {
      setVisible(status);
    });
  };

  useEffect(() => {
    if (props.loginMode === LOGIN_WAY.WeChart) {
      action &&
      action.events.on('loginSuccess', event => {
        props.history.push(`/?client=${props.global.client}`);
        window.share.event.emit('triggerMicro', props.global);
      });
      action &&
      action.events.on('loginError', event => {
        setVisible(false);
        setSubmitting(false);
      });
    }
  }, [props.loginMode]);

  let loginTimeInterval = null;
  let videoTimeout = null;
  useEffect(() => {
    if (loginTimeInterval)
      clearInterval(loginTimeInterval), (loginTimeInterval = null);
    loginTimeInterval = setInterval(() => {
      const date = new Date();
      const weekday = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
      const time = `${
        date.getHours() < 10 ? `0${date.getHours()}` : date.getHours()
      }:${
        date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes()
      }:${
        date.getSeconds() < 10 ? `0${date.getSeconds()}` : date.getSeconds()
      }`;
      setCurrentDate({
        time,
        dayofweek: weekday[date.getDay()],
        date: date.pattern('yyyy/MM/dd'),
      });
    }, 1000);
    return () => {
      loginTimeInterval && clearInterval(loginTimeInterval);
    };
  }, []);

  useEffect(() => {
    if (videoRef && videoRef.current) {
      videoRef.current.addEventListener('ended', function() {

        videoTimeout = setTimeout(() => {
          dom.removeClass(loginRef.current, styles.caseHide);
          dom.addClass(loginRef.current, 'animate__fadeInDown');

          dom.removeClass(timeRef.current, styles.caseHide);
          dom.addClass(timeRef.current, 'animate__fadeIn');

          dom.removeClass(loginFormRef.current, styles.caseHide);
          dom.addClass(loginFormRef.current, 'animate__fadeInUp');

          dom.removeClass(footerRef.current, styles.caseHide);
          dom.addClass(footerRef.current, 'animate__slideInUp');
          dom.removeClass(titleRef.current, styles.caseHide);
          dom.addClass(titleRef.current, 'animte__fadeInUp');

          dom.removeClass(loginWrapper.current, styles.caseHide);
          dom.addClass(loginWrapper.current, 'animate__fadeInUp');
        }, 500);
      });
    }

    return () => {
      videoTimeout && clearTimeout(videoTimeout);
      videoRef.current.removeEventListener('ended', () => {});
    };
  }, [videoRef]);
  useEffect(() => {
    setSubmitting(false);
  }, [visible]);
  const renderAddons = useRenderQcode(props.global);
  const renderPlatform = () => {
    const template = props.global.loginTemplate;
    const params = {
      fromRef: formRef,
      type,
      setType,
      status,
      submitting,
      autoLogin,
      setAutoLogin,
      action,
      onSubmit: handleSubmit,
      loginMode: props.loginMode,
      updateLoginMode: props.updateLoginMode,
      intl,
    };
    switch (template) {
      case 'DarkCloud.html':
      case 'Dark.html':
        return <Account {...params} />;
      case '新春 - 智联.html':
        return <IotComponent {...params} />;
      default:
        return <Account {...params} />;
        break;
    }
  };
  /* eslint-disable */

  return (
    <HelmetProvider>
      <Helmet>
        <title>{props.global.title || defaultSetting.title}</title>
        <meta name="description" content={props.global.title || defaultSetting.title} />
      </Helmet>
      <div className={styles.main}>
        <video
          src={require("../../../../assets/videos/001.mp4") }
          className={styles.videLayer}
          autoPlay="autoPlay"
          muted
          playsInline="playsinline"
          ref={videoRef}
        />
        <div className={classNames(styles.inner, styles.newYearInner)}>
          <div
            className={classNames(styles.loginTime, styles.newYearLoginTime, styles.caseHide, 'animated')}
            ref={loginRef}
          >
            <img
              role="logo"
              src={props.global.transformDevAssetsBaseURL(props.global.logo)}
            />
            <div
              className={classNames(
                styles.titleCase,
              )}
            >
              <span className={styles.title}>{props.global.title}</span>
              <span className={styles.subtitle}>
              {window.globalConfig.subtitle}
            </span>
            </div>
          </div>
          <span
            className={classNames(
              styles.divider,
              styles.caseHide,
              'animate__animated',
            )}
          />
          <div
            className={classNames(
              styles.timeCase,
              styles.caseHide,
              'animate__animated',
            )}
            ref={timeRef}
          >
            <span className={styles.time}>{currentDate.time}</span>
            <span className={styles.dayofweek}>{currentDate.dayofweek}</span>
            <span className={styles.date}>{currentDate.date}</span>
          </div>
          <div className={classNames(
            styles.loginBlockWrapper,
            'animate__animated',
             styles.caseHide,
          )} ref={loginWrapper}>
            <div
              className={classNames(
                styles['login-block'],
                styles['login-newYear-block'],
                styles.caseHide,
                'animate__animated',
              )}
              ref={loginFormRef}
            >
              <div>
                <img src="https://panda-water.com/web4/assets/images/login/workflow/%E6%99%BA%E8%81%94%E6%96%B0%E6%98%A5%E5%9B%BE%E7%89%87.png" />
              </div>
              <div className={styles['login-form']}>{renderPlatform()}</div>
            </div>
          </div>

        </div>
        <Modal
          centered
          visible={visible}
          width={340}
          footer={null}
          closable={false}
          bodyStyle={{ padding: '15px' }}
        >
          <div ref={sliVerify} />
        </Modal>
      </div>
    </HelmetProvider>
  );
});

const mapStateToProps = state => ({
  global: state.getIn(['global', 'globalConfig']),
  loginMode: state.getIn(['global', 'loginMode']),
});

const mapDispatchToProps = dispatch => ({
  updateConfig(config) {
    dispatch(actionCreators.getConfig(config));
  },
  createContext(data) {
    dispatch(actionCreators.createContext(data));
  },
  updateLoginMode(mode) {
    dispatch(actionCreators.changeLoginMode(mode));
  },
  updateCurrentIndex(index) {
    dispatch(actionCreators.updateCurrentIndex(index));
  },
});
export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(withRouter(Login));
