/*
 * 功能名称: 邳州登录页
 * 功能路径:
 * 功能参数:
 */

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

import { Modal, Popover } from 'antd';
import QRCode from 'qrcode.react';

import { Helmet, HelmetProvider } from 'react-helmet-async';
import { connect } from 'react-redux';
import { useHistory, withRouter } from '@wisdom-utils/runtime';
import { actionCreators } from '@/containers/App/store';
import classnames from 'classnames';
import moment from 'moment';
import QueueAnim from 'rc-queue-anim';
import defaultSetting from '../../../../../../../config/defaultSetting';
import LoginAction from '../../../login';
import styles from './index.less';
import Account from '../../../js/useAccount';
import { defaultApp } from '../../../../../../micro';
import logo from './images/logo.png';
import qrcodePng from './images/1.png';
import bg from './images/邳州背景.jpg';
const Cripples = require('@/assets/js/ripples/jquery.ripples');

const PopOvercontent = () => {
  const qrcodes = window.globalConfig && window.globalConfig.qrcode;
  if (qrcodes) {
    return <QRCode value={qrcodes} />;
  }
  return <span>手持APP下载未配置</span>;
};

const Login = forwardRef((props, _ref) => {
  const sliVerify = useRef();
  const loginFormRef = useRef();
  const formRef = useRef(null);
  const [status, setStatus] = useState('normal');
  const [show, setShow] = useState(false);
  const [autoLogin, setAutoLogin] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [type, setType] = useState('Account');
  const [visible, setVisible] = useState(false);
  const history = useHistory();
  const [action, setAction] = useState(() => new LoginAction(Object.assign({}, props, { history }), setVisible, false));
  const [dateObj, setDateObj] = useState({});

  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);
  };

  useEffect(() => {
    action &&
      action.events.on('loginSuccess', event => {
        setSubmitting(false);
        props.updateCurrentIndex && props.updateCurrentIndex(0);
        props.history.push(`/?client=${props.global.client}`);

        defaultApp();
      });
    action &&
      action.events.on('loginError', event => {
        setVisible(false);
        setSubmitting(false);
      });
    action &&
      action.events.on('loginVisible', status => {
        setVisible(status);
      });
    return () => {
      action && action.events && action.events.removeAllListeners('loginSuccess');
      action && action.events && action.events.removeAllListeners('loginError');
      action && action.events && action.events.removeAllListeners('loginVisible');
    };
  }, [props.loginMode]);

  useEffect(() => {
    setSubmitting(false);
  }, [visible]);

  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,
      welcome: null,
    };
    return <Account {...params} />;
  };
  /* eslint-disable */

  const handleWeek = () => {
    const weekOfDay = Number(moment().format('E'));

    let weekDayName = '';
    switch (weekOfDay) {
      case 1:
        weekDayName = '周一';
        break;
      case 2:
        weekDayName = '周二';
        break;
      case 3:
        weekDayName = '周三';
        break;
      case 4:
        weekDayName = '周四';
        break;
      case 5:
        weekDayName = '周五';
        break;
      case 6:
        weekDayName = '周六';
        break;
      case 7:
        weekDayName = '周日';
        break;
      default:
        weekDayName = '';
    }
    return weekDayName;
  };
  const onShow = () => {
    if (!show) {
      setShow(true);
    }
  };

  useEffect(() => {
    setTimeout(() => {
      onShow();
    }, 300);
    setTimeout(() => {
      $('.CarouselRipples').ripples({
        resolution: 800,
        dropRadius: 20, //px
        perturbance: 2,
      });
    }, 1000);
  }, []);
  useEffect(() => {
    return () => {};
  }, [show]);
  useEffect(() => {
    const timer = setInterval(() => {
      setDateObj({
        curTime: moment().format('HH:mm:ss'),
        week: handleWeek(),
        date: moment().format('YYYY/MM/DD'),
      });
    }, 1000);
    return () => {
      clearInterval(timer);
    };
  }, []);

  return (
    <HelmetProvider>
      <Helmet>
        <title>{props.global.title || defaultSetting.title}</title>
        <meta name="description" content={props.global.title || defaultSetting.title} />
      </Helmet>

      <div
        className={classnames(styles.pizhouLogin, 'pizhouLogin')}
        onClick={onShow}
        style={{ background: `url(${bg}) no-repeat center center`, backgroundSize: '100%' }}
      >
        {show ? (
          <div className={classnames(styles['wrapper'])}>
            <QueueAnim type="scale" duration={1000}>
              <div key={'innerwrapper'} className={classnames(styles['inner-wrapper'])}>
                <div className={styles['inner-center']}>
                  <div className={styles['welcome-title']}>汇一脉水 润邳州城 筑供水梦</div>
                  <div className={classnames(styles['inner-bg'], styles['login-part'])} ref={loginFormRef}>
                    {renderPlatform()}
                  </div>
                </div>
                <Popover
                  content={PopOvercontent}
                  title="扫码下载APP"
                  placement="right"
                  overlayClassName={'popover-style'}
                >
                  <img src={qrcodePng} alt="APP" className={styles['qrcode-box']} />
                </Popover>
              </div>
            </QueueAnim>

            <div key="loginheader" className={classnames(styles['login-header'])}>
              <QueueAnim type="left">
                <div key="logintitle" className={styles['left-title']}>
                  <div>
                    <img src={logo} alt="logo" />
                  </div>
                  <div className={styles['cn-title']}>{props.global.title || defaultSetting.title}</div>
                </div>
              </QueueAnim>
              <QueueAnim type="right">
                <div key="logintime" className={styles['right-timebox']}>
                  <div className={styles['curr-time']}>{dateObj.curTime}</div>
                  <div className={styles['curr-week-date']}>
                    <div className={styles['curr-week']}>{dateObj.week}</div>
                    <div className={styles['curr-date']}>{dateObj.date}</div>
                  </div>
                </div>
              </QueueAnim>
            </div>
          </div>
        ) : null}
        <div className={classnames(styles.CarouselRipples, 'CarouselRipples')} data-ripple="ripple" />

        <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));