import {
  inject,
  observer
} from 'mobx-react';
import {
  Button,
  Form,
  Modal,
  message,
  Spin
} from 'antd';
import isEmpty from 'lodash/isEmpty'
import {
  WeaTop,
  WeaTab,
  // WeaOrgTree,
  WeaLeftRightLayout,
  WeaRightMenu,
  WeaErrorPage,
  WeaTools,
  WeaSearchGroup,
  WeaDialog,
  WeaInput,
  WeaInputSearch,
  WeaDropMenu,
  WeaFormItem,
  WeaTransfer,
  WeaSelect,
} from 'ecCom';
import trim from 'lodash/trim'
import {
  WeaTableNew,
  WeaSwitch
} from 'comsMobx';
const {
  WeaTable
} = WeaTableNew;
import '../style/addressBook.less';
import * as PublicFunc from '../util/pulic-func';
import {
  jumpToHrmCard,
  jumpToHrmSubCompany,
  jumpToHrmDept,
  jumpToHrmPost
} from '../util/pulic-func'
import cloneDeep from 'lodash/cloneDeep';
import AddressBookExportSetting from './resourceExportTemplate/AddressBookExportSetting';
import {
  i18n
} from '../public/i18n';

@inject('hrmAddressBook')
@observer
export default class AddressBook extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      transferVisible: false
    }
  }
  componentDidMount() {
    // const {
    //   from,
    //   lastname
    // } = this.props.location.query;
    const {
      hrmAddressBook
    } = this.props;
    // hrmAddressBook.searchFrom = from || '';
    // hrmAddressBook.searchKeyWord = lastname || '';
    const paramsFromURL = this.props.location.query;
    this.init(paramsFromURL);
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.location.key !== nextProps.location.key) {
      // const {
      //   from,
      //   lastname
      // } = nextProps.location.query;
      const {
        hrmAddressBook
      } = this.props;
      // hrmAddressBook.searchFrom = from || '';
      // hrmAddressBook.searchKeyWord = lastname || '';
      // this.refs.WeaOrgTree.reset(()=>{
      //   this.refs.WeaOrgTree.fetchData();
      // });
      const paramsFromURL = nextProps.location.query;
      this.init(paramsFromURL);
    }
  }

  init = (paramsFromURL) => {
    const {
      type,
      id
    } = this.props.location.query;
    const {
      hrmAddressBook
    } = this.props;
    hrmAddressBook.showAllLevel = true;
    hrmAddressBook.rightMenus = []
    hrmAddressBook.defaultShowLeft = false;
    if (hrmAddressBook.searchFrom && hrmAddressBook.searchFrom == 'quickSearch') {
      hrmAddressBook.tabkey = 'default_3';
    } else {
      hrmAddressBook.tabkey = 'default_3';
    }

    let params = {}
    if (type && type != '' && id && id != '') {
      if (type == '1') {
        params['subcompanyid1'] = id;
      }
      if (type == '2') {
        params['departmentid'] = id;
      }
    }
    Object.assign(params, paramsFromURL);
    hrmAddressBook.getData(params);
    hrmAddressBook.getRightMenuConfig();
    hrmAddressBook.updateShowSearchAd(false);
    hrmAddressBook.updateVisible1(false);
    hrmAddressBook.updateVisible2(false);
  }

  onTabEdit = (targetKey, action) => {
    const {
      hrmAddressBook
    } = this.props;
    if (action === 'remove') {
      let params = {};
      params.opera = "delete";
      params.mouldid = targetKey;
      hrmAddressBook.deleteTabs(params);
    }
  }

  reRenderColumns = (columns) => {
    let __this = this;
    columns.forEach(c => {
      if (c.dataIndex == 'lastname') {
        c.render = function(text, record) {
          return <span style={{cursor:'pointer'}} className='wea-hrm-linkstyle' onClick={()=>jumpToHrmCard(record.id)}>{record.lastname}</span>
        }
      } else if (c.dataIndex == 'managerid') {
        c.render = function(text, record) {
          return <span style={{cursor:'pointer'}} className='wea-hrm-linkstyle' onClick={()=>jumpToHrmCard(record.managerid)} dangerouslySetInnerHTML={{__html: record.manageridspan}}></span>
        }
      } else if (c.dataIndex == 'subcompanyid1') {
        c.render = function(text, record) {
          return <span style={{cursor:'pointer'}} className='wea-hrm-linkstyle' onClick={()=>jumpToHrmSubCompany(record.subcompanyid1)} dangerouslySetInnerHTML={{__html: record.subcompanyid1span}}></span>
        }
      } else if (c.dataIndex == 'departmentid') {
        c.render = function(text, record) {
          return <span style={{cursor:'pointer'}} className='wea-hrm-linkstyle' onClick={()=>jumpToHrmDept(record.departmentid)} dangerouslySetInnerHTML={{__html: record.departmentidspan}}></span>
        }
      } else if (c.dataIndex == 'jobtitle') {
        c.render = function(text, record) {
          return <span style={{cursor:'pointer'}} className='wea-hrm-linkstyle' onClick={()=>jumpToHrmPost(record.jobtitle)} dangerouslySetInnerHTML={{__html: record.jobtitlespan}}></span>
        }
      } else {
        c.render = function(text, record) {
          let valueSpan = record[c.dataIndex + "span"] !== undefined ? record[c.dataIndex + "span"] : record[c.dataIndex];
          return <span dangerouslySetInnerHTML={{__html: valueSpan}}></span>
        }
      }
    })
    return columns;
  }

  onOperatesClick = (record, index, operate, flag, argumentString) => {
    const fn = operate.href ? operate.href.split(':')[1].split('(')[0] : '';
    const id = record.id ? record.id : '';
    PublicFunc[fn](id);
  }

  onClickHandle1 = () => {
    this.props.hrmAddressBook.updateShowSearchAd(false);
    this.doSearch();
  }

  onClickHandle2 = () => {
    this.props.hrmAddressBook.updateVisible2(true)
  }

  onClickHandle3 = () => {
    this.props.hrmAddressBook.formatTransfer();
    this.props.hrmAddressBook.updateVisible1(true)
  }

  onClickHandle4 = () => this.props.hrmAddressBook.updateShowSearchAd(false)

  getTabButtonsAd = () => {
    const {
      hrmAddressBook
    } = this.props;
    const {
      tabkey,
      form
    } = hrmAddressBook;
    const btns = [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@deghjo@1`} type='primary' onClick={this.onClickHandle1}>{i18n.button.search()}</Button>];
    tabkey == 'default_3' && btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@s5oxto@2`} type='primary' onClick={this.onClickHandle2}>{i18n.button.saveAsTemplate()}</Button>);
    tabkey == 'default_3' && btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@y5v77k@3`} type='primary' onClick={this.onClickHandle3}>{i18n.button.conditionDef()}</Button>);
    btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@vq8blp@4`} type='ghost' onClick={form.resetConditionValue}>{i18n.button.reset()}</Button>);
    btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@qadwox@5`} type='ghost' onClick={this.onClickHandle4}>{i18n.button.cancel()}</Button>);
    return btns;
  }
  getSearchs = () => {
    const {
      hrmAddressBook
    } = this.props;
    const {
      conditioninfo,
      conditioninfoAll,
      form,
      showAllCondition
    } = hrmAddressBook;
    const {
      isFormInit
    } = form;
    let ci = showAllCondition ? conditioninfoAll : conditioninfo;
    const group = [];
    isFormInit && ci.forEach((c, i) => {
      let items = [];
      c.items.forEach((field, j) => {
        if (field.isQuickSearch) {
          this.quickSearchPara = field.domkey[0];
        }
        items.push({
          com: (
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@g3vv2f@${j}`}
              label={`${field.label}`}
              labelCol={{ span: field.labelcol }}
              wrapperCol={{ span: field.fieldcol }}
            >
              <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@0g2l92@${j}`} fieldConfig={field} form={form} />
            </WeaFormItem>
          ),
          colSpan: 1,
        });
      });
      group.push(
        <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@f3dgvw@${i}`} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items} />
      );
    });
    return <div>
      {group}
      {!showAllCondition && <div style={{textAlign: 'right', padding: '20px 25px'}}>
        <span className="cursor-pointer" onClick={this.onClickHandle5} style={{marginRight: 12}}>
          <span style={{marginRight: 8}}>{i18n.label.allCondition()}</span><i className="icon-coms-right" style={{color: '#b2b2b2'}}/></span>
      </div>}
    </div>
  }

  onClickHandle5 = () => this.props.hrmAddressBook.updateShowAllCondition(true)

  getRightMenu = () => {
    const {
      hrmAddressBook
    } = this.props;
    const {
      rightMenus
    } = hrmAddressBook;
    let btns = [];
    const keys = this.getSelectedRowKeys();
    !isEmpty(rightMenus) && rightMenus.forEach((c) => {
      let item = {
        icon: <i className={`${c.menuIcon}`}/>,
        content: c.menuName,
      }
      if (c.menuFun == 'sendEmessage') item.disabled = keys.length == 0;
      btns.push(item);
    })
    return btns;
  }

  onRightMenuClick = (key) => {
    const {
      hrmAddressBook
    } = this.props;
    const {
      rightMenus
    } = hrmAddressBook;
    const menuFun = rightMenus[key].menuFun;
    this[menuFun] && this[menuFun]();
  }

  getTree = () => {
    return (
      <WeaOrgTree ecId={`${this && this.props && this.props.ecId || ''}_WeaOrgTree@f8as9n`}
          ref='WeaOrgTree'
          loading
          needSearch
          isLoadSubDepartment={true}
          topPrefix={'hrmSearch'}
          inputLeftDom = {`<b>${i18n.label.organization()}</b`}
          treeNodeClick={this.treeNodeClick}
      />
    )
  }

  treeNodeClick = (event) => {
    const {
      hrmAddressBook
    } = this.props;
    const {
      form
    } = hrmAddressBook;
    const type = event.node.props.type || '0';
    const id = event.node.props.id || '';
    let params = {};
    form.resetConditionValue();
    hrmAddressBook.updateShowSearchAd(false);
    hrmAddressBook.tabkey = 'default_3';
    if (type == '1') {
      params['subcompanyid1'] = id;
    }
    if (type == '2') {
      params['departmentid'] = id;
    }
    hrmAddressBook.doSearch(params);
  }
  getDialogBtns1 = () => {
    const {
      hrmAddressBook
    } = this.props;
    const btns = [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@5hyrlh@1`} type='primary' onClick={hrmAddressBook.saveHrmSearchUserDefine}>{i18n.button.save()}</Button>];
    return btns;
  }
  getDialogBtns2 = () => {
    const {
      hrmAddressBook
    } = this.props;
    const btns = [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@k9g3fa@1`} type='primary' onClick={hrmAddressBook.saveTemplete}>{i18n.button.save()}</Button>];
    return btns;
  }
  filterLeft = (items) => {
    let leftItems = cloneDeep(items)
    const {
      hrmAddressBook
    } = this.props;
    const {
      transferleftIptVal,
      transferSelectedKey
    } = hrmAddressBook;
    if (transferSelectedKey) {
      leftItems = leftItems.filter((item) => item.idx == transferSelectedKey)
    }
    if (trim(transferleftIptVal)) {
      leftItems = leftItems.filter((item) => item.label.indexOf(trim(transferleftIptVal)) > -1)
    }
    return leftItems
  }
  filterRight = (items) => {
    let rightItems = cloneDeep(items)
    const {
      hrmAddressBook
    } = this.props;
    const {
      transferRightIptVal
    } = hrmAddressBook;
    if (trim(transferRightIptVal)) {
      rightItems = rightItems.filter((item) => item.label.indexOf(trim(transferRightIptVal)) > -1)
    }
    return rightItems
  }
  renderItem = (item) => {
    return <div className="trasfer-list-item">
      <div className="top text-overflow" title={item.label}>{item.label}</div>
      <div className="bottom text-overflow" title={item.title}>{item.title}</div>
    </div>
  }
  renderTransfer = () => {
    const {
      hrmAddressBook
    } = this.props;
    let {
      transferDatas,
      transferKeys,
      transferOptions,
      transferleftIptVal,
      transferRightIptVal,
      transferSelectedKey
    } = hrmAddressBook;
    transferDatas = transferDatas;
    transferKeys = transferKeys;
    transferOptions = transferOptions;
    return <div style={{padding: 20}}>
      {
        !isEmpty(transferDatas) && <WeaTransfer ecId={`${this && this.props && this.props.ecId || ''}_WeaTransfer@exqx7p`}
          icon="icon-coms-hrm"
          iconBgcolor='#217346'
          filterLeft={this.filterLeft}
          filterRight={this.filterRight}
          height={350}
          leftHeader={
            <div className="trasfer-header">
              <span>{i18n.label.toBeSelected()}</span>
              <WeaInputSearch ecId={`${this && this.props && this.props.ecId || ''}_WeaInputSearch@yo9vg4`}
                value={transferleftIptVal}
                onSearchChange={hrmAddressBook.updateTransferleftIptVal}
              />
              <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@pcm3mi`}
                options={transferOptions}
                value={transferSelectedKey}
                onChange={hrmAddressBook.updateTransferSelectedKey}
              />
            </div>
  }
  rightHeader = {
    <div className="trasfer-header">
              <span>{i18n.label.selected()}</span>
              <WeaInputSearch ecId={`${this && this.props && this.props.ecId || ''}_WeaInputSearch@tpx8un`}
                value={transferRightIptVal}
                onSearchChange={hrmAddressBook.updateTransferRightptVal}
              />
            </div>
  }
  renderItem = {
    this.renderItem
  }
  data = {
    transferDatas
  }
  selectedKeys = {
    transferKeys
  }
  onChange = {hrmAddressBook.updateTransferKeys}
  />
} </div>
}
getTopButtons = () => {
  const {
    hrmAddressBook
  } = this.props;
  const {
    showAllLevel,
    tabkey,
    rightMenus
  } = hrmAddressBook;
  const keys = this.getSelectedRowKeys();
  let btns = [];

  const btnShowAllLevel = <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@px81w6`} size="small" style={{height: '28px'}} onClick={this.changeShowAllLevel} title={showAllLevel?i18n.button.DisplaySubordinateSubordinates():i18n.button.directSubordinates()}>
                            <span>{showAllLevel?
                                  <i className='icon-coms-DisplaySubordinates' style={{color: '#2db7f5'}}/>
                                  :<i className='icon-coms-NoDisplayOfSubordinates'/>}</span>
                          </Button>;
  if (tabkey == 'default_2') {
    btns.push(btnShowAllLevel);
  }
  rightMenus.map((item, index) => {
    if (item.isTop && item.isTop == '1') {
      btns.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@q4w23a@${index}`} type='primary' onClick={this[item.menuFun]} disabled={ item.menuFun=='sendEmessage' && keys.length == 0}>{item.menuName}</Button>);
    }
  });
  return btns;
}

changeShowAllLevel = () => {
  const {
    hrmAddressBook
  } = this.props;
  hrmAddressBook.changeShowAllLevel();
}

sendEmessage = () => {
  const keys = this.getSelectedRowKeys();
  const ids = keys ? keys.join(',') : '';
  PublicFunc.sendEmessage(ids);
}

exportExcel = () => {
  const {
    hrmAddressBook
  } = this.props;

  hrmAddressBook.initExportSetting();
  return;
  hrmAddressBook.exportExcel();
}

doSearch = (params) => {
  const {
    hrmAddressBook
  } = this.props;
  hrmAddressBook.doSearch(params);
}
reSearch = () =>{
  const {
    hrmAddressBook
  } = this.props;
  hrmAddressBook.reSearch();
}
definedColumn = () => {
  const {
    hrmAddressBook
  } = this.props;
  const {
    table
  } = hrmAddressBook;
  table.setColSetVisible(true);
  table.tableColSet(true);
}

getSelectedRowKeys = () => {
  const {
    hrmAddressBook
  } = this.props;
  const {
    table
  } = hrmAddressBook;
  const selectedRowKeys = table.selectedRowKeys;
  return selectedRowKeys;
}

onCancel1 = () => this.props.hrmAddressBook.updateVisible1(false)

onCancel2 = ()=> this.props.hrmAddressBook.updateVisible2(false)

hideSearchAd = () => this.props.hrmAddressBook.updateShowSearchAd(false)

onSearchChange = value => {
  this.props.hrmAddressBook.form.updateFields({ [this.quickSearchPara || 'lastname']: { value } })
}

render() {
  const {
    hrmAddressBook
  } = this.props;
  const {
    title,
    tabs,
    tabkey,
    showSearchAd,
    loading,
    comsWeaTableStore,
    form,
    table,
    visible1,
    visible2,
    templeteValue,
    defaultShowLeft,
    spinning
  } = hrmAddressBook;
  const formParams = form.getFormParams();
  return (
    <div className='wea-hrm-address'>
        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@a3ugp6`}
          className="wea-hrm-address-dialog"
          visible={visible1}
          onCancel={this.onCancel1}
          closable
          style={{width: 700, height: 440}}
          title = {i18n.button.conditionDef()}
          icon="icon-coms-hrm"
          iconBgcolor='#217346'
          buttons = {this.getDialogBtns1()}
        >
          {this.renderTransfer()}
        </WeaDialog>
        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@rz78aq`}
          visible={visible2}
          onCancel={this.onCancel2}
          closable
          style={{width: 500, height: 120}}
          title = {i18n.button.saveAsTemplate()}
          icon="icon-coms-hrm"
          iconBgcolor='#217346'
          buttons = {this.getDialogBtns2()}
        >
          <div style={{padding: 20}}>
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@0kf0cj`}
                label={i18n.label.searchTemplateName()}
                labelCol={{span: 6}}
                wrapperCol={{span: 14}}>
                  <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@s9u1lu`} viewAttr="3" value={templeteValue} {...window.inputType} value={''} onChange={hrmAddressBook.updateTempleteValue}/>
                </WeaFormItem>
          </div>
        </WeaDialog>
        <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@8cgcko`} spinning={spinning}>
          <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@30gfii`}  datas={this.getRightMenu()} onClick={this.onRightMenuClick}>
              <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@55dlzb`}
                title={title()}
                loading={false}
                icon={<i className='icon-coms-hrm' />}
                iconBgcolor='#217346'
                buttons={this.getTopButtons()}
                buttonSpace={10}
                showDropIcon={true}
                dropMenuDatas={this.getRightMenu()}
                onDropMenuClick={this.onRightMenuClick}
              > 
                {/*<WeaLeftRightLayout isNew={true} showLeft={defaultShowLeft} leftCom={this.getTree()}>*/}
                    <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@8gzq0y`}
                      type='editable-inline'
                      buttonsAd={this.getTabButtonsAd()}
                      searchType={['base', 'advanced']}
                      searchsBaseValue={form.getFormParams()[this.quickSearchPara || 'lastname'] || ''}
                      searchsAd={this.getSearchs()}
                      showSearchAd={showSearchAd}
                      setShowSearchAd={bool => {hrmAddressBook.updateShowSearchAd(bool); }}
                      hideSearchAd={this.hideSearchAd}
                      keyParam='typeid'
                      // datas={toJS(tabs)}
                      selectedKey={tabkey}
                      onChange={hrmAddressBook.updateTabkey}
                      onSearch={hrmAddressBook.getSearchList}
                      onSearchChange={this.onSearchChange}
                      onEdit={this.onTabEdit}
                    />
                    <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@5zy2oz`}
                      comsWeaTableStore={table}
                      hasOrder={true}
                      needScroll={true}
                      getColumns={this.reRenderColumns}
                      onOperatesClick={this.onOperatesClick}
                    />
               {/* </WeaLeftRightLayout>*/}
              </WeaTop>
          </WeaRightMenu>
        </Spin>
        <AddressBookExportSetting ecId={`${this && this.props && this.props.ecId || ''}_AddressBookExportSetting@cvxdsn`} store={hrmAddressBook} />
      </div>
  );
}
}