import React, { Component } from 'react';
import { browserHistory } from 'amos-react-router';
import { Store, LocationParam } from 'amos-tool';
import SysConsts from 'amos-processor/lib/config/consts';
import { AmosAlert } from 'amos-framework';

import { login } from '../../services/securityService';

const lsTool = Store.lsTool;

/**
 * 自动登录，无界面
 *  BaseAutoLogin： props => `tip: string` `hideTip: boolean`
 * @class AutoLogin
 * @extends {Component}
 */
class AutoLogin extends Component {

  componentWillMount() {
    let code = LocationParam.getLocationParamByName('code');
    let userId = LocationParam.getLocationParamByName('userId');
    if (code && userId) {
      login(code, userId).then(
        data => {

          const { companys = [], companyDepartments = {}, orgRoles = {} } = data.user;
          lsTool.write(SysConsts.token, data.accessToken);
          lsTool.write(SysConsts.userId, data.userId);
          lsTool.write(SysConsts.company, JSON.stringify(data.user.companys));
          lsTool.write(SysConsts.userName, data.user.userName);
          lsTool.write(SysConsts.nickName, data.user.realName);
          if (companys.length > 0) {
            browserHistory.push('/region');
            return;
          }
        },
        err => {
          AmosAlert.error('警告', err || '系统初始化失败，请重新尝试！');
        }
      );
    } else {
      AmosAlert.error('警告', '无法打开该系统，请重新尝试!');
    }
  }

  render() {
    return null;
  }
}

export default AutoLogin;
