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

import {
  Alert,
  Checkbox,
  message,
  Modal,
  Popover,
} from 'antd';
import classNames from 'classnames';
import { dom } from 'kit_utils';
import QRCode from 'qrcode.react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';

import { actionCreators } from '../../../containers/App/store';
import LoginForm from './components/Login';
import LoginAction from './login';
import styles from './style.less';

const { UserName, Password, Submit } = LoginForm;

const LoginMessage = ({ content }) => (
  <Alert
    style={{
      marginBottom: 2,
    }}
    message={content}
    type="error"
    showIcon
  />
);

const useRenderQcode = (props) => {
  const qrcodes = props.qrcode.split("|");
  const qcodeComponent = (url) => {
    return (<img src={url} className="QuickMark-cont" style={{width: '150px', height: '150px'}}/>)
  }
  let 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={index}>
            <Popover  placement="top" content={qcodeComponent("https://panda-water.cn/web4/assets/images/小程序二维码.jpg")}>
              <div className={styles['icon-Container']}>
                  <span className={styles.Wechat}></span>
                  <span className="iconText WechatText">Wechat</span>
              </div>
            </Popover>
          </div>
        )
        break;
      case "智联小程序":
        element.push(
          <div className={classNames(styles["quickMark-single"], "miniIOT-single")} key={index}>
            <Popover placement="top" content={qcodeComponent("https://panda-water.cn/web4/assets/images/智联小程序二维码.jpg")}>
              <div className={styles['icon-Container']}>
                  <span className={styles.Wechat}></span>
                  <span className={classNames(styles.iconText, styles.WechatText)}>熊猫智联</span>
              </div>
            </Popover>
          </div>
        )
        break;
      case "Android":
        element.push(
          <div className={classNames(styles["quickMark-single"], "miniIOT-single")} key={index}>
            <Popover placement="top" content={<QRCode value={firstValue[1].replace(/{ip}/ig, props.ip || window.location.host)}/>}>
              <div className={styles['icon-Container']}>
                  <span className={styles.Android}></span>
                  <span className={classNames(styles.iconText, styles.AndroidText)}>Android</span>
              </div>
            </Popover>
          </div>
        )
        break;
      case "iPhone":
        element.push(
          <div className={classNames(styles["quickMark-single"], "miniIOT-single")} key={index}>
            {/* <img src="https://panda-water.cn/web4/assets/images/智联小程序二维码.jpg" class="QuickMark-cont"/> */}
            <Popover placement="top" content={<QRCode value={firstValue[1].replace(/{ip}/ig, props.ip || window.location.host)}/>}>
              <div className={styles['icon-Container']}>
                  <span className={styles.Wechat}></span>
                  <span className={classNames(styles.iconText, styles.iphoneText)}>iPhone</span>
              </div>
            </Popover>
          </div>
        )
        break;
      default:
        if(item && item.replace(/ /g, "").length > 0) {

        }
        break;    
    }
  })
  return element;

}

const Login = props => {

  const videoRef = useRef();
  const loginRef = useRef();
  const timeRef = useRef();
  const titleRef = useRef();
  const sliVerify = useRef();
  const loginFormRef = useRef();
  const footerRef = useRef();
  const [status, setStatus ] = useState('normal');
  const [autoLogin, setAutoLogin] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [currentDate, setCurrentDate] = useState({});
  const [type, setType] = useState('account');
  const [visible, setVisible] = useState(false)
  const [action, setAction] = useState(() => {
    return new LoginAction(props)
  })
  const handleSubmit = values => {
    action && action.loginHandler(values.userName, values.password, null, false, sliVerify);
    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 => {
      console.log(event)
      message.error('账户或密码错误')
      setSubmitting(false)
    })

    action && action.events.on('loginVisible', status => {
      setVisible(status)
    })
  };

  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: time,
        dayofweek: weekday[date.getDay()],
        date: date.pattern('yyyy/mm/dd'),
      });
    }, 1000);
    return () => {
      loginTimeInterval && clearInterval(loginTimeInterval);
    };
  }, []);

  useEffect(() => {
    if (videoRef) {
      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]);

  const renderAddons = useRenderQcode(props.global)

  return (
    <div className={styles.main}>
      <video
        src="https://panda-water.cn/web4/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={`https://panda-water.cn/web4/${window.globalConfig.logo}`}
          />
          <div
            className={classNames(
              styles.titleCase,
              styles.caseHide,
              'animated',
            )}
            ref={titleRef}
          >
            <span className={styles.title}>{window.globalConfig.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']}>
            <LoginForm
              activeKey={type}
              onTabChange={setType}
              onSubmit={handleSubmit}
            >
              {status === 'error' && type === 'account' && !submitting && (
                <LoginMessage content="账户或密码错误" />
              )}
              <UserName
                name="userName"
                placeholder="请输入你的用户名"
                rules={[
                  {
                    required: true,
                    message: '请输入用户名!',
                  },
                ]}
              />
              <Password
                name="password"
                placeholder="请输入你的密码"
                rules={[
                  {
                    required: true,
                    message: '请输入密码！',
                  },
                ]}
              />
              <div>
                <Checkbox
                  checked={autoLogin}
                  onChange={e => setAutoLogin(e.target.checked)}
                >
                  下次自动登录
                </Checkbox>
              </div>
              <Submit loading={submitting}>登录</Submit>
            </LoginForm>
          </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"></span>
            <a id="qrcode" href="javascript:void(0);"><span class="glyphicon glyphicon-qrcode" role="button" title="手持APP下载"></span></a>
          </span>
        </span>
      </div>
      <Modal
        centered
        visible={visible}
        width={340}
        footer={null}
        closable={false}
        bodyStyle={{padding: '15px'}}
      >
        <div ref={sliVerify}></div>
      </Modal>
    </div>
  );
};
const mapStateToProps = state => {
  return {
    global: state.getIn(['global', 'globalConfig']),
  };
};

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