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,
  message
} from "antd";
import CryptoJS from "crypto-js";
import IEBrowserPrompt from "../../components/Pro/IEBrowserPrompt/IEBrowserPrompt";
import Utils from "../../common/bcx_utils";

import {
  accesstoken,
  systemComVaseInfoGet,
  systemOauthGetUserMenus,
  getPublicKey
} from "../../services/api";
import Logo from "../../components/Logo";

import "./Login.less";
import { stat } from "fs";

import updateTipImgUrl from "../../../public/update.gif";
const store = require("store");

const FormItem = Form.Item;

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

  /**
   * 生命周期
   */
  componentDidMount() {
    // 隐藏底部logo
    document.querySelector("#footer").style.display = "none";
    getPublicKey({}).then(res => {
      this.setState({
        publickKey: res.data
      });
    });
    this.isShowBrowserTips();
  }

  /***
   * 事件方法
   */
  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 = () => {
    if (!this.state.username) {
      return message.error("请输入用户名");
    }
    if (!this.state.password) {
      return message.error("请输入密码");
    }
    const { type } = this.state;
    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(this.state.password, key, iv);
    const cipherText = encrypted.ciphertext.toString();

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

  //获取用户登陆菜单-是否有菜单,没有菜单弹框提示且不能登录
  systemOauthGetUserMenus = username => {
    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();
          // //获取并登录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;

    return (
      <div className="dahuo_login_container" style={{minHeight: "calc(100vh)"}}>
        <div
          className="login-main-con"
          style={{
            
            paddingTop: window.top !== window.self && "0px",
            background: `url("${require("../../assets/images/login/login_bg.png")}")`,
            position: "relative"
          }}
        >
          {/* 是否在升级 */}
          {!this.props.netErr ? (
            <section class="form_container">
              <header>GIS现场防控指挥系统</header>

              <div class="form_infos">
                <div class="form_item">
                  <Input
                    type="text"
                    placeholder="用户名"
                    onChange={e => {
                      this.setState({
                        username: e.target.value.trim()
                      });
                    }}
                  />
                  <img
                    class="form_icon"
                    src={require("../../assets/images/login/user_icon.png")}
                    alt=""
                  />
                </div>
                <div class="form_item">
                  <Input
                    type="password"
                    placeholder="密码"
                    onChange={e => {
                      this.setState({
                        password: e.target.value.trim()
                      });
                    }}
                  />
                  <img
                    class="form_icon"
                    src={require("../../assets/images/login/pwd_icon.png")}
                    alt=""
                  />
                </div>
                <div class="form_item">
                  <button class="btn" onClick={() => this.handleSubmit()}>
                    登录
                  </button>
                </div>
              </div>
              {/* <Form
                onSubmit={this.handleSubmit}
                className="form_infos"
                style={{ width: window.top !== window.self && "276px" }}
              >
                <FormItem>
                  {getFieldDecorator("username", {
                    rules: [
                      {
                        required: type === "account",
                        message: "请输入正确的账户名！"
                      }
                    ]
                  })(
                    <Input
                      size="large"
                      prefix={<Icon type="user" className="prefixIcon" />}
                      placeholder="账号"
                    />
                  )}
                </FormItem>
                <FormItem style={{ marginBottom: "8px" }}>
                  {getFieldDecorator("password", {
                    rules: [
                      {
                        required: type === "account",
                        message: "请输入密码！"
                      }
                    ]
                  })(
                    <Input
                      size="large"
                      prefix={<Icon type="lock" className="prefixIcon" />}
                      type="password"
                      placeholder="密码"
                    />
                  )}
                </FormItem>
                <FormItem>
                  <Button
                    size="large"
                    className="submit"
                    type="primary"
                    htmlType="submit"
                  >
                    登录
                  </Button>
                </FormItem>
              </Form> */}
              <i class="horn horn_left_top"></i>
              <i class="horn horn_left_bottom"></i>
              <i class="horn horn_right_top"></i>
              <i class="horn horn_right_bottom"></i>
            </section>
          ) : (
            <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>
        <IEBrowserPrompt
          isIEBrowser={this.state.isIEBrowser}
          cancel={mode => this.cancel(mode)}
        />
      </div>
    );
  }
}
