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

import { Modal, Popover, Form, Tooltip } from 'antd';
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 moment from 'moment';
import classnames from 'classnames';
import QRCode from 'qrcode.react';
import defaultSetting from '../../../../../../../config/defaultSetting';
import LoginAction from '../../../login';
import styles from './index.less';
import Account from '../../../js/useAccount';
import FormLogin from './Account';
import { defaultApp } from '../../../../../../micro';
import logoPng from './images/8.png';
import qrcodePng from './images/1.png';
import welcomePng from './images/4.png';

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 [form] = Form.useForm();
  const sliVerify = useRef();
  const loginFormRef = useRef();
  const formRef = useRef(null);
  const [status, setStatus] = useState('normal');

  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 [loginType, setLoginType] = useState('OA账号');
  const handleSubmit = values => {
    /* eslint-disable */
    action &&
      (type === 'Account'
        ? loginType === 'OA账号'
          ? action.loginHandlerJiangXi(values.userName, values.password, null, autoLogin, sliVerify)
          : 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}`);
        // window.share.event.emit('triggerMicro', props.global);
        // initMicroApps();
        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 = {
      form: form,
      fromRef: formRef,
      type,
      setType,
      status,
      submitting,
      autoLogin,
      setAutoLogin,
      action,
      onSubmit: handleSubmit,
      loginMode: props.loginMode,
      updateLoginMode: props.updateLoginMode,
      welcome: null,
    };
    // return <Account {...params} />;
    return <FormLogin {...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 0:
        weekDayName = '周日';
        break;
      default:
        weekDayName = '';
    }
    return weekDayName;
  };

  useEffect(() => {
    const timer = setInterval(() => {
      setDateObj({
        curTime: moment().format('HH:mm:ss'),
        week: handleWeek(),
        date: moment().format('YYYY/MM/DD'),
      });
    }, 1000);
    return () => {
      clearInterval(timer);
    };
  }, []);
  const toLink = () => {
    window.open('http://gis.panda-water.cn/jiangxi/index.html');
  };
  const tabChange = key => {
    form.resetFields();
    setLoginType(key);
  };
  return (
    <HelmetProvider>
      <Helmet>
        <title>{props.global.title || defaultSetting.title}</title>
        <meta name="description" content={props.global.title || defaultSetting.title} />
      </Helmet>
      <div className={classnames(styles.lvchenglogin, 'lvcheng')}>
        <div className={styles['inner-wrapper']}>
          <div className={styles['title-image-box']}>
            <img
              src={
                props.global &&
                props.global.transformDevAssetsBaseURL &&
                props.global.transformDevAssetsBaseURL(props.global.logo)
              }
              alt=""
              className={styles['title-image']}
            />
            <span className={styles['title-name']}>{props.global.title}</span>
          </div>
          <div className={styles['inner-center']}>
            <div className={styles['welcome-title']}>
              <div
                className={classnames(styles.tabItem, { [styles.tabActive]: loginType === 'OA账号' })}
                onClick={() => tabChange('OA账号')}
              >
                OA账号
              </div>
              <div
                className={classnames(styles.tabItem, { [styles.tabActive]: loginType === '平台账号' })}
                onClick={() => tabChange('平台账号')}
              >
                平台账号
              </div>
            </div>
            <div className={classnames(styles['inner-bg'], styles['login-part'])} ref={loginFormRef}>
              {renderPlatform()}
            </div>
            {/* <Popover content={PopOvercontent} title="扫码下载APP" overlayClassName={'popover-style'}>
              <img src={qrcodePng} alt="APP" className={styles['qrcode-box']} />
            </Popover> */}
          </div>
        </div>
        <div className={styles['login-header']}>
          {/* <div className={styles['left-title']}>
                        <img src={logoPng} alt='logo' className={styles['logo-png']}/>
                        <div className={styles['cn-title']}>南宁市二次供水管理平台</div>
                    </div> */}
          <div 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>
        </div>
        <Tooltip title="打开网站下载">
          <div className={styles.linkBox} onClick={toLink}>
            <img src={require('./images/9.png')} alt="" />
            APP下载
          </div>
        </Tooltip>

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