/**
 * Created by baoyinghai on 11/27/16.
 */
import React from 'react';
import { autobind } from 'core-decorators';
import Qs from 'qs';
import SideMenu, { SideMenuContainer } from './sideMenu';
import Compose from '../../utils/Compose';
import AsyncDecorator from '../../pageContainer/AsyncDecorator';
import InitDecorator from '../../pageContainer/InitDecorator';
import exclusive from '../../pageContainer/exclusive';
import { isApply, isReview } from '../../utils/ProcessHelper';
import {
  getMenuItemByKeyPaths,
  getMenuItemByFunc,
  getMenuItemAndPathByFunc,
  searchBeforeAndAfter,
  getAllLeafs
} from '../../utils/MenuHelper';
import { showModal } from '../../pageContainer/ModalWrapper';
import { getValueByKey } from '../../utils/MapUtils';
import { PAGE_TYPE_DETAIL, PAGE_TYPE_LIST } from '../../constant/dictActions';
import { BUTTON_POSITION, BUTTON_RELATEDDATA } from '../../constant/dictCodes';
import { ExtendButton, BackTop } from '../../../components';
import { filterEmptyValue } from '../../utils/EmptyUtils';
import { convertTemplate, trimStart } from '../../utils/StringUtils';
import { scrollAble, scrollDisable } from '../../utils/ScrollHelper';
import Config from '../../../config';
import Anchor, { archorQuery } from '../../../components/anchor';
import TitleBar from './titleBar';
import InfoException from '../exception/InfoException';

// const IFrame = require('react-iframe');

// const ButtonGroup = Button.Group;


export default class InfoLayout extends React.Component {

  static propTypes = {
    dataSource: React.PropTypes.object
  };

  constructor(props) {
    super(props);
    if (this.props.dataSource && this.props.dataSource.pageMenu && this.props.dataSource.pageMenu.menus) {
      this.tag = getMenuItemByFunc(m => m.isSelected === true, this.props.dataSource.pageMenu.menus)
        || getAllLeafs(this.props.dataSource.pageMenu.menus)[0]; // 没有默认选中的叶子 就选第一个
    }
    const buttons = (this.props.dataSource && this.props.dataSource.buttons) || [];
    const { prefixCls, query, inject } = this.props;
    const buttonClass = `${prefixCls}-button`;
    const menuCode = this.props.query.processMenuId;
    const readonly = this.props.query.readonly === 'true' || this.props.query.readonly === true || this.props.dataSource.readOnly || this.props.query.displayType === 'VIEW';
    const globalBtns = readonly || ((isApply(this.props.domainLink) || isReview(this.props.domainLink)) &&
      (menuCode && menuCode !== 'BPMApply.QueryToDo' && menuCode !== 'BPMReview.QueryToDo' && menuCode !== 'BPMApply.QueryReturned')) ? [] :
      buttons.map(item => (
        <ExtendButton
          type="link"
          inline={false}
          buttonProps={{ type: 'ghost' }}
          {...item}
          disabled={false}
          key={item.buttonDescription}
          query={query}
          className={buttonClass}
          inject={inject}
          relatedRows={BUTTON_RELATEDDATA.NONE}
          onRefresh={() => console.log('!!!!!!!-----onRefresh')}
        />
      ));
    this.state = {
      main: null,
      // current: this.tag,
      topButtons: [],
      globalBtns,
      header: '',
      summarys: [],
      showSummary: true,
      anchor: [],
      sideMenuStatus: true,  // side menu status
      showProcessBtn: false,
      innerHeight: window.innerHeight,
      readonly
    };
  }

  _getIcon = item => {
    return (item && (item.buttonIcon || item.menuIcon)) || Config.DefaultMenuIcon;
  };

  @autobind
  getGlobalButtons() {
    return this.state.globalBtns;
  }

  @autobind
  createTopButtons(data) {
    this.setState({ topButtons: data });
  }

  @autobind
  clearState(cb) {
    this.setState({ topButtons: [], summarys: [] }, cb);
  }

  @autobind
  _renderSummaryHandler(summarys) {
    this.setState({ summarys: summarys });
  }

  @autobind
  createMain(data, domainType, domainLink, displayType, params, updateMain) {
    const TempPage = Compose(AsyncDecorator, InitDecorator)();
    const { query, ...rest } = this.props;
    return (
      <TempPage
        {...rest}
        query={{ ...params, s: '' }} // remove other parameters
        displayType={displayType}
        createTopButtons={domainType === PAGE_TYPE_DETAIL ? this.createTopButtons : null}
        dataSource={data}
        domainType={domainType}
        domainLink={domainLink}
        updateMain={updateMain}
        renderSummaryHandler={this._renderSummaryHandler}
        isInfo={true}
        readonly={this.state.readonly}
        formInfo={true}
        refreshCallback={this.refreshCallback}
      />
    );
  }

  @autobind
  refreshCallback() {
    const { domainLink, domainType } = this.getLinkAndType(this.tag);
    this.updateMain(domainLink, domainType, this.tag);
  }

  @autobind
  getLinkAndType(e) {
    return { domainLink: trimStart(e.domainLink || e.actionLink, '/'), domainType: e.domainType || e.templateType };
  }

  @autobind
  menuClick(m) {
    this.tag = m;
    const { domainLink, domainType } = this.getLinkAndType(m);
    this.updateMain(domainLink, domainType, m);
  }

  // extraParams select params
  @autobind
  createReqParam(menuItem, query = {}, extraParams = {}) {
    // TODO: some all
    let params = {};
    if (this.props && this.props.params) {
      params = { ...params, ...this.props.params, ...query };
    }
    params = { ...params, ...getValueByKey(this.props, {}, 'query'), ...extraParams };
    // TODO: 只传递bindParameters数据
    const ret = {};
    menuItem.bindParameters && menuItem.bindParameters.forEach(item => {
      ret[item.name] = filterEmptyValue(item.value, params[item.name]);
    });
    return ret;
  }

  // TODO: refactor  不需要renderMain
  @autobind
  updateMain(domainLink, dt, mi, extraParams = {}) {
    let domainType = dt;
    let menuItem = mi;
    if (!menuItem) {
      menuItem = this.state.current;
      domainType = this.state.current.domainType;
    }
    const menuCode = menuItem.menuCode;
    // 下部菜单
    // const patch = searchBeforeAndAfter(menuCode, this.props.dataSource.pageMenu.menus);
    // patch.current = menuItem;
    const params = this.createReqParam(menuItem, this.props && this.props.query, extraParams);
    this.props.exec(() => {
      return new Promise((resolve, reject) => {
        const tagLink = trimStart(convertTemplate(domainLink, params, menuItem.actionLinkMappings), '/');
        if (exclusive.some(f => f(tagLink))) {
          resolve({});
        } else {
          this.props.fetch(tagLink, params).then(resolve);
        }
      }).then(data => {
        if (domainType === PAGE_TYPE_DETAIL || domainType === PAGE_TYPE_DETAIL) {
          scrollAble();
        } else {
          scrollDisable();
        }

        this.clearState(() => this.setState({
          header: menuItem.menuValue,
          main: this.createMain(data, extraParams.domainType || domainType, domainLink, extraParams.displayType || menuItem.displayType, params, this.updateMain),
        }, () => this.setState({ anchor: archorQuery() })));
      }).catch(err => {
        console.log('**  error  **', err);
        this.setState({
          main: (<InfoException err={err} />),
        });
        throw err;
      });
    });
  }

  _onBodyScroll = e => {
    const sideMenu = document.querySelector('.info-sidebar-sticky-wrapper');
    const mainContent = document.querySelector('.main-sticky-wrapper');
    /* eslint-disable */
    if (window.scrollY >= 54) {
      sideMenu.classList.add('sticky');
      mainContent.classList.add('sticky-main-content');
      !this.state.showProcessBtn && this.setState({ showProcessBtn: true });
    } else {
      sideMenu.classList.remove('sticky');
      mainContent.classList.remove('sticky-main-content');
      this.state.showProcessBtn && this.setState({ showProcessBtn: false });
    }
  };

  modifyWindowHeight = () => {
    this.setState({ innerHeight: window.innerHeight })
  };

  /* eslint-disable */
  componentDidMount() {
    document.addEventListener('scroll', this._onBodyScroll);
    window.addEventListener('resize', this.modifyWindowHeight );
  }

  componentWillUnmount() {
    document.removeEventListener('scroll', this._onBodyScroll);
    window.removeEventListener('resize', this.modifyWindowHeight );
  }

  componentWillMount() {
    if (this.tag) {
      const { domainLink, domainType } = this.getLinkAndType(this.tag);
      this.updateMain(domainLink, domainType, this.tag);
    }
  }

  /* eslint-disable */
  _modifyStyle = item => {
    if (item) {
      const { domainType } = this.getLinkAndType(item);
      if (domainType === PAGE_TYPE_LIST) {
        return '100%';
      }
    }
    return "";
  };

  // TODO: refactor
  _getTitleDesc = () => {
    const { dataSource = {} } = this.props;
    const { pageMenu = {} } = dataSource;
    const name = pageMenu.name;
    const headerDesc = pageMenu.headerDesc;
    const headerId = pageMenu.headerId;
    if (!headerDesc || headerDesc === 'null') return name;
    if (!headerId || headerId === 'null') return name + '-' + convertTemplate(headerDesc, this.props.query);
    return convertTemplate(headerDesc, this.props.query) + ' ' + convertTemplate(headerId, this.props.query);
  };

  _sideMenuChange = status => {
    this.setState({ sideMenuStatus: status});
  };

  render() {
    const headerStyle = !this.state.showSummary ? { height: '0px', overflow: 'hidden' } : {};
    const lockedLayoutStyle = {};
    const mainGrid = {};
    if ((this.tag.domainType || this.tag.templateType) === PAGE_TYPE_LIST) {
      lockedLayoutStyle.display = 'none';
      mainGrid.height = 'calc(100% - 52px)';
    } else {
      lockedLayoutStyle.borderBottom = '2px solid #00aaef';
    }

    const { pageMenu, infoCompletenessBean } = this.props.dataSource;
    const isNewPage = this.props.query && this.props.query.s === '1';
    /* eslint-disable */
    return (
      <div style={{height: this._modifyStyle(this.tag)}} className="info-wrapper">
        {isNewPage && (
          <TitleBar getTitleDesc={this._getTitleDesc} infoCompleteness={infoCompletenessBean && infoCompletenessBean.totalValue}>
            {this.getGlobalButtons()}
          </TitleBar>
        )}
        <div className="info-container margin-center-container" style={{ margin: isNewPage ? '0 60px' : 0 }}>
          <SideMenuContainer changeHander={this._sideMenuChange}>
            <SideMenu
              infoCompleteness={infoCompletenessBean && infoCompletenessBean.dtoValues}
              menu={pageMenu.menus}
              menuClick={this.menuClick}
              selectedItem={this.tag}
            />
          </SideMenuContainer>
          <div className={'main-grid ' + (this.state.sideMenuStatus ? '' : ' side-menu-close')} style={{ minHeight: this.state.innerHeight - 54 + 'px' }}>
            <div className="locked-layout" style={lockedLayoutStyle}>
              <div className=" main-sticky-wrapper">
                <div className="info-header">
                  <div className="detail-top">
                    <div className="header-spread">
                      <div className="biz-info">
                        <div className="header-primary">
                          <div className="header-col">
                            <h1 className="header-title">
                              <i className={'iconfont ' + this._getIcon(this.tag)  + ' menu-icon-alibb header-ico'} />
                              <span className="header-desc">
                                {this.state.header}
                              </span>
                            </h1>
                          </div>
                          <div className="header-col">
                            <a className="business-info">
                              <i></i>
                              工商信息
                            </a>
                          </div>
                          <div className="header-col">
                            <a className="group-talk">
                              <i></i>
                              讨论一下
                            </a>
                          </div>
                        </div>
                      </div>
                      <div className="header-menu">
                        {this.state.topButtons && this.state.topButtons.length > 0 ? (
                          <div className="button-bar">
                            <ul className="button-bar-list">
                              {this.state.topButtons && this.state.topButtons.map((item, index) => {
                                return (
                                  <li key={index} style={!index && { borderTopLeftRadius: '4px', borderBottomLeftRadius: '4px' }}>
                                    {item}
                                  </li>
                                );
                              })}
                            </ul>
                          </div>
                        ) : null}
                      </div>
                    </div>
                    {this.state.summarys && this.state.summarys.length > 0 && (
                      <div className="header-detail" style={headerStyle}>
                        <ul className="summary-field">
                        {this.state.summarys.map(summary => {
                          return (
                            <li className="summary-col" style={{width: ((100 / this.state.summarys.length) + '%')}}>
                              <div className="summary-col-item">
                                <div className="summary-col-label">
                                  <span className="ellipsis">{summary.label}</span>
                                </div>
                                <div className="summary-col-value">
                                  <span className="ellipsis">{summary.value}</span>
                                </div>
                              </div>
                            </li>
                          );
                        })}
                        </ul>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </div>
            <div className="main_grid_middlle" style={mainGrid}>
              <div className="info-wrapper-margin">
                <div style={{height: '100%', overflowY: ''}}>
                  {this.state.main}
                </div>
              </div>
            </div>
            <Anchor links={this.state.anchor}>
              {this.state.showProcessBtn && this.getGlobalButtons()}
            </Anchor>
            <BackTop />
          </div>
        </div>
      </div>
    );
  }
}
