import React from 'react';
import { inject, observer} from 'mobx-react';
import {WeaTop, WeaTab,WeaRightMenu,WeaErrorPage,WeaSearchGroup,WeaFormItem,WeaSelect,WeaAlertPage,} from 'ecCom';
import {Button, Spin} from 'antd';
import {routerShape} from 'react-router';
import * as mobx from 'mobx';
const toJS = mobx.toJS;
import {WeaTableNew,WeaSwitch} from 'comsMobx';
import {i18n} from '../../public/i18n';
const WeaTable = WeaTableNew.WeaTable;

@inject('hrmRpSubSearch')
@observer
class RpSubSearch extends React.Component {
  static contextTypes = {
    router: routerShape
  }

  constructor(props) {
    super(props);
    const funcs = ['jumpToReport'];
    funcs.forEach(f=> this[f] = this[f].bind(this))
  }

  componentDidMount() {
    const { hrmRpSubSearch } = this.props;
    hrmRpSubSearch.getHasRight();
  }

  componentWillReceiveProps(nextProps) {
    const { hrmRpSubSearch } = this.props;
    if(this.props.location.key !== nextProps.location.key){
      hrmRpSubSearch.getHasRight();
    }
  }

  render(){
    const { hrmRpSubSearch } = this.props;
    const {title,form,table,showSearchAd,searchParamsAd,verified,hasRight} = hrmRpSubSearch;

    if (verified && hasRight) {
      const formParams = form.getFormParams();
      let loadingTable = table.loading;
      return (
        <div className='wea-myhrm-RpSubSearch'>
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@lc3niw`} datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)}>
          <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@ium9oy`}
            title={title()}
            loading={loadingTable}
            icon={<i className='icon-coms-hrm' />}
            iconBgcolor='#217346'
            buttons={[]}
            buttonSpace={10}
            showDropIcon={false}
          >
          <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@qa5l5l`}
            buttonsAd={this.getTabButtonsAd()}
            searchType={['base','advanced']}
            searchsBaseValue={formParams.formlabel}
            setShowSearchAd={bool => {hrmRpSubSearch.setShowSearchAd(bool)}}
            hideSearchAd={() => hrmRpSubSearch.setShowSearchAd(false)}
            searchsAd={<div
                onKeyDown={(e) =>{
                  if ( e.keyCode == 13 && e.target.tagName === "INPUT")  {
                    hrmRpSubSearch.doSearch();
                    hrmRpSubSearch.setShowSearchAd(false)
                  }
                } 
              }
              >{this.getSearchs()}</div>}
            showSearchAd={showSearchAd}
            onSearch={v => {hrmRpSubSearch.doSearch()}}
            advanceHeight={150}
            onSearchChange={v => {
              form.updateFields({
                  formlabel:{name:'formlabel',value:v},
                });
              }}
          />
          <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@cqr41w`} spinning={loadingTable}>
            <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@2t49zy`}
              comsWeaTableStore={table}
              hasOrder={true}
              needScroll={true}
              getColumns={this.reRenderColumns}
              />
          </Spin>
          </WeaTop>
          </WeaRightMenu>
        </div>
      );
    }
    if (verified && !hasRight) {
        return (<WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@nwxvft`} >
                <div style={{color : '#000'}}>
                    {i18n.message.authFailed()}
                </div>
            </WeaAlertPage>
        )
    }
    return (
        <div></div>
    )
  }

  getSearchs() {
    const { hrmRpSubSearch } = this.props;
    const { form,condition } = hrmRpSubSearch;
    const {isFormInit} = form;
    let group = [];
    const formParams = form.getFormParams();
    isFormInit && toJS(condition).map((c, i) =>{
      let items = [];
      c.items.map((fields, j) => {
        let dom =  <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@dbqc0n@${j}`} fieldConfig={fields} form={form} formParams={formParams}/>;
        items.push({
          com:(<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@fq3jsx@${j}`}
              label={`${fields.label}`}
              labelCol={{span: `${fields.labelcol}`}}
              wrapperCol={{span: `${fields.fieldcol}`}}>
                {dom}
              </WeaFormItem>),
          colSpan:1,
        })
      });
      group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@x7t2bg@${i}`} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>)
    });
    return group;
  }

  reRenderColumns = (columns) => {
    columns.forEach(c=>{
        if(c.dataIndex=='formlabel'){
          c.render = (text, record) => {
              return  <span style={{cursor:'pointer'}} className='wea-hrm-linkstyle' onClick={() => this.jumpToReport(record.randomFieldId)}>{record.formlabel}</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;
  }

  jumpToReport = (scopeId) => {
    let {router} = this.context;
    if (router) {
      router.push({
          pathname: `/main/hrm/constrpsubsearch/${scopeId}`,
          query: {isCustom: "1"}
      });
    }
  }

  getRightMenu(){
    const keys = this.getSelectedRowKeys();
    const arr = [{
        icon: <i className='icon-coms-ws'/>,
        content:i18n.button.search()
      }, {
        icon: <i className='icon-coms-task-list'/>,
        content:i18n.button.columnVisibleSetting()
      }
    ];
    return arr;
  }

  onRightMenuClick(key){
    const { hrmRpSubSearch } = this.props;
    switch(key){
        case '0':
            hrmRpSubSearch.doSearch();
            break;
        case '1':
            this.definedColumn();
            break;
    }
  }

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

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

  getTabButtonsAd() {
    const { hrmRpSubSearch } = this.props;
    const { form,searchParamsAd } = hrmRpSubSearch;
    return [
        (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@k8yyyu@1`} type="primary" onClick={()=>{hrmRpSubSearch.doSearch();hrmRpSubSearch.setShowSearchAd(false)}}>{i18n.button.search()}</Button>),
        (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@h8vhki@2`} type="ghost" onClick={()=>{form.reset();}}>{i18n.button.reset()}</Button>),
        (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ehyes2@3`} type="ghost" onClick={()=>{hrmRpSubSearch.setShowSearchAd(false)}}>{i18n.button.cancel()}</Button>)
    ]
  }
}

export default RpSubSearch