/**
 * @Date:   2019-05-28T13:23:00+08:00
 * @Last modified time: 2019-05-29T15:33:03+08:00
 */
/**
 * 此组件是两层通用结构commonListTree,功能如物料需求计划，两层都可以配制独立的数据源
 */
/* eslint-disable */
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 CommonListTreeEvent from '../CommonListTreeEvent';/* 继承销售模块业务功能 */
import * as commonFunc from '../commonFunc';/* 通用单据方法 */ /* 通用单据方法 */
import Toolbar from '../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'; /* 通用方法 */

const { Header } = Layout;

class CommonListTree extends Component {
  constructor(props) {
    super(props);
    this.state = {
    };
  }

  // ----------------------------数据修改回带end  ---------------------------- //
  /**   处理选择行发生改变   */
  handleTableFilterData= (name, data, record) => {
    /*   外置处理业务   */
    if (name === 'slave') {
      let slaveInfoDataNew = [];
      if (commonUtils.isNotEmptyArr(data)) {
        slaveInfoDataNew = data.filter(item => item.sSqlConditionId === record.sSqlConditionId);
      }
      return slaveInfoDataNew;
    }
  };
  /**   处理选择行发生改变   */
  handleTableSelectRowChange = (name, selectedRowKeys) => {
    /*   外置处理业务   */
    const {
      sModelsType,slaveInfoData, slaveData,    slaveSelectedData, slaveInfoSelectedData,
    } = this.props;
    let { slaveInfoSelectedRowKeys, slaveSelectedRowKeys } = this.props;
    const addState = {};
    addState[`${name}SelectedRowKeys`] = selectedRowKeys;
    let newSlaveSelectedData = [];
    const newSlaveInfoSelectedData = [];
    const newSelectedRowKeys = [];
    const addSelectedRowKeys = [];
    if(commonUtils.isEmptyArr(slaveInfoSelectedRowKeys)) {
      slaveInfoSelectedRowKeys =[];
    }
    /* 如果列表是需要主从表联动 */
    if (sModelsType && sModelsType.includes('linkTree')) {
      if (name === 'slave') {
        if (selectedRowKeys.length === 0) {
          if(commonUtils.isNotEmptyArr(slaveData)) {
            slaveData.forEach((omsRowkey, iIndexSlave) => {
              slaveData[iIndexSlave].dAuxiliaryQty = slaveData[iIndexSlave].dAuxiliaryQtyAll;
              slaveData[iIndexSlave].dMaterialsQty = slaveData[iIndexSlave].dMaterialsQtyAll;
            });
          }
          addState.slaveData = slaveData;
          addState.slaveSelectedRowKeys = [];
          addState.slaveSelectedData = [];
          addState.slaveInfoSelectedRowKeys = [];
          addState.slaveInfoSelectedData = [];
        } else{
          /* 找到勾选掉的Id */
          let oldSelectRowkeys = []; /* 取消勾选行 */
          if(commonUtils.isNotEmptyArr(slaveSelectedRowKeys)) {
            oldSelectRowkeys = slaveSelectedRowKeys.filter(item => !selectedRowKeys.includes(item)); // 找到取消的那个行 */
            if(commonUtils.isNotEmptyArr(oldSelectRowkeys) ) { /* 单层表格时 */
              oldSelectRowkeys.forEach((oldSelectRowkey) => {
                let slaveRow = {};
                /* 找到从表对应的所有子从表 */
                const iIndex = slaveData.findIndex(item => oldSelectRowkey.includes(item.sSlaveId));
                if (iIndex > -1) {
                  slaveRow = slaveData[iIndex];
                }
                if(commonUtils.isNotEmptyObject(oldSelectRowkey)) { /* 找到勾选掉的sDivRow汇总行 */
                  const slaveRemoveData = slaveInfoData.filter(item => item.sSqlConditionId === slaveRow.sSqlConditionId);
                  if(commonUtils.isNotEmptyArr(slaveRemoveData) && commonUtils.isNotEmptyArr(slaveInfoSelectedRowKeys)) {
                    let dAuxiliaryQtySum = slaveRow.dAuxiliaryQty;
                    let dMaterialsQtySum = slaveRow.dMaterialsQty;
                    slaveRemoveData.forEach((itemInfo) => {
                      const indexKey = slaveInfoSelectedRowKeys.indexOf(itemInfo.sSlaveId);
                      if(indexKey > -1) {
                        slaveInfoSelectedRowKeys.splice(indexKey, 1);
                        dAuxiliaryQtySum -= itemInfo.dAuxiliaryQty;
                        dMaterialsQtySum -= itemInfo.dMaterialsQty;
                      }
                    });
                    if(dAuxiliaryQtySum ===0) {
                      dAuxiliaryQtySum= slaveRow.dAuxiliaryQtyAll;
                    }
                    if(dMaterialsQtySum ===0) {
                      dMaterialsQtySum= slaveRow.dMaterialsQtyAll;
                    }
                    slaveRow.dAuxiliaryQty = dAuxiliaryQtySum;
                    slaveRow.dMaterialsQty = dMaterialsQtySum;
                    slaveData[iIndex] = {...slaveData[iIndex], ...slaveRow};
                    addState.slaveInfoSelectedRowKeys = slaveInfoSelectedRowKeys;
                    addState.slaveData = slaveData;
                  }
                }
              });
            }
          }
          if(commonUtils.isNotEmptyArr(selectedRowKeys)) {  /* 从表行新增勾选 */
            selectedRowKeys.forEach((selectedRowKey) => {
              let slaveRow = {};
              /* 找到从表对应的所有子从表 */
              const iIndex = slaveData.findIndex(item => selectedRowKey.includes(item.sSlaveId));
              if (iIndex > -1) {
                slaveRow = slaveData[iIndex];
              }
              if (commonUtils.isNotEmptyObject(slaveRow) && commonUtils.isNotEmptyArr(slaveInfoData)) {
                let dAuxiliaryQtySum = 0;
                let dMaterialsQtySum = 0;
                const slaveInfoFilterData = slaveInfoData.filter(item => item.sSqlConditionId === slaveRow.sSqlConditionId);
                if (commonUtils.isNotEmptyArr(slaveInfoFilterData)) {
                  slaveInfoFilterData.forEach((itemInfo) => {
                    if(slaveInfoSelectedRowKeys.indexOf(itemInfo.sSlaveId) === -1) {
                      slaveInfoSelectedRowKeys.push(itemInfo.sSlaveId);
                    }
                    dAuxiliaryQtySum += itemInfo.dAuxiliaryQty;
                    dMaterialsQtySum += itemInfo.dMaterialsQty;
                  });
                  slaveRow.dAuxiliaryQty = dAuxiliaryQtySum;
                  slaveRow.dMaterialsQty = dMaterialsQtySum;
                  slaveData[iIndex] = {...slaveData[iIndex], ...slaveRow};
                }
              }
            });
            newSlaveSelectedData = slaveData.filter(item => selectedRowKeys.includes(item.sSlaveId)); /* 从表的所有选中行 */
            addState.slaveSelectedData = newSlaveSelectedData;
            addState.slaveData = slaveData;
            addState.slaveInfoSelectedRowKeys = slaveInfoSelectedRowKeys;
          }
        }
        this.props.onSaveState({ ...addState });
      } else if (name === 'slaveInfo') {
        /* 勾选行 */
        if (selectedRowKeys.length === 0) {
          if(commonUtils.isNotEmptyArr(slaveData)) {
            slaveData.forEach((omsRowkey, iIndexSlave) => {
              slaveData[iIndexSlave].dAuxiliaryQty = slaveData[iIndexSlave].dAuxiliaryQtyAll;
              slaveData[iIndexSlave].dMaterialsQty = slaveData[iIndexSlave].dMaterialsQtyAll;
            });
          }
          addState.slaveData = slaveData;
          addState.slaveSelectedRowKeys = [];
          addState.slaveSelectedData = [];
          addState.slaveInfoSelectedRowKeys = [];
          addState.slaveInfoSelectedData = [];
        } else {
          const newSlaveInfoSelectedData = slaveInfoData.filter(item => selectedRowKeys.includes(item.sSlaveId));
          if(commonUtils.isNotEmptyArr(newSlaveInfoSelectedData)) {
            const newSlaveSelectedData = slaveData.filter(item => newSlaveInfoSelectedData.findIndex(newItem => newItem.sSqlConditionId === item.sSqlConditionId) > -1);
            newSlaveSelectedData.forEach((item) => {
              newSelectedRowKeys.push(item.sSlaveId);
              const newlist = newSlaveInfoSelectedData.filter(siItem => siItem.sSqlConditionId === item.sSqlConditionId); /* 找到该子表行对应的从表 所对应的所有子从表 */
              let dAuxiliaryQty = 0;
              let dMaterialsQty = 0;
              if(commonUtils.isNotEmptyArr(newlist)) {
                newlist.forEach((item) => {
                  dAuxiliaryQty = commonUtils.convertFixNum(item.dAuxiliaryQty + dAuxiliaryQty, 6);
                  dMaterialsQty = commonUtils.convertFixNum(item.dMaterialsQty + dMaterialsQty, 6);
                });
              }
              const iIndex = slaveData.findIndex(itemSlave => itemSlave.sSlaveId === item.sSlaveId);
              if(iIndex > -1) {
                slaveData[iIndex].dAuxiliaryQty = dAuxiliaryQty;
                slaveData[iIndex].dMaterialsQty = dMaterialsQty;
              }
            });
            addState.slaveData = slaveData;
            addState.slaveSelectedData= newSlaveSelectedData;
            addState.slaveSelectedRowKeys = newSelectedRowKeys;
            addState.slaveInfoSelectedRowKeys = selectedRowKeys;
          }
        }
      }
      this.props.onSaveState({ ...addState });
    } else {
      this.props.onTableSelectRowChange(name, selectedRowKeys);
    }
  };

  render() {
    const { pageLoading } = this.props;
    return (
      <div style={{ height: '100%' }}>
        <Spin spinning={pageLoading}>
          <div style={{ height: '100%' }}>
            <CommonListTreeComponent
              {...this.props}
              {...this.state}
              onTableFilterData={this.handleTableFilterData}
              onTableSelectRowChange={this.handleTableSelectRowChange}
            />
          </div>
        </Spin>
      </div>
    );
  }
}

const CommonListTreeComponent = Form.create({
  mapPropsToFields(props) {
    const { masterData } = props;
    const obj = commonFunc.mapPropsToFields(masterData, Form);
    return obj;
  },
})((props) => {
  const { form, onReturnForm, slavePagination, defaultExpandAllRows } = props;
  /*   回带表单   */
  onReturnForm(form);
  const pagination = {
    pageSize: commonConfig.pageSize,
    ...slavePagination,
    size: 'large',
    pageSizeOptions: commonConfig.pageSizeOptions,
    showSizeChanger: true,
    showQuickJumper: true,
  };
  const tableProps = {
    ...commonBusiness.getTableTypes('slave', props),
    onTableFilterData: props.onTableFilterData,
    tableBelone: 'list',
    tableProps: { rowKey: 'sSlaveId', pagination, onChange: props.onTitleChange },
  };
  const tableInfoProps = {
    ...commonBusiness.getTableTypes('slaveInfo', props),
    tableProps: { rowKey: 'sSlaveId', pagination, onChange: props.onTitleChange },
    // tableBelone: 'list',
    onChange: props.onTitleChange.bind(this, 'slaveInfo'),
    enabled:true,
    bRowClick: true
    // data: commonUtils.isNotEmptyObject(props.slaveInfoDataNew) ? props.slaveInfoDataNew : props.slaveInfoData,
  };
  // const mProps = { ...commonBusiness.createMemoProps('master', props) };
  return (
    <Form style={{ height: '100%' }}>
      <Layout style={{ height: '100%' }} className="xly-list">
        <Header className={styles.header}>
          <Toolbar {...props} className="billBtnGroup" style={{ backgroundColor: '#646464', color: 'rgb(255,255,255)' }} />
        </Header>
        <Layout className={styles.clayout}>
          <div className={styles.filterContent}>
            <SearchComponent {...props} />
          </div>
          <div
            style={{ marginTop: 5 }}
            className="xly-normal-list materialRequirementPlane"
          >
            <StaticEditTable {...tableProps} slaveInfo={tableInfoProps} setExpandedRowRender="Y" defaultExpandAllRows={!!defaultExpandAllRows} />
          </div>
        </Layout>
      </Layout>
    </Form>
  );
});

export default CommonBase(CommonListTreeEvent(CommonListTree));
