/* eslint-disable */
/*
 * @Author: xule;
 * @Date: 2021-11-22
 * @Description:榆林登录页;
 */
import React from 'react';
import styles from './style/yulin.less'
import classNames from 'classnames';
import { connect } from 'react-redux';
import { CheckOutlined } from '@ant-design/icons';
import { withRouter } from '@wisdom-utils/runtime';
import Logo from '@/assets/images/login/榆林/标题.png'
import Code from '@/assets/images/login/榆林/小程序@2x.png'
import MyHead from '@/assets/images/login/榆林/d-我的.png'
import PassWord from '@/assets/images/login/榆林/密码.png'
import Close from '@/assets/oa/login/close.png'
import Open from '@/assets/oa/login/open.png'
import LoginAction from '../login';
import { actionCreators } from '@/containers/App/store';
import Cookies from 'js-cookie';
import QRCode from 'qrcode.react';
import { initMicroApps } from '../../../../micro';
const Logger = logger('login');
// 、登录页
class InfoLogin extends React.Component {
  state = {
    loginStyle: false, //true  账号密码登录 false  扫码登录
    isOpen: false,   //查看密码
    isRember: false, //记住密码
    ddOrWeixin: '',
    qrcode: '',//二维码
    codeLenth: 1,
    time: '',
    week: '',
    date: ''
  }
  componentDidMount() {
    let action = new LoginAction(this.props, false, true)
    this.loginEvent(action);
    this.renderQRcode();
    this.renderTime();
  }
  renderQRcode() {
    var me = this;
    var list = globalConfig.qrcode ? globalConfig.qrcode.split("|") : [];
    let str = [];
    if (list.length) {
      list.forEach(function (val, index) {
        if (val && val.replace(/ /g, "").length > 0) {
          str.push(me.creatCodeHtml(val, index));
        }
      })
    } else {
      str.push(<span>手持APP下载未配置</span>);
    }
    this.setState({
      qrcode: str,
      codeLenth: list.length
    })
  }
  renderTime() {
    let me = this;
    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()}`;
      me.setState({
        time,
        week: weekday[date.getDay()],
        date: date.pattern('yyyy/MM/dd'),
      })
    }, 1000);

  }
  creatCodeHtml(val, index) {
    return (
      <div className={('codeCase codeCase' + index)}>
        <QRCode value={val.replace(/{ip}/ig, globalConfig.ip).split('=')[0]} />
        <div className={styles.codeText}>{val.replace(/{ip}/ig, globalConfig.ip).split('=')[0]}</div>
      </div>);
  }
  // 切换登录方式
  changeloginStyle = () => {
    const { ddOrWeixin } = this.state
    this.setState({
      loginStyle: !this.state.loginStyle,
      ddOrWeixin: ddOrWeixin ? '' : 'dingding'
    }, () => {
      Cookies.set('loginMode', `${this.state.ddOrWeixin ? 'dingding' : 'pdw'}`, {
        path: '/',
      });
      if (this.state.ddOrWeixin === 'dingding') {
        let action = new LoginAction(this.props, false, true)
        action.loginByDD()
      }
    })
  }
  // 查看密码
  seePassWord = (e) => {
    this.setState({
      isOpen: !this.state.isOpen
    })
  }
  // 记住密码
  remberWord = () => {
    this.setState({
      isRember: !this.state.isRember
    })
  }
  // 输入框变化
  handleForm = (e) => {
    const target = e.target
    // 判断事件类型，如果是checkbox返回checked值，不是返回文本框的value值
    const value = target.type == 'checkbox' ? target.checked : target.value;
    // 获取文本框的name值
    const name = target.name
    this.setState({
      [name]: value
    })
  }
  onKeyDownchange(e){
    if(e.keyCode == 13){
      this.loginToWeb5();
  }
  }
  // 登录
  loginToWeb5 = () => {
    const { loginName, passWord, isRember } = this.state
    let action = new LoginAction(this.props, false, true)
    action.loginHandler(loginName, passWord, null, isRember, false)
    this.loginEvent(action)

  }
  // 登录成功事件
  loginEvent(action) {
    action.globalConfig = this.props.global;
    this.props.updateCurrentIndex && this.props.updateCurrentIndex(-1);
    action && action.events.on('loginSuccess', event => {
      this.props.updateCurrentIndex && this.props.updateCurrentIndex(0);
      this.props.history.push(`/?client=${this.props.global.client}`);
      // window.share.event.emit('triggerMicro', this.props.global);
      initMicroApps();
    });
    action && action.events.on('loginError', event => {

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

    });
  }
  render() {
    const { loginStyle, isOpen, isRember, loginName, passWord, qrcode, codeLenth, time, week, date } = this.state
    return (
      <div className={styles.InfoBg}>
        <div className={styles.IBtimeBox}>
          <span className={styles.IBTtime}>{time}</span>
          <span className={styles.IBTweek}>{week}</span>
          <span className={styles.IBTdate}>{date}</span>
        </div>
        <div className={styles.loginBg}>
          {/* 标题 */}
          <div className={styles.IBtitle}>
            <img src={Logo} alt="" />
          </div>
          <div className={styles.IBcenter}>
            <div className={styles.IBCleft}></div>
            <div className={styles.IBCright}>
              <p className={styles.IBCRnamec}>榆林清水工业园智慧水务平台</p>
              <p className={styles.IBCRnameE}>Smart Water Platform of Yulin Qingshui Industrial Park</p>

              {/* 登录主题 */}
              <form className={styles.loginForm} style={{ display: loginStyle ? 'none' : '' }}>
                <div className={styles.formgroup}>
                  <img className={styles.IBCRimg} src={MyHead} alt="" />
                  <input type="text" className={styles.inputLg} id='loginName' name='loginName' value={loginName} onChange={this.handleForm} placeholder="请输入你的用户名" />
                </div>
                <div className={styles.formgroup}>
                  <img className={styles.IBCRimg} src={PassWord} alt="" />
                  <input type={isOpen ? 'text' : "password"} className={styles.inputLg} onKeyDown={e=> this.onKeyDownchange(e)} id='passWord' name='passWord' value={passWord} onChange={this.handleForm} placeholder="请输入你的密码" />
                  <img className={styles.eyes} src={isOpen ? Open : Close} alt="" onMouseDown={(e) => this.seePassWord(e)} onMouseUp={(e) => this.seePassWord(e)} />
                </div>
                <div className={styles.formgroup} style={{ position: 'relative', marginTop: '20px' }}>
                  <label className={classNames(isRember ? (styles.rmpwdInput, styles.active) : styles.rmpwdInput)} onClick={() => this.remberWord()}>
                    <CheckOutlined style={{ display: isRember ? '' : 'none' }} />
                  </label>
                  <span style={{ color: '#9FA8B3', marginLeft: '10px', fontSize: '14px' }}>记住密码</span>
                </div>
                <div className={styles.submitBtn} onClick={this.loginToWeb5}>登录</div>
              </form>
            </div>
            <div className={styles.codeBox}>
              <img className={styles.codeImg} src={Code} alt="" />
              <div className={styles.codeBig} style={{ width: codeLenth * 148 + 'px' }}>
                {qrcode}
              </div>
            </div>
          </div>
        </div>
      </div>

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

