import React from 'react'
import {inject,observer} from 'mobx-react';
import {WeaAlertPage} from 'ecCom'
import isEmpty from 'lodash/isEmpty'
import debounce from 'lodash/debounce'
import {
  WeaReportGroup,
  WeaTop,
  WeaTab,
  WeaRightMenu,
  WeaDialog,
  WeaInput,
  WeaFormItem,
  WeaTools} from 'ecCom'
import {Tabs,Button,Spin} from 'antd'
import * as mobx from 'mobx';
import { toJS } from 'mobx';
import {WeaTableNew} from 'comsMobx';
import '../../style/constrpsubsearch.less';
import {routerShape} from 'react-router';
import {i18n} from '../../public/i18n';
const WeaTable = WeaTableNew.WeaTable;

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

  constructor(props) {
    super(props);
  }

  componentDidMount() {
    const { hrmConstRpSubSearch } = this.props;
    const { isCustom } = this.props.location.query;
    hrmConstRpSubSearch.scopeId = this.props.params.scopeId || '';
    hrmConstRpSubSearch.isCustom = isCustom || ''; 
    this.init();
  }

  componentWillReceiveProps(nextProps) {
    const { hrmConstRpSubSearch } = this.props;
    const { isCustom } = nextProps.location.query;
    hrmConstRpSubSearch.scopeId = nextProps.params.scopeId || '';
    hrmConstRpSubSearch.isCustom = isCustom || '';
    if(this.props.location.key !== nextProps.location.key ||
      this.props.params.scopeId !== nextProps.params.scopeId) {
        this.init();
    }
  }

  init = () => {
    const { hrmConstRpSubSearch } = this.props;
    hrmConstRpSubSearch.visible=false;
    hrmConstRpSubSearch.templeteValue='';
    hrmConstRpSubSearch.templateid = '0';
    hrmConstRpSubSearch.getTabInfo({},()=>{
      hrmConstRpSubSearch.getCondition();
    });
  }

  reset = () => {
    const { hrmConstRpSubSearch } = this.props;
    this.refs.report.reset();
    hrmConstRpSubSearch.reset();
  }

  formatData = () => {
    let fieldParams = this.refs.report.get();
    let params = {};
    let fieldnames = [];
    let checkshows = []
    for(let key in fieldParams) {
      let fieldparam = fieldParams[key]
      if(!fieldparam.disabled){
        if(fieldparam.checkRow){
          checkshows.push(key);
          params["con"+key+"_colname"]=key;
          params["con"+key+"_fieldlabel"]=fieldparam.label;
          params["show"+key+"_sn"]=fieldparam.index;
        }
        if(fieldparam.checked){
          fieldnames.push(key);
          params["con"+key+"_colname"]=key;
          let arrConditionType = fieldparam.conditionType.split("_");
          params["con"+key+"_htmltype"]=arrConditionType[0];
          params["con"+key+"_type"]=arrConditionType[1];
          if(fieldparam.value){
            params["con"+key+"_opt"]=fieldparam.value.opt||'';
            params["con"+key+"_opt1"]=fieldparam.value.opt1||'';
            // 司龄、工龄、身高、体重，不输入默认传0上去
            if(fieldparam.conditionType == "1_3"){
              params["con"+key+"_value"]=fieldparam.value.optvalue||'0';
              params["con"+key+"_value1"]=fieldparam.value.opt1value||'';
            }else{
              params["con"+key+"_value"]=fieldparam.value.optvalue||'';
              params["con"+key+"_value1"]=fieldparam.value.opt1value||'';
            }
          }
        }
      }
    }
    params.check_show=checkshows;
    params.check_con=fieldnames;
    return params;
  }

  doSearch = () => {
    const { hrmConstRpSubSearch } = this.props;
    let params = this.formatData();
    hrmConstRpSubSearch.doSearch(params);
  }

  saveTemplete = (params = {}) => {
    const { hrmConstRpSubSearch } = this.props;
    let tmpTabKey = hrmConstRpSubSearch.tabkey;
    let formParams = this.formatData();
    params.scopeId = hrmConstRpSubSearch.scopeId;
    if(hrmConstRpSubSearch.isCustom=='1'){
      params.scopeCmd = '0';
    }else{
      if(tmpTabKey&& tmpTabKey.split("_").length==3){
        let tmpValue = tmpTabKey.split("_");
        params.scopeCmd = tmpValue[1];
      }else{
        params.scopeCmd = tmpTabKey;
      }
    }
    hrmConstRpSubSearch.saveTemplete({...params,...formParams});
  }

  doSave = () => {
    let params = {};
    params.doSave=true;
    this.saveTemplete(params);
  }

  reSave = () => {
    const { hrmConstRpSubSearch } = this.props;
    hrmConstRpSubSearch.isReSave = true;
    hrmConstRpSubSearch.updateVisible(true);
  }

  doDel = () => {
    const { hrmConstRpSubSearch } = this.props;
    const { templateid } = hrmConstRpSubSearch;
    if(templateid!='0'){
      hrmConstRpSubSearch.deleteTabs();
    }
  }

  getRightMenu = () => {
    const { hrmConstRpSubSearch } = this.props;
    const { showResult,templateid } = hrmConstRpSubSearch;

    let btns =[];
    const btnDoSearch = {
      icon: <i className='icon-coms-search'/>,
      content: i18n.button.search()
    };
    const btnSave = {
      icon: <i className='icon-coms-common'/>,
      content: i18n.button.save()
    };
    const btnDel = {
      icon: <i className='icon-coms-common'/>,
      content: i18n.button.delete()
    };
    const btnReSearch = {
      icon: <i className='icon-coms-go-back'/>,
      content:i18n.button.research()
    };
    const btnReSet = {
      icon: <i className='icon-coms-Return'/>,
      content:i18n.button.reset()
    };
    const btnSaveTemplete = {
      icon: <i className='icon-coms-content-o'/>,
      content:i18n.button.saveAsTemplate()
    };
    const btnReSaveTemplete = {
      icon: <i className='icon-coms-content-o'/>,
      content:i18n.button.saveAs()
    };
    const btnImportExcel = {
      icon: <i className='icon-coms-export'/>,
      content:i18n.button.export()
    };

    if(showResult){
      btns.push(btnReSearch);
      btns.push(btnImportExcel);
    }else{
      if(templateid == '0'){
        btns.push(btnDoSearch);
        btns.push(btnReSet);
        btns.push(btnSaveTemplete);
      }else{
        btns.push(btnDoSearch);
        btns.push(btnSave);
        btns.push(btnDel);
        btns.push(btnReSaveTemplete);
      }
    }
    return btns;
  }

  onRightMenuClick = (key) => {
    const { hrmConstRpSubSearch } = this.props;
    const { showResult,templateid } = hrmConstRpSubSearch;

    if(showResult){
      switch(key){
        case '0':
          hrmConstRpSubSearch.reSearch();
          break;
        case '1':
          hrmConstRpSubSearch.importExcel();
          break;
      }
    }else{
      if(templateid=='0'){
        switch(key){
          case '0':
            this.doSearch();
            break;
          case '1':
            this.reset();
            break;
          case '2':
            hrmConstRpSubSearch.updateVisible(true);
            break;
        }
      }else{
        switch(key){
          case '0':
            this.doSearch();
            break;
          case '1':
            this.doSave();
            break;
          case '2':
            this.doDel();
            break;
          case '3':
            this.reSave();
            break;
        }
      }

    }
   
  }

  getTopButtons = () => {
    const { hrmConstRpSubSearch } = this.props;
    const { showResult, templateid} = hrmConstRpSubSearch;
    let btns =[];
    const btnDoSearch = <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ejagbt`} type="primary" className='wea-hrm-top-buttons' onClick={()=>this.doSearch()} >{i18n.button.search()}</Button>;
    const btnDoSave = <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@4bxn1b`} type="primary" className='wea-hrm-top-buttons' onClick={()=>this.doSave()} >{i18n.button.save()}</Button>;
    const btnDoDel= <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@f4rnx1`} type="primary" className='wea-hrm-top-buttons' onClick={()=>this.doDel()} >{i18n.button.delete()}</Button>;
    const btnReSearch = <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ha6av2`} type="primary" className='wea-hrm-top-buttons' onClick={()=>hrmConstRpSubSearch.reSearch()} >{i18n.button.research()}</Button>;
    const btnReSet = <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@fsjxy3`} type="primary" className='wea-hrm-top-buttons' onClick={()=>this.reset()} >{i18n.button.reset()}</Button>;
    const btnSaveTemplete = <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@sr9a7y`} type="primary" className='wea-hrm-top-buttons' onClick={()=>hrmConstRpSubSearch.updateVisible(true)} >{i18n.button.saveAsTemplate()}</Button>;
    const btnReSaveTemplete = <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@odowk6`} type="primary" className='wea-hrm-top-buttons' onClick={()=>this.reSave()} >{i18n.button.saveAs()}</Button>;
    const btnImportExcel = <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@cyf88b`} type="primary" onClick={debounce(()=>hrmConstRpSubSearch.importExcel(),1000)} >{i18n.button.export()}</Button>;
    if(showResult){
      btns.push(btnReSearch);
      btns.push(btnImportExcel);
    }else{
      if(templateid=='0'){
        btns.push(btnDoSearch);
        btns.push(btnReSet);
        btns.push(btnSaveTemplete);
      }else{
        btns.push(btnDoSearch);
        btns.push(btnDoSave);
        btns.push(btnDoDel);
        btns.push(btnReSaveTemplete);
      }
    }
    return btns;
  }

  getDialogBtns = () => {
    const { hrmConstRpSubSearch } = this.props;
    const btns = [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@7tlzld@1`} type='primary' onClick={() => {
      this.saveTemplete();
    }}
    >{i18n.button.save()}</Button>];
    return btns;
  }
  
  getTabChildren = () => {
    const {hrmConstRpSubSearch} = this.props;
    let {topTabkey,tabkey,tabDatas} = hrmConstRpSubSearch;
    let tabChildren;
    tabDatas && tabDatas.map((t,i)=>{
      if (topTabkey === t.key) {
        tabChildren=<WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@ewiona@${i}`}
              type='card'
              selectedKey={tabkey}
              datas={toJS(t.tabinfo)}
              keyParam='key'
              onChange={(key)=>{this.refs.report && this.refs.report.reset();hrmConstRpSubSearch.changeTab(key)}}
            />
      }
    })
    return tabChildren;
  }

  getCustomTabChildren = () => {
    const {hrmConstRpSubSearch} = this.props;
    let {tabkey,tabDatas} = hrmConstRpSubSearch;
    let tabChildren;
    tabDatas = toJS(tabDatas);
    tabDatas && tabDatas.map((t,i)=>{
      tabChildren = <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@5wl08d@${i}`}
                  type='card'
                  selectedKey={tabkey}
                  datas={toJS(t.tabinfo)}
                  keyParam='key'
                  onChange={(key)=>{this.refs.report && this.refs.report.reset();hrmConstRpSubSearch.changeTab(key)}}
                />
    })
    return tabChildren;
  }

  getTableWidth = (columns) => {
    const columnLength = columns.filter((col)=>col.display === 'true').length;
    if(columnLength>10){
      return columnLength*160;
    }else{
      return '100%' 
    }
  }

  rowKey = (record,index)=> index

  getBreadcrumb = () => {
    let {router} = this.context;
    const { hrmConstRpSubSearch } = this.props;
    const { title,isCustom } = hrmConstRpSubSearch;
    const arr = [];
    if(isCustom=='1'){
      arr.push({
        name: i18n.label.customerInfo(),
        onClick: () => {
          if (router) {
            router.push({
                pathname: `/main/hrm/rpsubsearch`
            });
          }
        },
      });
      arr.push({
        name: title,
        onClick: () => {},
      });
    }else{
      arr.push({
        name: title,
        onClick: () => {},
      });
    }
    return arr;
  }

  tabsOnChange = (key) => {
    const { hrmConstRpSubSearch } = this.props;
    this.refs.report && this.refs.report.reset();
    hrmConstRpSubSearch.changeTopTab(key);
  }
  
  render(){
    const { hrmConstRpSubSearch } = this.props;
    let { verified, hasRight, title,form,table,config,showResult,tabDatas,topTabkey,visible,templeteValue, isCustom} = hrmConstRpSubSearch;
    config = toJS(config)
    if (verified && hasRight) {
     return( <div className='wea-hrm-const_rpsubsearch'>
        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@5fyl4d`}
          visible={visible}
          onCancel={()=>hrmConstRpSubSearch.updateVisible(false)}
          closable
          style={{width: 500, height: 120}}
          title = {i18n.button.saveAsTemplate()}
          icon="icon-coms-hrm"
          iconBgcolor='#217346'
          buttons = {this.getDialogBtns()}
        >
          <div style={{padding: 20}}>
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@4l6nw5`}
                label={i18n.label.templateName()}
                labelCol={{span: 6}}
                wrapperCol={{span: 14}}>
                  <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@51apfq`} viewAttr="3" value={templeteValue} onChange={(v)=> hrmConstRpSubSearch.updateTempleteValue(v)}/>
                </WeaFormItem>
          </div>
        </WeaDialog>
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@wrn73p`}  datas={this.getRightMenu()} onClick={this.onRightMenuClick}>
          <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@ch3szg`}
            //title={title}
            breadcrumb={ this.getBreadcrumb() }
            loading={false}
            icon={<i className='icon-coms-hrm' />}
            iconBgcolor='#217346'
            buttons={this.getTopButtons()}
            buttonSpace={10}
            showDropIcon={true}
            dropMenuDatas={this.getRightMenu()}
            onDropMenuClick={this.onRightMenuClick}
          > 
          <div className='wea-hrm-detialtabinfo'>
            {
               isCustom == '1' && <div className='wea-hrm-cus_detialtabinfo'>{this.getCustomTabChildren()}</div>
            }
            {
               isCustom != '1' && <div>
                  <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@tqisae`}
                    type='editable-inline'
                    keyParam='key'
                    datas={tabDatas}
                    selectedKey={topTabkey}
                    onChange={this.tabsOnChange}
                  />
                  {this.getTabChildren()}
               </div>
            }
          </div>
          {
            !showResult && !isEmpty(config) && <WeaReportGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaReportGroup@0wcu7g`} ref="report" config={config} hasIndex/>
          }
          {
            showResult && <div>
                <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@1nuto1`}
                  comsWeaTableStore={table}
                  hasOrder={true}
                  needScroll={true}
                  tableWidth={this.getTableWidth}
                  //getColumns={c=>this.reRenderColumns(c)}
                  rowKey={this.rowKey}
                  />
            </div>
          }
          </WeaTop>
        </WeaRightMenu>
        </div> ); 
    }
    if (verified && !hasRight) {
        return (<WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@vxsv31`} >
                <div style={{color : '#000'}}>
                    {i18n.message.authFailed()}
                </div>
            </WeaAlertPage>
        )
    }
    return (
        <div></div>
    )
  }
}
export default Main