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 { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import { Helmet, HelmetProvider } from 'react-helmet-async';
import { actionCreators } from '../../../containers/App/store';
import LoginForm from './components/Login';
import WxLogin from './components/WxLogin';
import LoginAction from './login';
import styles from './style.less';
import i18n from '../../../utils/share';
import defaultSetting from '../../../../config/defaultSetting';
const { UserName, Password, Mobile, Captcha, Submit } = LoginForm;
const Display = {
  Account: 'Account',
  WeChart: 'WeChart',
  Mobile: 'Mobile',
};
const LoginWay = {
  Account: 'pdw',
  WeChart: 'iotWechat',
  Mobile: 'iotPhone',
};
const pages = i18n.getI18n('pages');
const LoginMessage = ({ content }) => (
  <Alert
    style={{
      marginBottom: 2,
    }}
    message={content}
    type="error"
    showIcon
  />
);

const useRenderQcode = props => {
  if (!props.qrcode) {
    return null;
  }
  const qrcodes = props.qrcode.split('|');
  const qcodeComponent = url => (
    <img
      src={url}
      className="QuickMark-cont"
      style={{ width: '150px', height: '150px' }}
      alt=""
    />
  );
  const element = [];
  qrcodes.forEach((item, index) => {
    const firstValue = item.split('=');
    switch (firstValue[0]) {
      case '小程序':
        element.push(
          <div
            className={classNames(
              styles['quickMark-single'],
              styles['mini-single'],
            )}
            key={firstValue[0]}
          >
            <Popover
              placement="top"
              content={qcodeComponent(
                'https://panda-water.cn/web4/assets/images/小程序二维码.jpg',
              )}
            >
              <div className={styles['icon-Container']}>
                <span className={styles.Wechat} />
                <span className="iconText WechatText">Wechat</span>
              </div>
            </Popover>
          </div>,
        );
        break;
      case '智联小程序':
        element.push(
          <div
            className={classNames(styles['quickMark-single'], 'miniIOT-single')}
            key={firstValue[0]}
          >
            <Popover
              placement="top"
              content={qcodeComponent(
                'https://panda-water.cn/web4/assets/images/智联小程序二维码.jpg',
              )}
            >
              <div className={styles['icon-Container']}>
                <span className={styles.Wechat} />
                <span
                  className={classNames(styles.iconText, styles.WechatText)}
                >
                  熊猫智联
                </span>
              </div>
            </Popover>
          </div>,
        );
        break;

      case 'Android':
        if (firstValue[1] && firstValue[1].replace(/ /g, '').length > 0) {
          element.push(
            <div
              className={classNames(
                styles['quickMark-single'],
                'Android-single',
              )}
              key={firstValue[0]}
            >
              <Popover
                placement="top"
                content={
                  <QRCode
                    value={firstValue[1].replace(
                      /{ip}/gi,
                      props.ip || window.location.host,
                    )}
                  />
                }
              >
                <div className={styles['icon-Container']}>
                  <span className={styles.Android} />
                  <span
                    className={classNames(styles.iconText, styles.AndroidText)}
                  >
                    Android
                  </span>
                </div>
              </Popover>
            </div>,
          );
        }
        break;
      case 'iPhone':
        if (firstValue[1] && firstValue[1].replace(/ /g, '').length > 0) {
          element.push(
            <div
              className={classNames(
                styles['quickMark-single'],
                'iphone-single',
              )}
              key={firstValue[0]}
            >
              <Popover
                placement="top"
                content={
                  <QRCode
                    value={firstValue[1].replace(
                      /{ip}/gi,
                      props.ip || window.location.host,
                    )}
                  />
                }
              >
                <div className={styles['icon-Container']}>
                  <span className={styles.Wechat} />
                  <span
                    className={classNames(styles.iconText, styles.iphoneText)}
                  >
                    iPhone
                  </span>
                </div>
              </Popover>
            </div>,
          );
        }
        break;
      default:
        if (item && item.replace(/ /g, '').length > 0) {
          const indexIndex = element.findIndex(
            // eslint-disable-next-line no-shadow
            item => item.props.className.indexOf('Android-single') > -1,
          );
          element.splice(indexIndex, 1);
          element.push(
            <div
              className={classNames(
                styles['quickMark-single'],
                'Android-single',
              )}
              key={index}
            >
              <Popover
                placement="top"
                content={
                  <QRCode
                    value={item.replace(
                      /{ip}/gi,
                      props.ip || window.location.host,
                    )}
                  />
                }
              >
                <div className={styles['icon-Container']}>
                  <span className={styles.Android} />
                  <span
                    className={classNames(styles.iconText, styles.AndroidText)}
                  >
                    Android
                  </span>
                </div>
              </Popover>
            </div>,
          );
        }
        break;
    }
  });
  return element;
};
/* eslint-disable */
const Account = props => (
  <LoginForm onSubmit={props.onSubmit}>
    {props.status === 'error' &&
      props.type === 'account' &&
      !props.submitting && (
        <LoginMessage content={pages.get('login.accountLogin.errorMessage')} />
      )}
    <UserName
      name="userName"
      placeholder={pages.get('login.username.placeholder')}
      rules={[
        {
          required: true,
          message: pages.get('login.username.required'),
        },
      ]}
    />
    <Password
      name="password"
      placeholder={pages.get('login.password.placeholder')}
      rules={[
        {
          required: true,
          message: pages.get('login.password.required'),
        },
      ]}
    />
    <div>
      <Checkbox
        checked={props.autoLogin}
        onChange={e => props.setAutoLogin(e.target.checked)}
      >
        {pages.get('login.rememberMe')}
      </Checkbox>
    </div>
    <Submit loading={props.submitting}>{pages.get('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="手机号码未注册" />}
      <Mobile name="mobile" placeholder="请输入手机号码" />
      <Captcha
        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(Display[type]);
    props.updateLoginMode(LoginWay[type]);
    Cookies.set('loginMode', LoginWay[type], {
      expires: 5 * 60 * 1000,
      path: '/',
    });
  };
  return (
    <div className={styles.wechatQRcode}>
      {props.type === Display.Account ? (
        <Account {...props} />
      ) : props.type === Display.WeChart ? (
        <IOTQRCode {...props} />
      ) : props.type === Display.Mobile ? (
        <Phone {...props} />
      ) : (
        <Account {...props} />
      )}
      <div className={styles.loginDisplay}>
        <a
          onClick={() => handlerType('Account')}
          style={{
            display: props.type === Display.Account ? 'none' : 'block',
          }}
        >
          {pages.get('login.accountLogin.tab')}
        </a>
        <a
          onClick={() => handlerType('WeChart')}
          style={{
            display: props.type === Display.WeChart ? 'none' : 'block',
          }}
        >
          {pages.get('login.weChart.tab')}
        </a>
        <a
          onClick={() => handlerType('Mobile')}
          style={{
            display: props.type === Display.Mobile ? 'none' : 'block',
          }}
        >
          {pages.get('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 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),
  );

  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);
    action &&
      action.events.on('loginSuccess', event => {
        setSubmitting(false);
        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(() => {
    console.log('===LoginWay===', LoginWay.WeChart);
    if (props.loginMode === LoginWay.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() {
        dom.removeClass(loginRef.current, styles.caseHide);
        dom.addClass(loginRef.current, styles.loginTimeShow);
        videoTimeout = setTimeout(() => {
          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');
        }, 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,
    };
    switch (template) {
      case 'DarkCloud.html':
      case 'Dark.html':
        return <Account {...params} />;
      case 'Dark - IOTMultiLogin.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/beforPage.mp4") }
          className={styles.videLayer}
          autoPlay="autoPlay"
          muted
          playsInline="playsinline"
          ref={videoRef}
        />
        <div className={styles.inner}>
          <div
            className={classNames(styles.loginTime, styles.caseHide)}
            ref={loginRef}
          >
            <img
              role="logo"
              src={props.global.transformDevAssetsBaseURL(props.global.logo)}
            />
            <div
              className={classNames(
                styles.titleCase,
                styles.caseHide,
                'animated',
              )}
              ref={titleRef}
            >
              <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['login-block'],
              styles.caseHide,
              'animate__animated',
            )}
            ref={loginFormRef}
          >
            <div>
              <img src="https://panda-water.cn/web4/assets/images/login/dark/login.png" />
            </div>
            <div className={styles['login-form']}>{renderPlatform()}</div>
          </div>
        </div>
        <div
          className={classNames(
            styles.footerCase,
            styles.caseHide,
            'animate__animated',
          )}
          ref={footerRef}
        >
          <div className={classNames(styles.quickMark)}>{renderAddons}</div>
          <span className={classNames(styles.copyright)}>
          Copyright ©
          <a target="_blank" href="https://panda-water.cn">
            熊猫智慧水务
          </a>
            {new Date().getFullYear()} All Rights Reserved{' '}
            <a target="_blank" id="IndexCaseNumber" href="">
            沪ICP备11036640-1
          </a>
          <span className="addons">
            <span className="split" />
            <a id="qrcode">
              <span
                className="glyphicon glyphicon-qrcode"
                role="button"
                title="手持APP下载"
              />
            </a>
          </span>
        </span>
        </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));
  },
});
export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(withRouter(Login));
