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 { tellRegionSelectAction } from './../../services/navApi';
import { getCurrentUser,getDictionaryList } from './../../services/securityService';
import { fetchRegionSelectAction } from './../../services/checkInfoService';
import { tirggerTransTopic } from './../3dview/dataProcessor';
import { regionSelectAction } from './../../services/bizService';
import { CONSTS } from '../../consts/storageConsts';
import imgStatic from './../../consts/imgStatic';
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: {},
      dictionaryList:[]
    };
  }

  componentDidMount() {
    console.log('.......');
    this.getCurrentUser();
    this.getDicCode('BANK_ORG');
  }

   /**
   * 查询组织机构字典
   */
  getDicCode = (dicCode) => {
    getDictionaryList(dicCode).then(data =>{
       this.setState({
        dictionaryList:data
       })
    })
  }

  onClick = () => {
    const { reginParams,dictionaryList } = this.state;
    //获取当前登陆部门
    lsTool.write('dictionaryList', JSON.stringify(dictionaryList));
    lsTool.write("department", JSON.stringify(reginParams.department))
    lsTool.remove('selectedRole');
    regionSelectAction(reginParams).then(
      data => {
        const { state } = this.props.location;
        const { sequenceNbr } = reginParams.role || {};
        const { companyName } = reginParams.company || {};
        const companyOrgCode  = reginParams.company.orgCode || {};
        const companySequenceNbr = reginParams.sequenceNbr || {};
        lsTool.write('selectedRole', sequenceNbr);
        lsTool.write('selectedCompany', companyName);
        lsTool.write('selectedCompanyOrg', companyOrgCode);
        lsTool.write('companySequenceNbr', companySequenceNbr);
        if (state) {
          browserHistory.push('/main/3dview');
          // browserHistory.push('/biz/preControl');
          tirggerTransTopic(CONSTS.region_change, { refresh: { refresh: true } });
        } else {
          //1.打开3d屏
          browserHistory.push('/main/3dview');
          //2.通过配置，确定是否打开业务屏
          // if (isAutoOpen){
          //   // window.open('/biz/assessment');
          //   // window.open('/biz/preControl');
          // }
        }
      }
    );
  }

  uniq = (array) => {
    if (array && array.length > 0) {
      array.sort();
      var temp = [array[0]];
      for (var i = 1; i < array.length; i++) {
        if (array[i].sequenceNbr !== temp[temp.length - 1].sequenceNbr) {
          temp.push(array[i]);
        }
      }
      return temp;

    } else {

      return [];
    }

  }


  // 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 &&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) {
          departments = [departments[0]];
        }
        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={this.uniq(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={this.uniq(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;
