import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { browserHistory } from 'amos-react-router';
import { Select, Form, Button } from 'amos-framework';
import * as endConf from 'amos-processor/lib/config/endconf';
import { setRegion } from './../../utils/cacheUtils';
import { regionSelectAction } from './../../services/navApi';
import { getCurrentUser } from './../../services/securityService';
import { CONSTS } from '../../consts/storageConsts';
import { Store, utils } from 'amos-tool';
import SysConsts from 'amos-processor/lib/config/consts';

const lsTool = Store.lsTool;
const AmosConfig = endConf.AmosConfig;
const isAutoOpen = AmosConfig.sysConf.isAutoOpenBussiness;

const FormItem = Form.Item;
const Option = Select.Option;
/**
 * 厂区选择
 *
 * @class RegionSelect
 * @extends {Component}
 */
class RegionSelect extends Component {

  constructor(props) {
    super(props);
    this.state = {
      userInfo: {},
      reginParams: {}
    };
  }

  componentDidMount() {
    this.getCurrentUser();
  }

  onClick = () => {
    const { reginParams } = this.state;
    lsTool.remove('selectedRole');
    regionSelectAction(reginParams).then(
      data => {
        const { state } = this.props.location;
        const { sequenceNbr } = reginParams.role || {};
        lsTool.write('selectedRole', sequenceNbr);
        if (state){
          browserHistory.push('/main');
          lsTool.write(CONSTS.region_change, { refresh: { refresh: true } });
        } else {
          //1.打开3d屏
          browserHistory.push('/main');
        }
      }
    );
  }

  // new
  onSelectChange = (key, value) => {
    const { companys = [], companyDepartments = {}, orgRoles = {} } = this.state.userInfo;
    const { reginParams } = this.state;
    let { departments = [], roles = [] } = this.state;
    if (key === 'company') {
      reginParams.company = companys.find(item => item.sequenceNbr === value);
      departments = companyDepartments[value];
      roles = orgRoles[value];
    }
    if (key === 'department') {
      reginParams.department = departments.find(item => item.sequenceNbr === value);
      roles = orgRoles[value];
    }
    if (key === 'role') {
      reginParams.role = roles.find(item => item.sequenceNbr === value);
    }
    this.setState({ reginParams, departments, roles });
  }

  getCurrentUser =()=>{
    getCurrentUser().then(data => {
      const { reginParams } = this.state;
      const { companys = [], companyDepartments = {}, orgRoles = {} } = data;

      lsTool.write(SysConsts.userId, data.userId);
      lsTool.write(SysConsts.company, JSON.stringify(companys));
      lsTool.write(SysConsts.userName, data.userName);
      lsTool.write(SysConsts.nickName, data.realName);

      if (companys.length === 1) {
        let company = companys[0];
        let departments = companyDepartments[company.sequenceNbr] || [];
        if (departments.length === 1 && ((orgRoles[company.sequenceNbr] || orgRoles[departments[0].sequenceNbr]) || []).length === 1 ) {
          reginParams.company = company;
          reginParams.department = departments[0];
          reginParams.role = orgRoles[company.sequenceNbr] ? orgRoles[company.sequenceNbr][0] : orgRoles[departments[0].sequenceNbr] ? orgRoles[departments[0].sequenceNbr][0] : {};
          this.setState({ reginParams },()=>this.onClick());
        } else if (departments.length === 0 && (orgRoles[company.sequenceNbr] || []).length === 1){
          reginParams.company = company;
          reginParams.department = {};
          reginParams.role = orgRoles[company.sequenceNbr][0];
          this.setState({ reginParams },()=>this.onClick());
        } else {
          this.setState({ userInfo: data });
        }
      } else {
        this.setState({ userInfo: data });
      }
    });
  }

  renderItem = (item) => {
    const { userId, companys = [] } = item;
    let { departments = [], roles = [] } = this.state;
    let newDepartments =  departments.filter(d => d != null && void 0 !== d);
    const formItemLayout = {
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 },
        className: 'colspan'
      }
    };
    return (
      <div key={userId} className="region-item">
        <Form className="region-form">
          <FormItem {...formItemLayout}>
            <Select
              className="form-item"
              data={companys}
              renderOption={item => <Option value={item.sequenceNbr}>{item.companyName}</Option>}
              defaultOption={<Option>请选择公司</Option>}
              // defaultValue={companys.length === 1 ? companys[0] : ''}
              onChange={(value, item) => this.onSelectChange('company', value)}
            />
          </FormItem>
          <FormItem  {...formItemLayout}>
            <Select
              className="form-item"
              data={newDepartments}
              renderOption={item => <Option value={item.sequenceNbr}>{item.departmentName}</Option>}
              defaultOption={<Option>请选择部门</Option>}
              // defaultValue={newDepartments.length === 1 ? newDepartments[0] : ''}
              onChange={(value, item) => this.onSelectChange('department', value)}
            />
          </FormItem>
          <FormItem {...formItemLayout}>
            <Select
              className="form-item"
              data={roles}
              renderOption={item => <Option value={item.sequenceNbr}>{item.roleName}</Option>}
              defaultOption={<Option>请选择角色</Option>}
              // defaultValue={roles.length === 1 ? roles[0] : ''}
              onChange={(value, item) => this.onSelectChange('role', value)}
            />
          </FormItem>
          <FormItem {...formItemLayout}>
            <img src="" alt='' />
          </FormItem>
          <FormItem>
            <Button className="regoin-button" onClick={this.onClick}>确定</Button>
          </FormItem>
        </Form>
      </div>
    );
  }

  render() {
    const { userInfo } = this.state;
    return  Object.keys(userInfo).length > 0 ? (
      <div className="region-select">
        {
          this.renderItem(userInfo)
        }
      </div>
    ) : null;
  }
}

RegionSelect.propTypes = {
  location: PropTypes.object
};

export default RegionSelect;
