import React, { forwardRef, useEffect, useRef, useState } from 'react';
import Zoom from 'react-reveal/Zoom';
import Fade from 'react-reveal/Fade';
import Slide from 'react-reveal/Slide';
import Roll from 'react-reveal/Roll';
import Pulse from 'react-reveal/Pulse';

import QueueAnim from 'rc-queue-anim';
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 { Swiper, SwiperSlide } from 'swiper/react';
import SwiperCore, { Autoplay } from 'swiper/core';
import $ from 'jquery';
import defaultSetting from '../../../../../../../config/defaultSetting';
import LoginAction from '../../../login';
import styles from './index.less';
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';
// import SwiperCore, { Autoplay, Navigation } from 'swiper/core';
// SwiperCore.use([Autoplay, Navigation]);
import 湖口润泉水源地 from './images/江西水投子公司图片/湖口润泉水源地.png';
import 会昌润泉石壁坑水库 from './images/江西水投子公司图片/会昌润泉石壁坑水库.png';
import 景德镇水务公司 from './images/江西水投子公司图片/景德镇水务公司.png';
import 景德镇水务新洋湖水厂 from './images/江西水投子公司图片/景德镇水务新洋湖水厂.png';
import 乐平润泉水务公司 from './images/江西水投子公司图片/乐平润泉水务公司.png';
import 南城润泉麻源水库1 from './images/江西水投子公司图片/南城润泉麻源水库1.png';
import 南城润泉麻源水库2 from './images/江西水投子公司图片/南城润泉麻源水库2.png';
import 南城润泉麻源水库3 from './images/江西水投子公司图片/南城润泉麻源水库3.png';
import 南康润泉龙华水厂 from './images/江西水投子公司图片/南康润泉龙华水厂.png';
import 南康润泉龙华水厂2 from './images/江西水投子公司图片/南康润泉龙华水厂2.png';
import 上高润泉第二水厂 from './images/江西水投子公司图片/上高润泉第二水厂.png';
import 上高润泉第二水厂平流沉淀池 from './images/江西水投子公司图片/上高润泉第二水厂平流沉淀池.png';
import 上高润泉水务公司 from './images/江西水投子公司图片/上高润泉水务公司.png';
import 上高润泉水务公司2 from './images/江西水投子公司图片/上高润泉水务公司2.png';
import 寻乌润泉大路水厂 from './images/江西水投子公司图片/寻乌润泉大路水厂.png';
import 永修润泉湖东水厂 from './images/江西水投子公司图片/永修润泉湖东水厂.png';
import 'swiper/swiper-bundle.css';
const Cripples = require('@/assets/js/ripples/jquery.ripples');
SwiperCore.use([Autoplay]);
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 timeRef = useRef();
  const formRef = useRef(null);
  const [status, setStatus] = useState('normal');
  const [num, setNum] = useState(0);
  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 [img, setImg] = useState(
    [
      '湖口润泉水源地',
      '会昌润泉石壁坑水库',
      '景德镇水务公司',
      '景德镇水务新洋湖水厂',
      '乐平润泉水务公司',
      '南城润泉麻源水库1',
      '南城润泉麻源水库2',
      '南城润泉麻源水库3',
      '南康润泉龙华水厂',
      '南康润泉龙华水厂2',
      // '上高润泉第二水厂',
      '上高润泉第二水厂平流沉淀池',
      '上高润泉水务公司',
      // '上高润泉水务公司2',
      '寻乌润泉大路水厂',
      // '永修润泉湖东水厂',
    ].sort(() => 0.5 - Math.random()),
  );
  const [imgObj, setimgObj] = useState({
    湖口润泉水源地,
    会昌润泉石壁坑水库,
    景德镇水务公司,
    景德镇水务新洋湖水厂,
    乐平润泉水务公司,
    南城润泉麻源水库1,
    南城润泉麻源水库2,
    南城润泉麻源水库3,
    南康润泉龙华水厂,
    南康润泉龙华水厂2,
    //  上高润泉第二水厂,
    上高润泉第二水厂平流沉淀池,
    上高润泉水务公司,
    //   上高润泉水务公司2,
    寻乌润泉大路水厂,
    //   永修润泉湖东水厂,
  });

  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(() => {
  //  setTimeout(() => {
  //    onShow();
  //  }, 300);
    setTimeout(() => {
      $('.CarouselRipples').ripples({
        resolution: 800,
        dropRadius: 20, //px
        perturbance: 2,
      });
    }, 1000);
  }, []);
  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);
      //   clearInterval(timer1)
    };
  }, []);
  useEffect(() => {
    if (timeRef.current) clearTimeout(timeRef.current);
    timeRef.current = setTimeout(() => {
      if (num < 12) {
        setNum(num + 1);
      } else {
        setNum(0);
      }
    }, 5000);
  }, [num]);
  const toLink = () => {
    window.open('http://gis.panda-water.cn/jiangxi/index.html');
  };
  const tabChange = key => {
    form.resetFields();
    setLoginType(key);
  };
  const getBJ = (url) => {
    return (
      <div
        style={{ background: `url(${url}) no-repeat`,  transition: 'background-image 1s' }}
        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>
          <QueueAnim type="scale" duration={1000}>
            <div key={'innerwrapper'} style={{position: 'relative',zIndex:2,backdropFilter: 'blur(6px)'}} className={styles['inner-center']}>
              <Tooltip title="打开网站下载">
                <div className={styles.linkBox} onClick={toLink}>
                  <img style={{ width: '14px', marginRight: '4px' }} src={require('./images/下载.png')} alt="" />
                  点击下载APP
                </div>
              </Tooltip>

              <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>
            </QueueAnim>
        </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>
        <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 className={styles['lbt']}>
          <div
            onClick={() => {
              if (num > 0) {
                setNum(num - 1);
              } else {
                setNum(12);
              }
            }}
          >
            {' '}
            <img style={{ width: '30px', cursor: 'pointer' }} src={require('./images/左.png')} alt="" />
          </div>
          <div className={styles['divImgAll']}>
            <Swiper
              autoplay={{ delay: 5000 }}
              loop
              spaceBetween={1}
              slidesPerView={12}
              onSlideChange={() => console.log('slide change')}
              onSwiper={swiper => console.log(swiper)}
              style={{ width: 'calc(100% - 340px)', height: '100%' }}
            >
              {img.map((v, i) => {
                return (
                  <SwiperSlide>
                    <div
                      onClick={() => {
                        setNum(i);
                      }}
                      className={styles['divT']}
                      style={{ cursor: 'pointer', position: 'relative' }}
                    >
                      <img
                        title={v}
                        style={{
                          border: i == num ? '2px solid #FFDFA0' : '0px',
                          width: i == num ? '82px' : '82px',
                          height: i == num ? '82px' : '82px',
                        }}
                        src={require(`./images/江西水投子公司图片/${v}.png`)}
                        alt=""
                      />
                      <div
                        style={{
                          position: 'absolute',
                          overflow: 'hidden',

                          whiteSpace: 'nowrap',
                          color: 'white',
                          textOverflow: 'ellipsis',
                          top: '61px',
                          width: '82px',
                          fontSize: '12px',
                          textAlign: 'center',
                          background: 'rgba(0,0,0,0.4)',
                       //   opacity: 0.4
                        }}
                      >
                        {v.indexOf('景德镇')>-1?'景德镇':v.substring(0, 4)}
                      </div>
                    </div>
                  </SwiperSlide>
                );
              })}
            </Swiper>
          </div>
          <div
            onClick={() => {
              if (num < 12) {
                setNum(num + 1);
              } else {
                setNum(0);
              }
            }}
          >
            {' '}
            <img style={{ width: '30px', cursor: 'pointer' }} src={require('./images/右.png')} alt="" />
          </div>
        </div>
      </div>
    
    );
  };
  return (
    <HelmetProvider>
      <Helmet>
        <title>{props.global.title || defaultSetting.title}</title>
        <meta name="description" content={props.global.title || defaultSetting.title} />
      </Helmet>
     
      {getBJ(imgObj[img[num]])}
    
    </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));