import React, { PureComponent } from 'react';
import { connect } from 'dva';
import moment from 'moment';
// import { Link } from 'dva/router';
import { Form, Input, Button, Checkbox, Icon, Modal, Row, Col } from 'antd';
import CryptoJS from 'crypto-js';
import IEBrowserPrompt from '../../components/Pro/IEBrowserPrompt/IEBrowserPrompt';
import Utils from '../../common/bcx_utils';
import { domainConfig } from '../../utils/config';
import {
  accesstoken,
  systemComVaseInfoGet,
  systemOauthGetUserMenus,
  getPublicKey
} from '../../services/api';
import Logo from '../../components/Logo';

import './LogOn.less';
import { stat } from 'fs';

import updateTipImgUrl from '../../../public/update.gif';
import comImg from '../../assets/images/com_login.png';
import personImg from '../../assets/images/personal_login.png';
const store = require('store');

const FormItem = Form.Item;

@connect(state => ({
  register: state.register,
  netErr: state.global.netErr
}))
@Form.create()
export default class logOn extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      type: 'account',
      redirect_uri: '',
      publickKey: '',
      isIEBrowser: false, //是否IE浏览器

      initialState: true, //初始状态给一个选择框，让用户选择登陆方式(只使用企业登陆的时候将状态改成false就可以了)
      loginType: 0, // 0企业登陆 1 自然人登陆
      provinace: '',   // 自然人登陆选择的省份,
      provinaces: [
          {
            name: '广西', 
            url: 'http://gx.baibaodun.cn//login.jsp'
          },
          {
            name: '陕西', 
            url: 'http://sn.baibaodun.cn//login.jsp'
          },
          {
            name: '宁夏', 
            url: 'http://222.75.71.181:11180//login.jsp'
          },
          {
            name: '北京', 
            // url: 'http://1.202.89.254:8801/ars-web/login.jsp'
            url: 'http://bj.baibaodun.cn:8801/ars-web/login.jsp'
          }
        ]
    };
  }

  /**
   * 生命周期
   */
  componentWillMount() {
    // document.title = domainConfig.getName('');
    document.title = domainConfig.name;
  }
  componentDidMount() {
    getPublicKey({}).then(res => {
      this.setState({
        publickKey: res.data
      });
    });
    this.isShowBrowserTips();
    if (document.querySelector("#footer")) {
      // 隐藏底部
      document.querySelector("#footer").style.display = "none";
    }
  }
  componentWillUnmount() {
    if (document.querySelector("#footer")) {
      // 隐藏底部
      document.querySelector("#footer").style.display = "block";
    }
  }
  /***
   * 事件方法
   */
  encrypt(msg, key, iv) {
    return CryptoJS.AES.encrypt(msg, key, {
      iv,
      padding: CryptoJS.pad.Pkcs7,
      mode: CryptoJS.mode.CBC
    });
  }

  slectProvince = ({url}) => {
    // this.setState({
    //   provinace,
    //   loginType: 1,
    //   initialState: false
    // });
    window.location.href = url;
  }
  decrypt(cipherText, key, iv) {
    return CryptoJS.AES.decrypt({ ciphertext: cipherText }, key, {
      iv,
      padding: CryptoJS.pad.Pkcs7,
      mode: CryptoJS.mode.CBC
    });
  }

  cancel = mode => {
    this.setState({
      isIEBrowser: mode
    });
  };

  //调用判断浏览器方法
  isShowBrowserTips = () => {
    if (Utils.isIEBrowser()) {
      this.setState({
        isIEBrowser: true
      });
    }
  };

  handleSubmit = e => {
    e.preventDefault();
    const { type } = this.state;
    this.props.form.validateFields({ force: true }, (err, values) => {
      const publickKey = CryptoJS.enc.Base64.stringify(
        CryptoJS.enc.Utf8.parse(this.state.publickKey)
      );
      const key = CryptoJS.enc.Base64.parse(publickKey);
      const iv = CryptoJS.enc.Base64.parse(publickKey);

      const encrypted = this.encrypt(values.password, key, iv);
      const cipherText = encrypted.ciphertext.toString();

      if (!err) {
        accesstoken({
          username: values.username,
          password: cipherText,
          redirect_uri: this.state.redirect_uri,
          public_key: this.state.publickKey
        }).then(
          data => {
            if (data.retType === '0') {
              this.systemOauthGetUserMenus(values.username);
            }
          },
          err1 => {
            console.log(err1, 'accesstoken-err');
          }
        );
        this.props.dispatch({
          type: `login/${type}Submit`,
          payload: values
        });
      }
    });
  };

  //获取用户登陆菜单-是否有菜单,没有菜单弹框提示且不能登录
  systemOauthGetUserMenus = (username) => {
    systemOauthGetUserMenus({}).then(
      response => {
        // 储存时间用于控制时间控件
        window.sessionStorage.setItem('requestDate', moment(response.date).valueOf());
        this.props.dispatch({
          type: 'global/saveMenuInfo',
          payload: response.data
        });
        if (response.data && JSON.stringify(response.data) === '[]') {
          Modal.info({
            title: '您的账号未授权登录企业端，请联系企业管理员！',
            okText: '确定',
            onOk() {}
          });
        } else {
          this.systemComVaseInfoGet();
          // //获取并登录im
          // this.props.dispatch({
          //   type: `global/imLogin`,
          //   payload: {
          //     username
          //   }
          // });
          //是否有企业菜单,无企业菜单，不能点击公司名
          Array.isArray(response.data)
            ? response.data.forEach(val => {
                if (val.menuId && val.menuId === '10000000') {
                  store.set('isHasEnterpriseMenu', {
                    isHasEnterpriseMenu: val.isActive
                  });
                }
              })
            : null;
        }
      },
      err => {
        console.log(err, 'systemOauthGetUserMenus-err-获取用户登陆菜单');
      }
    );
  };

  systemComVaseInfoGet = () => {
    systemComVaseInfoGet({}).then(
      response => {
        if (response.data === '' || response.data.comId === '') {
          this.props.history.push(
            '/user/PersonalRegistrationResult?type=download'
          );
          return;
        }
        this.props.dispatch({
          // type: "global/companyInfo",
          // 暂时直接派发到下一级
          type: 'global/getCompanyInfo',
          payload: response.data
        });

        //登录后是否是否展示内容,默认 欢迎页面
        store.set('isShowContent', { isShowContent: false });

        if (window.top === window.self) {
          this.props.history.push('/');
        } else {
          const url = window.location.href.split('#')[0];
          window.top.location = url + '#/';
        }
      },
      err => {
        console.log(err, 'systemComVaseInfoGet-err-获取企业详情');
      }
    );
  };

  render() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    const { type } = this.state;
    const { prefix, name } = domainConfig;
    return (
      <div className='logOn'>
        {
          prefix!='yaba'&&<div
          className='login-header'
          style={{ display: window.top !== window.self && 'none' }}
        >
          <div className='head-portrait'>
            {
              prefix == 'qiye' &&
              <Logo alt='百保盾' />
            }
            {
              prefix != 'qiye' &&
              <span style={{fontSize: 24}}>{name}</span>
            }
          </div>
        </div>
        }
        
          {/* <div className="head-portrait-register">
          <span
          style={{ cursor: "pointer" }}
          onClick={() => this.props.history.push("Enroll")}
          >
          注册
          </span>
          </div> */}
        <div
          className='login-main-con'
          style={{
            minHeight: prefix=='yaba'?`calc(100vh)`:'calc(100vh - 165px)',
            paddingTop: window.top !== window.self && '0px',
            background: prefix=='yaba'?`url("${require('../../../public/login_bg_yaan.png')}")`:`url("${require('../../../public/login-bg.png')}")`,
            position: 'relative'
          }}
        >
          {
            prefix=='yaba'&&<div
            className='login-header-yaan'
            style={{ display: window.top !== window.self && 'none' }}
          >
            <div className='head-portrait-yaan'>
              {
                prefix == 'qiye' &&
                <Logo alt='百保盾' />
              }
              {
                prefix != 'qiye' &&
                <span>{name}</span>
              }
            </div>
          </div>
          }
        {/* 是否在升级 */}
          {!this.props.netErr ? (
            /** 展示初始化窗口，让用户选择登陆方式 **/
            this.state.initialState ? (
              <div className="login_types" style={{
                top:prefix=='yaba'?'250px':'100px',
                opacity:prefix=='yaba'?'90%':'100%'
                }}>
                <Row>
                  <Col className="gutter-row" span={12}>
                    <p className="login_title">企业登录</p>
                    <div className="img_box">
                      <img src={comImg} alt="公司"/>
                    </div>
                    <Button onClick={() => {
                      this.setState({
                        initialState: false,
                        loginType: 0
                      });
                    }} className="btn" type="primary">登录</Button>
                    <p className="introduce">已注册开通企业的用户请登录，如保安从业单位、风险评估机构、活动承办单位、行业协会、政府单位等。</p>
                  </Col>
                  <Col className="gutter-row" span={12}>
                  <p className="login_title">自然人登录</p>
                    <div className="img_box">
                      <img src={personImg} alt="自然人"/>
                    </div>
                    <Button onClick={() => {
                      this.setState({
                        loginType: 1
                      });
                    }} className="btn" type="primary">登录</Button>
                    <p className="introduce">已注册自然人账号的用户请登录，以自然人名义进行保安服务许可备案申报、报名参加保安员资格证考试等。</p>
                  </Col>
                </Row>
                <Modal
                  className="choose_provinces_modal"
                  title="请选择所属省份"
                  onCancel={() => {
                    // 恢复初始状态
                    this.setState({
                      loginType: 0
                    });
                  }}
                  visible={this.state.provinace == ''&& this.state.loginType == 1}
                >
                  {this.state.provinaces.map((item, index) => {
                    return (
                      <Button
                        key={index}
                        onClick={() => {this.slectProvince(item)}}
                        className="province_btn"
                      >
                        {item.name}
                      </Button>
                    );
                  })}


                  <p className="tip">
                    注：仅限已落地开通的省份进行自然人申请开通服务，请准确选择您所属的省份。

若您所在省份不在以下列表中，请联系当地公安或在线客服进行咨询（400-662-9696）。
                  </p>
                </Modal>
              </div>
            ): (
              <div
              className='logon-content'
              style={{
                padding: window.top !== window.self && '0px',
                marginLeft: window.top !== window.self && '0px',
                width: window.top !== window.self && '276px',
                height: window.top !== window.self && '178px'
              }}
            >
              <div className='login-ad'>
                <img
                  style={{ maxWidth: '100%' }}
                  src={require('../../../public/login-ad.png')}
                  alt=''
                />
              </div>
              <div className='login-area'>
                <header
                  style={{ display: window.top !== window.self && 'none' }}
                  className='login-title'
                >
                  {this.state.loginType == 0?'企业登录': '自然人登陆'}
                </header>
                <Form
                  onSubmit={this.handleSubmit}
                  className='login-form'
                  style={{ width: window.top !== window.self && '276px' }}
                >
                  <FormItem>
                    {getFieldDecorator('username', {
                      rules: [
                        {
                          required: type === 'account',
                          // pattern: /^1[0-9]{10}$/,
                          message: '请输入正确的账户名！'
                        }
                      ]
                    })(
                      <Input
                        size='large'
                        prefix={<Icon type='user' className='prefixIcon' />}
                        placeholder='账号'
                      />
                    )}
                  </FormItem>
                  <FormItem
                    style={{ marginBottom: '8px' }}
                    className='password'
                  >
                    {getFieldDecorator('password', {
                      rules: [
                        {
                          required: type === 'account',
                          message: '请输入密码！'
                        }
                      ]
                    })(
                      <Input
                        size='large'
                        prefix={<Icon type='lock' className='prefixIcon' />}
                        type='password'
                        placeholder='密码'
                      />
                    )}
                    <span
                      style={{
                        float: 'right',
                        color: '#666',
                        cursor: 'pointer'
                      }}
                      onClick={() => this.props.history.push('ForgetPassword')}
                    >
                      忘记密码？
                    </span>
                    {/* <span
                    style={{
                      float: 'left',
                      color: '#0F71FF',
                      cursor: 'pointer'
                    }}
                    onClick={() => this.props.history.push('Enroll')}
                  >
                    立即注册
                  </span> */}
                  </FormItem>
                  <FormItem className='additional'>
                    {getFieldDecorator('remember', {
                      valuePropName: 'checked',
                      initialValue: true
                    })(
                      <Checkbox
                        style={{ display: 'none' }}
                        className='autoLogin'
                      >
                        自动登录
                      </Checkbox>
                    )}
                    {/* <a className="forgot" href="">
                  忘记密码？
                </a> */}
                    <Button
                      size='large'
                      className='submit'
                      type='primary'
                      htmlType='submit'
                    >
                      登录
                    </Button>
                    <a onClick={() => {
                      this.setState({
                        initialState: true
                      });
                    }} style={{marginTop: '10px',display: 'block'}} href="javascript: void(0)">选择登录入口>></a>
                  </FormItem>
                </Form>
              </div>
            </div>
            )
          ) : (
            <div className='upgrade-box'>
              <div style={{ textAlign: 'center' }}>
                <img
                  style={{ width: '400px' }}
                  src={updateTipImgUrl}
                  alt='百保盾'
                />
                <h3 style={{ color: '#FF9900' }}>百保盾系统正在维护升级...</h3>
                <p>
                  为加强百保盾系统安全、提供更好的用户体验，当前系统正在升级当中。
                </p>
                <p>
                  系统升级时间：
                  <span style={{ color: '#008000' }}>预计半小时</span>
                </p>
                <p>给您带来的不便，敬请谅解！</p>
                {/* <p style={{ color: '#666', marginTop: '40px' }}>
                  百保盾官网：
                  <a href='http://www.baibaodun.cn/'>www.baibaodun.cn</a>
                </p> */}
              </div>
            </div>
          )}
        </div>
        {
          prefix!='yaba' && <div className='copyright'>
          <ul>
            <li>
              <a
                href='http://www.baibaodun.cn/'
                target='_blank'
                rel='noopener noreferrer'
              >
                关于百保盾
              </a>
              <a
                href='http://www.baibaodun.cn/agreement'
                target='_blank'
                rel='noopener noreferrer'
              >
                服务协议
              </a>
              <a
                href='http://www.baibaodun.cn/policy'
                target='_blank'
                rel='noopener noreferrer'
              >
                隐私政策
              </a>
              <a
                href='http://www.baibaodun.cn/contact'
                target='_blank'
                rel='noopener noreferrer'
              >
                联系我们
              </a>
              {/* <a
                href="http://47.93.117.58:8012/view?token=aHR0cDovL2JjeGludmVkaW8ub3NzLWNuLXNoYW5naGFpLmFsaXl1bmNzLmNvbS9wZWl4dW4vc2Fhcy9iYmRzYWFzX2hlbHAucGRm"
                target="_blank"
              >
                操作手册
              </a> */}
              {/* <Link to="/">版本套餐</Link>
              <Link to="/">在线客服</Link> */}
            </li>
          </ul>
          <p>
          {/* 平台运营与技术支持 © 百川信（北京）信息服务有限公司&nbsp;&nbsp;&nbsp;备案证书号： */}
          此平台由百川信（北京）信息服务有限公司开发与运营，产生的问题最终解释权归百川信所有&nbsp;&nbsp;&nbsp;备案证书号：
            {/* <span>闽ICP备14018517号-3</span> */}
            <a href="http://beian.miit.gov.cn" target="_blank" style={{color: '#fff'}}>闽ICP备14018517号-3</a>
          </p>
        </div>
        }
        
        <IEBrowserPrompt
          isIEBrowser={this.state.isIEBrowser}
          cancel={mode => this.cancel(mode)}
        />
        {/* {this.props.netErr && <div className='upgrade' />} */}
        {/* <Modal
          visible={this.props.netErr}
          footer={null}
          closable={false}
          width={700}
          centered
          wrapClassName='update-mask'
          zIndex={1002}
        >
          <div style={{ textAlign: 'center' }}>
            <img style={{ width: '500px' }} src={updateTipImgUrl} alt='' />
            <h3 style={{ color: '#FF9900' }}>百保盾系统正在维护升级...</h3>
            <p>
              为加强百保盾系统安全、提供更好的用户体验，当前系统正在升级当中。
            </p>
            <p>
              系统升级时间：<span style={{ color: '#008000' }}>预计半小时</span>
            </p>
            <p>给您带来的不便，敬请谅解！</p>
            <p style={{ color: '#666', marginTop: '40px' }}>
              百保盾官网：
              <a href='http://www.baibaodun.cn/'>www.baibaodun.cn</a>
            </p>
          </div>
        </Modal> */}
      </div>
    );
  }
}
