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

import './BBDLogin.less';
import { stat } from 'fs';
// import api from '../../../mock/api';

const store = require('store');

const FormItem = Form.Item;

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

  /**
   * 生命周期
   */
  componentDidMount() {
    // document.querySelector('.kf5-support-chat').style.display = 'none';
    getPublicKey({}).then(res => {
      this.setState({
        publickKey: res.data
      });
    });
    this.isShowBrowserTips();
  }

  componentWillUnmount() {
    // document.querySelector('.kf5-support-chat').style.display = 'block';
  }

  /***
   * 事件方法
   */
  encrypt(msg, key, iv) {
    return CryptoJS.AES.encrypt(msg, key, {
      iv,
      padding: CryptoJS.pad.Pkcs7,
      mode: CryptoJS.mode.CBC
    });
  }

  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();
            }
          },
          err1 => {
            console.log(err1, 'accesstoken-err');
          }
        );
        this.props.dispatch({
          type: `login/${type}Submit`,
          payload: values
        });
      }
    });
  };

  //获取用户登陆菜单-是否有菜单,没有菜单弹框提示且不能登录
  systemOauthGetUserMenus = () => {
    systemOauthGetUserMenus({}).then(
      response => {
        // 储存时间用于控制时间控件
        window.sessionStorage.setItem('requestDate', moment(response.date).valueOf());
        if (response.data && JSON.stringify(response.data) === '[]') {
          Modal.info({
            title: '您的账号未授权登录企业端，请联系企业管理员！',
            okText: '确定',
            onOk() {}
          });
        } else {
          this.systemComVaseInfoGet();

          //是否有企业菜单,无企业菜单，不能点击公司名
          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;

    return (
      <div className='BBDLogin'>
        {/* <div
          className='login-main-con'
          style={{
            minHeight: 'calc(100vh - 165px)',
            paddingTop: window.top !== window.self && '0px',
            position: 'relative'
          }}
        >
          <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-area'>
          {/* <header
                style={{ display: window.top !== window.self && 'none' }}
                className='login-title'
              >
                企业登录
              </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: '13px' }} 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 className='submit' type='primary' htmlType='submit'>
                登录
              </Button>
            </FormItem>
          </Form>
        </div>
        {/* </div>
        </div> */}
      </div>
    );
  }
}
