import React from 'react';
import {
  inject,
  observer
} from 'mobx-react';
import {
  WeaTop,
  WeaTab,
  WeaRightMenu,
  WeaErrorPage,
  WeaSearchGroup,
  WeaFormItem,
  WeaSelect,
  WeaAlertPage,
  WeaOrgTree,
  WeaLeftRightLayout,
  WeaDialog,
  WeaNewScroll,
  WeaBrowser,
  WeaDropdown,
  WeaLocaleProvider
} from 'ecCom';
import {
  Row,
  Form,
  Col,
  Button,
  Spin
} from 'antd';
import {
  openBatchEdit
} from '../../public/pulic-func'
import * as mobx from 'mobx';
import isEmpty from 'lodash/isEmpty';
import OrganizationTree from './OrganizationTree'
import OrganizationTabInfo from './OrganizationTabInfo'
import OrganizationInfo from './OrganizationInfo'
import OrganizationList from './OrganizationList'
import ResourceAddToVirtual from './ResourceAddToVirtual';
import ResourceSetManagerVirtual from './ResourceSetManagerVirtual';
import NewAndEditDialog from './NewAndEditDialog';
import ImportResource from '../importresource/Import';
const toJS = mobx.toJS;
import {
  WeaTableNew,
  WeaSwitch
} from 'comsMobx';
const WeaTable = WeaTableNew.WeaTable;
const {
  ButtonSelect
} = WeaDropdown;
import {
  routerShape
} from 'react-router';
import {
  WeaLogView
} from 'comsMobx';
const {
  LogStore
} = WeaLogView;
import {
  i18n
} from '../../public/i18n';
const getLabel = WeaLocaleProvider.getLabel;

@inject('hrmOrganization')
@inject('hrmImportResource')
@observer
class Organization extends React.Component {
  static contextTypes = {
    router: routerShape
  };

  constructor(props) {
    super(props);

    this.browserRef = null;
    this.setRef = (ref) =>{
      this.browserRef = ref;
    }
  }

  componentDidMount() {
    this.init();
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.location.key !== nextProps.location.key) {
      const {id,type} = nextProps.location.query;
      this.init(id,type);
    }
  }

  init(id,type) {
    const {
      hrmOrganization,
      hrmImportResource
    } = this.props;
    let showTree = this.props.location.query.showTree || ''
    hrmOrganization.showTree = showTree != 'false';
    hrmOrganization.type = type || this.props.location.query.type || 'company';
    hrmOrganization.typeValue = id || this.props.location.query.id || '1';
    hrmOrganization.isView = this.props.location.query.isView || '';
    hrmOrganization.showTree && hrmOrganization.selectVirtual("1");
    if (window.location.href.indexOf("/spa/hrm/engine.html") > -1) {
      hrmOrganization.isSingle = true;
      if (hrmOrganization.type == 'subcompany') {
        document.title =(window.e9_locale.userLanguage == '8') ? 'Division Information' :i18n.label.subCompanyInfo(); 
      } else if (hrmOrganization.type == 'department') {
        document.title = (window.e9_locale.userLanguage == '8') ? 'Department information' :i18n.label.departmentInfo();
      } else {
        document.title = i18n.label.companyInfo();
      }
    }
    if(hrmOrganization.typeValue.indexOf("-")!=-1){
      hrmOrganization.changeVirtual();
    }
    hrmOrganization.updateTabkey('1');
    hrmOrganization.getHasRight();
    hrmImportResource.init();
  }

  getRightMenu() {
    const {
      hrmOrganization
    } = this.props;
    const {
      rightMenu
    } = hrmOrganization;

    let menus = [];
    toJS(rightMenu).map((item, index) => {
      if (item.isTop && item.isTop == '1' && item.isBatch && item.isBatch == '1') {

      } else {
        let obj = {
          key: item.menuFun,
          icon: <i className={`${item.menuIcon}`} />,
          content: item.menuName,
          onClick: key =>{
            const menuFun = item.menuFun;
            this[menuFun] && this[menuFun](item.params);
          }
        }
        if (item.menuFun == 'addResourceToVirtual') {
          let btnBrower = <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@pn46zq@${index}`}
            type={17}
            title='人员'
            customized={true}
            hasAdvanceSerach={true}
            isSingle={false}
            onChange={(ids, names, datas) => hrmOrganization.addResourceToVirtual(ids)}
          >
          <div>{item.menuName}</div>
          </WeaBrowser>
          menus.push({ //添加人员右键菜单
            key: item.menuFun,
            content: btnBrower,
            icon: <i className={'icon-coms-New-Flow'}/>,
          })
        } else {
          if (!this[item.menuFun]) {
            obj.disabled = true;
          }
          menus.push(obj);
        }
      }
    })
    return menus;
  }

  showLog(params){
    const {
      hrmOrganization
    } = this.props;
    const {
      isVirtual,
      typeSearchList,
    } = hrmOrganization;
    if (typeSearchList == 'resource') {
      params.logType = '3';
      params.logSmallType = i18n.smallType.HRM_ENGINE_ORGANIZATION_RESOURCE;
      if(isVirtual){
        params.logType = '4';
        params.logSmallType = i18n.smallType.HRM_ENGINE_ORGANIZATION_VIRTUAL_RESOURCE;
      }
    }  
    window.setLogViewProps(params);
  }

  batchEdit = params => {
    openBatchEdit(params.type);
  }

  export = () => {
    const {
      hrmOrganization
    } = this.props;
    (hrmOrganization.typeSearchList == 'subcompany' || hrmOrganization.typeSearchList == 'department') && hrmOrganization.table && hrmOrganization.table.exportAll('', hrmOrganization.typeSearchList == 'department' ? getLabel('16289','部门信息') : getLabel('32816','分部信息'));
  }

  definedColumn() {
    const {
      hrmOrganization
    } = this.props;
    const {
      table
    } = hrmOrganization;
    table.setColSetVisible(true);
    table.tableColSet(true);
  }

  onAddToGroupChange(ids, names) {
    const {
      hrmOrganization
    } = this.props;
    hrmOrganization.saveAddToGroup({
      groupids: ids
    });
  }

  getTopButtons() {
    const {
      hrmOrganization
    } = this.props;
    const {
      rightMenu,
      showCanceled,
      table,
      batchOperateType
    } = hrmOrganization;
    const selectedRowKeys = table.selectedRowKeys;
    const btnShowAll = <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@rqv1ea`} size="small" style={{ height: '28px' }} onClick={() => hrmOrganization.changeShowAll()} title={showCanceled ? i18n.label.showCanceledOrg() : i18n.label.hideCanceledOrg()}>
      <span>{showCanceled ?
        <i className='icon-coms-Department-number' style={{ color: '#2DB7F5' }} /> : <i className='icon-coms-Department-number-hide' style={{ color: '#8A8A8A' }} />}</span>
    </Button>;

    let btns = [];
    let btnSelect = []
    toJS(rightMenu).map((item, index) => {
      if (item.isTop && item.isTop == '1') {
        if (item.isBatch && item.isBatch == '1') {
          btnSelect.push({
              key: item.menuFun,
              show: item.menuName,
              selected: btnSelect.length == 0
            });
          // if (item.menuFun == 'addResourceToGroup') {
          //   const btnAddToGroup = <WeaBrowser
          //     title={i18n.label.group()}
          //     icon={'icon-coms-hrm'}
          //     iconBgcolor={'#217346'}
          //     type={'hrmgroup'}
          //     customized
          //     isSingle={false}
          //     inputStyle={{ width: 200 }}
          //     onChange={(ids, names, datas) => this.onAddToGroupChange(ids, names)}
          //   >
          //     {item.menuName}
          //   </WeaBrowser>;
          //   btnSelect.push({
          //     key: item.menuFun,
          //     show: btnAddToGroup,
          //     selected: btnSelect.length == 0,
          //     text: item.menuName
          //   });
          // } else {
          //   btnSelect.push({
          //     key: item.menuFun,
          //     show: item.menuName,
          //     selected: btnSelect.length == 0
          //   });
          // }
        } else if (item.menuFun == 'addResourceToVirtual') {
          let btnBrower = <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@pamj8l@${index}`}
            type={17}
            title={i18n.label.resource()}
            customized={true}
            hasAdvanceSerach={true}
            isSingle={false}
            onChange={(ids, names, datas) => hrmOrganization.addResourceToVirtual(ids)}
          >
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@3h4gds@${index}`} type='primary'>{item.menuName}</Button>
          </WeaBrowser>
          btns.push(btnBrower);
        } else {
          btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@0jjhw9@${index}`} type='primary' onClick={() => this[item.menuFun] && this[item.menuFun]()}>{item.menuName}</Button>);
        }
      }
    })

    if (!isEmpty(btnSelect) && batchOperateType) {
      btns.push(<ButtonSelect ecId={`${this && this.props && this.props.ecId || ''}_ButtonSelect@p5894q`} datas={toJS(btnSelect)}
        dropBtnProps={{ title: i18n.label.batchOperateTitle() }}
        selectedKey={batchOperateType}
        btnProps={{ disabled: (batchOperateType == 'batchOrder' || batchOperateType == 'batchCode') ? false : selectedRowKeys.length <= 0 }}
        btnOnClick={key => { 
          if (key == 'addResourceToGroup') {
            this.browserRef && this.browserRef.openModal();
          }else{
            hrmOrganization[key] && hrmOrganization[key]() 
          }
        }}
        menuOnClick={key => hrmOrganization.updateBatchOperateType(key)} />);
    }

    btns.push(btnShowAll);
    return btns;
  }



  getBreadcrumb() {
    const {
      hrmOrganization
    } = this.props;
    const {
      title,
      parentId,
      parentTitle
    } = hrmOrganization;
    const arr = [];
    if (parentTitle && parentTitle != "") {
      arr.push({
        name: parentTitle,
        onClick: () => {
          hrmOrganization.initParam();
          let tmp = parentId.split("_");
          if (tmp.length > 1) {
            hrmOrganization.type = tmp[0];
            hrmOrganization.typeValue = tmp[1];
          } else {
            hrmOrganization.type = "company";
            hrmOrganization.typeValue = parentId;
          }
          hrmOrganization.initData();
        },
      });
    }
    arr.push({
      name: title,
      onClick: () => {},
    });
    return arr;
  }

  doEdit() {
    const {
      hrmOrganization
    } = this.props;
    const {
      type,
      typeValue
    } = hrmOrganization;
    hrmOrganization.dialogIsAdd = false;
    if (type == "company") {
      hrmOrganization.dialogFunc = 'editCompany';
      hrmOrganization.getCompanyForm({
        id: typeValue
      });
    } else if (type == "subcompany") {
      hrmOrganization.dialogFunc = 'editSubCompany';
      hrmOrganization.getSubCompanyForm({
        id: typeValue
      });
    } else if (type == "department") {
      hrmOrganization.dialogFunc = 'editDepartment';
      hrmOrganization.getDepartmentForm({
        id: typeValue
      });
    }
  }

  doDelete() {
    const {
      hrmOrganization
    } = this.props;
    hrmOrganization.doDelete();
  }

  doCancel() {
    const {
      hrmOrganization
    } = this.props;
    const {
      typeValue
    } = hrmOrganization;
    hrmOrganization.doCancel();
  }

  doISCanceled() {
    const {
      hrmOrganization
    } = this.props;
    hrmOrganization.doISCanceled();
  }

  addCompany() {
    const {
      hrmOrganization
    } = this.props;
    hrmOrganization.dialogIsAdd = true;
    hrmOrganization.dialogFunc = 'addCompany';
    hrmOrganization.getCompanyForm();
  }

  addSubCompany() {
    const {
      hrmOrganization
    } = this.props;
    hrmOrganization.dialogIsAdd = true;
    hrmOrganization.dialogFunc = 'addSubCompany';
    hrmOrganization.getSubCompanyForm({
      addType: 'normal'
    });
  }

  addSubCompanySibling() {
    const {
      hrmOrganization
    } = this.props;
    hrmOrganization.dialogIsAdd = true;
    hrmOrganization.dialogFunc = 'addSubCompany';
    hrmOrganization.getSubCompanyForm({
      addType: 'sibling'
    });
  }

  addSubCompanyChild() {
    const {
      hrmOrganization
    } = this.props;
    hrmOrganization.dialogIsAdd = true;
    hrmOrganization.dialogFunc = 'addSubCompany';
    hrmOrganization.getSubCompanyForm({
      addType: 'child'
    });
  }

  addDepartment() {
    const {
      hrmOrganization
    } = this.props;
    hrmOrganization.dialogIsAdd = true;
    hrmOrganization.dialogFunc = 'addDepartment';
    hrmOrganization.getDepartmentForm({
      addType: 'normal'
    });
  }

  addDepartmentSibling() {
    const {
      hrmOrganization
    } = this.props;
    hrmOrganization.dialogIsAdd = true;
    hrmOrganization.dialogFunc = 'addDepartment';
    hrmOrganization.getDepartmentForm({
      addType: 'sibling'
    });
  }

  addDepartmentChild() {
    const {
      hrmOrganization
    } = this.props;
    hrmOrganization.dialogIsAdd = true;
    hrmOrganization.dialogFunc = 'addDepartment';
    hrmOrganization.getDepartmentForm({
      addType: 'child'
    });
  }

  addResource() {
    const {
      hrmOrganization
    } = this.props;
    const {
      typeValue,
      departmentInfo:{id,name},
      initData
    } = hrmOrganization;

    // ecCom.WeaTools.createDialog({
    //   title: '新建人员',
    //   url:`/spa/hrm/index_mobx.html#/main/hrm/simple?id=${id}&name=${name}`,
    //   moduleName:'hrm',
    //   style:{width:800,height:800},
    //   callback: (datas)=>{ // 数据通信
    //     initData()
    //   },
    //   onCancel: ()=>{ // 关闭通信
    //   },
    //   maxHeight:800
    // }, undefined, (dialog) => {
    //   // 由于组件异步化可能导致第一次没有加载到组件，所以需要在回调中调用
    //   dialog.show();
    // });

    window.open(`/spa/hrm/index_mobx.html#/main/hrm/add?departmentid=${typeValue}`);
  }

  departmentRoles() {
    const {
      hrmOrganization
    } = this.props;
    const {
      typeValue
    } = hrmOrganization;
    window.open(`/hrm/HrmDialogTab.jsp?_fromURL=HrmDepartmentRoles&id=${typeValue}`);
  }

  importResource() {
    const {
      hrmImportResource
    } = this.props;
    hrmImportResource.visible = true;
    hrmImportResource.title = i18n.button.importResource();
    hrmImportResource.importType = 'resource';
    hrmImportResource.getImportForm();
  }

  importOrg() {
    const {
      hrmImportResource
    } = this.props;
    hrmImportResource.visible = true;
    hrmImportResource.title = i18n.button.importOrg();
    hrmImportResource.importType = 'company';
    hrmImportResource.getImportForm();
  }


  render() {
    const {
      hrmOrganization
    } = this.props;
    const {
      verified,
      hasRight
    } = hrmOrganization;
    const {
      loading,
      tabKey,
      showTree,
      date,
      logVisible,
      logStore
    } = hrmOrganization;
    if (verified && hasRight) {
      return (
        <div className='wea-hrm-organization'>
          <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@tdpzdm`}
            title={i18n.label.group()}
            icon={'icon-coms-hrm'}
            iconBgcolor={'#217346'}
            type={'hrmgroup'}
            customized
            ref={this.setRef}
            isSingle={false}
            inputStyle={{ width: 200 }}
            style={{display:"none"}}
            onChange={(ids, names, datas) => this.onAddToGroupChange(ids, names)}
          />
          <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@ggl50p`} spinning={loading}>
            <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@paa2ec`} datas={this.getRightMenu()}>
              <NewAndEditDialog ecId={`${this && this.props && this.props.ecId || ''}_NewAndEditDialog@6uhe30`} {...this.props} />
              <ResourceAddToVirtual ecId={`${this && this.props && this.props.ecId || ''}_ResourceAddToVirtual@lmu7gz`} {...this.props} />
              <ResourceSetManagerVirtual ecId={`${this && this.props && this.props.ecId || ''}_ResourceSetManagerVirtual@5a8wll`} {...this.props} />
              <ImportResource ecId={`${this && this.props && this.props.ecId || ''}_ImportResource@utebio`} {...this.props} />
              <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@iey5qx`}
                breadcrumb={this.getBreadcrumb()}
                loading={loading}
                icon={<i className='icon-coms-hrm' />}
                iconBgcolor='#217346'
                buttons={this.getTopButtons()}
                buttonSpace={10}
                showDropIcon={true}
                dropMenuDatas={this.getRightMenu()}
              >
                {showTree ? <WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@te4be2`} isNew={true} leftCom={<OrganizationTree ecId={`${this && this.props && this.props.ecId || ''}_OrganizationTree@ck9ri7`} {...this.props} />}>
                  {<OrganizationTabInfo ecId={`${this && this.props && this.props.ecId || ''}_OrganizationTabInfo@drz0yk`}  {...this.props} />}
                  {tabKey == '1' ? <OrganizationInfo ecId={`${this && this.props && this.props.ecId || ''}_OrganizationInfo@9b33wf`} {...this.props} /> : <OrganizationList ecId={`${this && this.props && this.props.ecId || ''}_OrganizationList@4dgzmm`} {...this.props} />}
                </WeaLeftRightLayout> : <div>
                    <OrganizationTabInfo ecId={`${this && this.props && this.props.ecId || ''}_OrganizationTabInfo@21erdc`}  {...this.props} />
                    {tabKey == '1' ? <OrganizationInfo ecId={`${this && this.props && this.props.ecId || ''}_OrganizationInfo@0fbq0l`} {...this.props} /> : <OrganizationList ecId={`${this && this.props && this.props.ecId || ''}_OrganizationList@k9nuw3`} {...this.props} />}
                  </div>
                }

              </WeaTop>
            </WeaRightMenu>
          </Spin>
        </div>
      );
    }
    if (verified && !hasRight) {
      return (<WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@fmj1gm`} >
        <div style={{ color: '#000' }}>
          {i18n.message.authFailed()}
        </div>
      </WeaAlertPage>)
    }
    return (
      <div></div>
    )
  }
}

export default Organization