import React from 'react';
import ReactDOM from 'react-dom';
import { Aes } from './tools/index';
import { HashRouter } from 'react-router-dom';
import { AppContainer } from 'react-hot-loader';
import { $http } from 'containers/config/https';
import store from './store'
// import moment from 'moment';
// 全局安装moment然后时间控件内部的也变成中文了
import 'moment/locale/zh-cn';

import App from './App.js';//引入自己写的组件(class)
import './assets/css/index.css';//引入样式
import './assets/less/index.less';//引入样式
import LoginRegister from './LoginRegister.js';//引入自己写的组件(class)
// import registerServiceWorker from './registerServiceWorker';

import "@babel/polyfill";
import "whatwg-fetch";
import './plugins'; // 全局方法注册

// 禁止后退
history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
  history.pushState(null, null, document.URL);
});

// 浮点的问题造成的(计算机准确的保存浮点) 重写Number.prototype.toFixed()方法 解决四舍六入五看双的  类似 2.445.toFixed(2)=2.44  的问题
Number.prototype.toFixed = function (d) {
  var s = this + "";
  if (!d) d = 0;
  if (s.indexOf(".") == -1) s += ".";
  s += new Array(d + 1).join("0");
  if (new RegExp("^(-|\\+)?(\\d+(\\.\\d{0," + (d + 1) + "})?)\\d*$").test(s)) {
    var s = "0" + RegExp.$2, pm = RegExp.$1, a = RegExp.$3.length, b = true;
    if (a == d + 2) {
      a = s.match(/\d/g);
      if (parseInt(a[a.length - 1]) > 4) {
        for (var i = a.length - 2; i >= 0; i--) {
          a[i] = parseInt(a[i]) + 1;
          if (a[i] == 10) {
            a[i] = 0;
            b = i != 1;
          } else break;
        }
      }
      s = a.join("").replace(new RegExp("(\\d+)(\\d{" + d + "})\\d$"), "$1.$2");

    } if (b) s = s.substr(1);
    return (pm + s).replace(/\.$/, "");
  } return this + "";
}

export default class Index extends React.Component {
  constructor(props) {
    super(props)
    var userData = JSON.parse(sessionStorage.getItem('userData'));
    this.state = {
      loginIs: 'N',
      userData: userData,
    }
  }

  componentDidMount() {
    // 获取path路径 https://np.h03.p0551.com/his/#/17050013?admID=943480&reqNo=H23O202308280006
    let path = window.location && window.location.href ? window.location.href.split('#')[1] : '';
    if (path.indexOf('/17050013') > -1) { // 视光外部链接直接打开系统界面
      if (sessionStorage.getItem('loginIsSession') !== 'Y') {
        // 是否是pc端
        var fixedMAC = { hostName: '', ipv4: '', ipv6: '', mac: '' }
        window.sessionStorage.setItem('ipConfig', JSON.stringify(fixedMAC));
        setTimeout(() => {
          let userName = 'C019999';
          let passWord = Aes.Encrypt('abc123');
          let locID = '1031';
          let groupID = '397';
          let hospID = '82';
          this.handleAutoLogin(userName, passWord, locID, groupID, hospID);
        }, 300)
      }
    }
    // 监听store的变化
    store.subscribe(() => {
      const state = store.getState();
      let loginIs = state.userRedux.loginIs;
      if (loginIs !== this.state.loginIs) {
        this.setState({
          loginIs,
        })
      }
    })
  }

  // 自动登录
  handleAutoLogin = (userName, passWord, locID, groupID, hospID) => {
    let data = {
      params: [{
        userName: userName,
        passWord: passWord,
        loginLocID: locID,
        loginGroupID: groupID,
        loginHospID: hospID,
        deviceID: '',
        IP: '',
        userLogonType: '03',
        mac: '',
      }]
    };
    $http.post('urlDeault', this, {
      code: '1011',
      data: data,
      success: function (res) {
        if (res.errorCode === '0') {
          let userData = Object.assign({}, res.result[0]);
          window.sessionStorage.setItem('userData', JSON.stringify(userData));
          window.sessionStorage.setItem('queryIP', '172.17.2.8');
          window.sessionStorage.setItem('productIP', '172.17.2.8');
          window.sessionStorage.setItem('EMRIP', 'https://172.16.1.6/EMR');
          window.sessionStorage.setItem('loginIsSession', 'Y');
          this.setState({ loginIs: 'Y' });
        }
      }
    });
  }

  render() {
    const { loginIs } = this.state;
    return (
      <HashRouter>
        <div className="app-dom">
          <LoginRegister {...this.props} />
          {loginIs === 'Y' ? <App {...this.props} /> : ''}
          {
            sessionStorage.getItem('loginIsSession') &&
              sessionStorage.getItem('loginIsSession') === 'Y' &&
              loginIs !== 'Y'
              ?
              <App  {...this.props} /> : ''
          }
        </div>
      </HashRouter>
    )
  }
};

// ReactDOM.render(
//   <Index />,
//   document.getElementById('root')
// );

const render = Component => {
  ReactDOM.hydrate(
    <AppContainer>
      <Component />
    </AppContainer>,
    document.getElementById('root')
  )
};

render(Index);

if (module.hot) {
  module.hot.accept(Index, () => {
    const NextApp = Index.default;
    render(NextApp)
  })
}
// registerServiceWorker();
//registerServiceWorker就是为react项目注册了一个service worker，
// 用来做资源的缓存，这样你下次访问时，就可以更快的获取资