/**
 * @Date:   2019-05-28T13:23:00+08:00
 * @Last modified time: 2019-05-29T15:33:03+08:00
 */
/**
 * Created by pengmin on 201210510. 该组件的作用是列表标题行通过存储过程返回值设定 不通过后台配置
 */
import React, { Component } from 'react';
import { Form } from '@ant-design/compatible';
// import '@ant-design/compatible/assets/index.css';
import { Layout, Spin } from 'antd-v4';
import CommonListEvent from './CommonListEvent';/* 继承销售模块业务功能 */
import * as commonFunc from './commonFunc';/* 通用单据方法 */ /* 通用单据方法 */
import Toolbar from '../Common/ToolBar/ToolBarNew';
import StaticEditTable from './CommonTable';/* 可编辑表格 */
import styles from '../../index.less';
import CommonBase from './CommonBase';/* 获取配置及数据 */
import * as commonBusiness from './commonBusiness';/* 单据业务功能 */
import SearchComponent from './SearchComponent';/* 搜索组件 */
import commonConfig from '../../utils/config';
import * as commonUtils from '../../utils/utils';
// import SlaveMemo from './SlaveMemo';
import StaticEditTree from './Tree/StaticTree';
import Eject from '../../assets/eject.svg';/* 弹出图标 */
import Close from '../../assets/close.svg';/* 关闭图标 */
import AntdDraggableModal from './AntdDraggableModal';
import CommonListSelect from './CommonListSelect';/* 选择界面 */

const { Header, Content } = Layout;
let NoTotalData = '';
class CommonList extends Component {
  constructor(props) {
    super(props);
    this.state = {
    };
  }
  componentWillReceiveProps(nextProps) {
    const { slaveData, slaveColumnNew } = nextProps;
    /* 将数据集里中的字段作为标题行 */
    if (commonUtils.isNotEmptyArr(slaveData) && commonUtils.isEmpty(slaveColumnNew)) {
      let column = [];
      const slaveConfig = {};
      const gdsconfigformslave = [];
      const slaveRow = slaveData[0];
      if (commonUtils.isNotEmptyObject(slaveRow)) {
        for (const key of Object.keys(slaveRow)) {
          if (commonUtils.isNotEmptyObject(key)) {
            column.push({
              title: key,
              dataIndex: key,
              width: 120,
              bFind: true,
              bNotEmpty: false, /* 设置表格必填项*号 */
            });
            const configObj = {};
            configObj.bVisible = true;
            if (key.includes('Id')) {
              configObj.bVisible = false;
            }
            configObj.bNotEmpty = true;
            configObj.showName = key;
            configObj.sName = key;
            configObj.iFitWidth = 120;
            gdsconfigformslave.push(configObj);
          }
        }
        slaveConfig.gdsconfigformslave = gdsconfigformslave;
        column = commonFunc.getHeaderConfig(slaveConfig);
      }
      this.props.onSaveState({ slaveColumnNew: column, slaveColumn: column, slaveConfig });
    }
  }
  // ----------------------------数据修改回带end  ---------------------------- //
  handleEject = () => {
    const { currentPane, panes } = this.props.app;
    if (commonUtils.isNotEmptyArr(panes) && commonUtils.isNotEmptyObject(currentPane)) {
      // const index = panes.indexOf(currentPane);
      const index = panes.findIndex(item => item.formId === currentPane.formId && item.key === currentPane.key && item.notCurrentPane === currentPane.notCurrentPane && item.route === currentPane.route && item.title === currentPane.title && item.sModelsType === currentPane.sModelsType && item.sProcName === currentPane.sProcName);
      /* 当前页签 */
      let currentTab = document.getElementById('navTabWrap').children[index];
      if (commonUtils.isEmpty(currentTab)) {
        const oChildren = document.getElementById('navTabWrap').getElementsByClassName('ant-tabs-content')[0].children;
        for (const child of oChildren) {
          if (child.nodeName === 'DIV' && index !== undefined && child.getAttribute('id') === `navTabWrap-panel-${panes[index].key}`) {
            currentTab = child;
          }
        }
      }
      // const currentTab = document.getElementById('tabs').getElementsByClassName('ant-tabs-content-no-animated')[0].children[index];
      if (!commonUtils.isEmpty(currentTab)) {
        const filterTreeArr = currentTab.getElementsByClassName('xly-filter-tree');/* 获取当前页签下的树组件 */
        if (commonUtils.isNotEmptyArr(filterTreeArr)) {
          const filterTree = filterTreeArr[0];
          if (filterTree.style.display === 'block') {
            filterTree.style.display = 'none';
          } else {
            filterTree.style.display = 'block';
          }
        }
      }
    }
  };
  /**   树节点选中   */
  handleTreeSelect = (name, checkedKeys, e) => {
    this.props.onSelect(name, checkedKeys, e); /* 调用CommonListEvent通用处理 */
  };

  handleCancelModal = (modelVisible) => {
    this.props.onSaveState({
      [modelVisible]: false,
    });
  }

  handleSelectModal = (modelVisible) => {
    this.props.onSaveState({
      [modelVisible]: false,
    });
  }


  render() {
    const { pageLoading } = this.props;
    return (
      <div style={{ height: '100%' }}>
        <Spin spinning={pageLoading}>
          <div style={{ height: '100%' }}>
            <CommonListComponent
              {...this.props}
              {...this.state}
              onEject={this.handleEject}
              onSelectTree={this.handleTreeSelect}
              onSelectModal={this.handleSelectModal}
              onCancelModal={this.handleCancelModal}
            />
          </div>
        </Spin>
      </div>
    );
  }
}

const CommonListComponent = Form.create({
  mapPropsToFields(props) {
    const { masterData } = props;
    const obj = commonFunc.mapPropsToFields(masterData, Form);
    return obj;
  },
})((props) => {
  const {
    form, onReturnForm, slavePagination, slaveConfig, slaveColumn, isSmall, iHeight, logVisible,
  } = props;
  // isSmall将分页变小，以及去掉跳转页面和总条数记录
  /*   回带表单   */
  if (commonUtils.isNotEmptyObject(slavePagination)) {
    if (isSmall) {
      slavePagination.showTotal = null;
    }
  }
  onReturnForm(form);
  const pagination = {
    pageSize: commonConfig.pageSize,
    ...slavePagination,
    size: isSmall ? 'small' : 'large',
    pageSizeOptions: commonConfig.pageSizeOptions,
    showSizeChanger: !isSmall,
    showQuickJumper: !isSmall,
  };
  const tableProps = {
    ...commonBusiness.getTableTypes('slave', props),
    tableProps: { rowKey: 'sSlaveId', pagination, onChange: props.onTitleChange },
    onSaveState: props.onSaveState,
    clearArray: props.clearArray,
    readOnly: true,
    isSmall,
    sGroupByList: props.sGroupByList,
  };
  const masterSum = commonUtils.isNotEmptyObject(slaveConfig) ? slaveConfig.gdsconfigformslave.filter(item => item.bSum && item.sName !== '') : [];
  const masterTitleGroup = commonUtils.isNotEmptyObject(slaveColumn) ? slaveColumn.filter(item => commonUtils.isNotEmptyObject(item.title) && item.title.indexOf('-') > -1) : [];
  const hasColumnGroup = masterTitleGroup.length;
  if (masterSum.length > 0) {
    NoTotalData = hasColumnGroup > 0 ? 'TitleGroup' : 'NoTitleGroup';
  } else {
    NoTotalData = hasColumnGroup > 0 ? 'NoTotalData TitleGroup' : 'NoTotalData NoTitleGroup';
  }
  // const mProps = { ...commonBusiness.createMemoProps('master', props)};

  const name = 'filterTree';
  const treeProps = {
    ...commonBusiness.getTreeTypes('tree', props),
    isSearch: false,
    checkable: false,
    disabled: false,
    checkedAll: false,
    unChecked: false,
    [`${name}Column`]: props[`${name}Column`],
    [`${name}Config`]: props[`${name}Config`],
    [`${name}Data`]: props[`${name}Data`],
    getFloatNum: props.getFloatNum,
    getSqlDropDownData: props.getSqlDropDownData,
    getSqlCondition: props.getSqlCondition,
    handleSqlDropDownNewRecord: props.handleSqlDropDownNewRecord,
    getDateFormat: props.getDateFormat,
    onDoubleClick: props.onDoubleClick,
    onSelect: props.onSelectTree,
    expandedKeys: props.expandedKeys,
  };
  const logProps = {
    app: {
      ...props.app,
      currentPane: {
        ...props.app.currentPane,
        formRoute: '/indexPage/commonList',
        route: '/indexPage/commonList',
        name: 'logView',
        config: props.logConfig,
        select: props.onSelectModal.bind(this, 'logVisible'),
        selectCancel: props.onCancelModal.bind(this, 'logVisible'),
        sModelsType: 'modal/logView',
      },
    },
    token: props.app.token,
    slaveColumn: props.logColumn, /*   表头   */
    slaveConfig: props.logConfig,
    slaveData: props.logData,
    dispatch: props.dispatch,
    content: props.content,
    id: new Date().getTime().toString(),
    pageLoading: false,
  };
  return (
    <Form style={{ height: '100%' }}>
      <Layout style={{ height: '100%' }} className="xly-list">
        {!commonUtils.isEmpty(props.routing) ? '' :
        <Header className={styles.header}>
          <Toolbar {...props} className="billBtnGroup" style={{ backgroundColor: '#646464', color: 'rgb(255,255,255)' }} />
        </Header>}
        <Layout className={styles.clayout}>
          <div className={styles.content}>
            <SearchComponent {...props} />
          </div>
          <Content style={{ height: iHeight || '100vh' }} className={`xly-normal-list ${NoTotalData}`} >
            <StaticEditTable {...tableProps} tableBelone="list" />
          </Content>
        </Layout>
      </Layout>
      {/* {!commonUtils.isEmpty(props.routing) ? '' : <SlaveMemo {...props} />} */}
      {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
      {commonUtils.isEmptyArr(treeProps.treeData) || !commonUtils.isEmpty(props.routing) ? '' : <div className="xly-eject"> <a onClick={props.onEject}> <img src={Eject} alt="eject" /></a> </div>}
      {commonUtils.isEmptyArr(treeProps.treeData) || !commonUtils.isEmpty(props.routing) ? '' :
      <div className="xly-filter-tree">
        <StaticEditTree {...treeProps} />
        <div className="xly-tree-close" >
          {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
          <a onClick={props.onEject}> <img src={Close} alt="close" /></a>
        </div>
      </div>
      }
      {
        logVisible ?
          <AntdDraggableModal
            width="1200"
            title="查看操作日志"
            visible={logVisible}
            onCancel={props.onCancelModal.bind(this, 'logVisible')}
            onOk={props.onSelectModal.bind(this, 'logVisible')}
            footer={null}
          >
            <CommonListSelect {...logProps} />
          </AntdDraggableModal> : ''
      }
    </Form>
  );
});

export default CommonBase(CommonListEvent(CommonList));
