/**
 * @Date:   2019-05-28T13:23:00+08:00
 * @Last modified time: 2019-05-29T15:33:03+08:00
 */
/**
 * Created by mar105 on 2019-03-27.
 */
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';/* 通用方法 */

const { Header } = Layout;

class MaterialRequirementsPlanning 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.sMaterialsId === record.sMaterialsId && item.sMaterialsStyle === record.sMaterialsStyle);
        // if (commonUtils.isNotEmptyArr(slaveInfoDataNew)) {
        //   slaveInfoDataNew.forEach((item) => {
        //     item.dAuxiliaryQty = item.dAuxiliaryQtyAll - item.dPurchaseAuxiliaryQty;
        //   });
        // }
      }
      return slaveInfoDataNew;
    }
  };
  /**   处理选择行发生改变   */
  handleTableSelectRowChange = (name, selectedRowKeys) => {
    /*   外置处理业务   */
    const {
      formRoute, slaveSelectedRowKeys, slaveInfoSelectedRowKeys, slaveInfoData, slaveData: slaveList,
    } = this.props;
    const {
      slaveSelectedData, slaveInfoSelectedData,
    } = this.props;

    const addState = {};
    addState[`${name}SelectedRowKeys`] = selectedRowKeys;
    addState.searchUpDownData = {};
    let newSlaveSelectedData = [];
    let newSlaveInfoSelectedData = [];
    let newSelectedRowKeys = [];
    const addSelectedRowKeys = [];

    if (formRoute === '/indexPage/materialRequirementsPlanning') {
      if (name === 'slave') {
        if (selectedRowKeys.length === 0) {
          // 主表 取消 ，数量取初始
          slaveList.forEach((omsRowkey, iIndexSlave) => {
            slaveList[iIndexSlave].dAuxiliaryQty = omsRowkey.dAuxiliaryQtyAll;
            slaveList[iIndexSlave].dMaterialsQty = omsRowkey.dMaterialsQtyAll;
          });
          addState.slaveData = slaveList;
          addState.slaveSelectedRowKeys = selectedRowKeys;
          addState.slaveSelectedData = [];
          addState.slaveInfoSelectedRowKeys = [];
          addState.slaveInfoSelectedData = [];
        } else {
          const oldMoreSelectRowkeys = slaveSelectedRowKeys.filter(item => !selectedRowKeys.includes(item)); // 历史数据中删除的数据
          if (commonUtils.isNotEmptyArr(oldMoreSelectRowkeys) && oldMoreSelectRowkeys.length === 1) {
            // 主表 取消 ，数量取初始
            const iIndexSlave = slaveList.findIndex(itemSlave => itemSlave.sMaterialsGS === oldMoreSelectRowkeys[0]);
            slaveList[iIndexSlave].dAuxiliaryQty = slaveList[iIndexSlave].dAuxiliaryQtyAll;
            slaveList[iIndexSlave].dMaterialsQty = slaveList[iIndexSlave].dMaterialsQtyAll;

            // 根据选择的key 确定主表选择的数据
            newSlaveSelectedData = slaveSelectedData.filter(item => selectedRowKeys.includes(item.sMaterialsGS));

            // 从表数据也根据 上一次选择的主表key 过滤移除要取消的key 获取新数据（SlaveInfoSelectedData, SelectedRowKeys)   在上次操作的数上进行筛选
            newSlaveInfoSelectedData = slaveInfoSelectedData.filter(item => selectedRowKeys.includes(item.sMaterialsGS));
            newSlaveInfoSelectedData.forEach((item) => {
              newSelectedRowKeys.push(item.sWorkMaterialsId);
            });
            addState.slaveData = slaveList;
            addState.slaveSelectedRowKeys = selectedRowKeys;
            addState.slaveSelectedData = newSlaveSelectedData;
            addState.slaveInfoSelectedRowKeys = newSelectedRowKeys;
            addState.slaveInfoSelectedData = newSlaveInfoSelectedData;
          } else {
            // 新增选择
            const newMoreSelectRowkeys = selectedRowKeys.filter(item => !slaveSelectedRowKeys.includes(item));
            if (commonUtils.isNotEmptyArr(newMoreSelectRowkeys) && newMoreSelectRowkeys.length === 1) {
              const iIndexSlave = slaveList.findIndex(itemSlave => itemSlave.sMaterialsGS === newMoreSelectRowkeys[0]);
              slaveList[iIndexSlave].dAuxiliaryQty = slaveList[iIndexSlave].dAuxiliaryQtyAll;
              slaveList[iIndexSlave].dMaterialsQty = slaveList[iIndexSlave].dMaterialsQtyAll;

              const addSlaveSelectedData = slaveList.filter(item => newMoreSelectRowkeys[0] === item.sMaterialsGS);
              newSlaveSelectedData = addSlaveSelectedData.concat(slaveSelectedData);

              const addSlaveInfoSelectedData = slaveInfoData.filter(item => newMoreSelectRowkeys[0] === item.sMaterialsGS);
              newSlaveInfoSelectedData = addSlaveInfoSelectedData.concat(slaveInfoSelectedData);

              addSlaveInfoSelectedData.forEach((item) => {
                addSelectedRowKeys.push(item.sWorkMaterialsId);
              });
              newSelectedRowKeys = slaveInfoSelectedRowKeys.concat(addSelectedRowKeys);
              addState.slaveData = slaveList;
              addState.slaveSelectedRowKeys = selectedRowKeys;
              addState.slaveSelectedData = newSlaveSelectedData;
              addState.slaveInfoSelectedRowKeys = newSelectedRowKeys;
              addState.slaveInfoSelectedData = newSlaveInfoSelectedData;
            } else if (commonUtils.isNotEmptyArr(newMoreSelectRowkeys) && newMoreSelectRowkeys.length > 1) {
              const addSlaveSelectedData = slaveList.filter(item => selectedRowKeys.includes(item.sMaterialsGS));
              // 主表 取消 ，数量取初始
              addSlaveSelectedData.forEach((omsRowkey) => {
                const iIndexSlave = slaveList.findIndex(itemSlave => itemSlave.sMaterialsGS === omsRowkey.sMaterialsGS);
                if (iIndexSlave > -1) {
                  slaveList[iIndexSlave].dAuxiliaryQty = slaveList[iIndexSlave].dAuxiliaryQtyAll;
                  slaveList[iIndexSlave].dMaterialsQty = slaveList[iIndexSlave].dMaterialsQtyAll;
                }
              });
              const addSlaveInfoSelectedData = slaveInfoData.filter(item => selectedRowKeys.includes(item.sMaterialsGS));
              const newSelectedRowKeys = [];
              slaveInfoData.forEach((item) => {
                newSelectedRowKeys.push(item.sWorkMaterialsId);
              });
              addState.slaveData = slaveList;
              addState.slaveSelectedRowKeys = selectedRowKeys;
              addState.slaveSelectedData = addSlaveSelectedData;
              addState.slaveInfoSelectedRowKeys = newSelectedRowKeys;
              addState.slaveInfoSelectedData = addSlaveInfoSelectedData;
            }
          }
        }
        this.props.onSaveState({ ...addState });
      } else if (name === 'slaveInfo') {
        if (selectedRowKeys.length === 0) {
          slaveList.forEach((omsRowkey, iIndexSlave) => {
            slaveList[iIndexSlave].dAuxiliaryQty = slaveList[iIndexSlave].dAuxiliaryQtyAll;
            slaveList[iIndexSlave].dMaterialsQty = slaveList[iIndexSlave].dMaterialsQtyAll;
          });
          addState.slaveData = slaveList;
          addState.slaveSelectedRowKeys = [];
          addState.slaveSelectedData = [];
          addState.slaveInfoSelectedRowKeys = [];
          addState.slaveInfoSelectedData = [];
        } else {
          newSlaveInfoSelectedData = slaveInfoData.filter(item => selectedRowKeys.includes(item.sWorkMaterialsId));
          newSlaveSelectedData = slaveList.filter(item => newSlaveInfoSelectedData.findIndex(newItem => newItem.sMaterialsGS === item.sMaterialsGS) > -1);
          newSlaveSelectedData.forEach((item) => {
            newSelectedRowKeys.push(item.sMaterialsGS);
            const newlist = newSlaveInfoSelectedData.filter(siItem => siItem.sMaterialsGS === item.sMaterialsGS);
            let dAuxiliaryQty = 0;
            let dMaterialsQty = 0;
            newlist.forEach((item) => {
              dAuxiliaryQty = commonUtils.convertFixNum(item.dAuxiliaryQty + dAuxiliaryQty, 6);
              dMaterialsQty = commonUtils.convertFixNum(item.dMaterialsQty + dMaterialsQty, 6);
            });
            const iIndex = slaveList.findIndex(itemSlave => itemSlave.sMaterialsGS === item.sMaterialsGS);
            slaveList[iIndex].dAuxiliaryQty = dAuxiliaryQty;
            slaveList[iIndex].dMaterialsQty = dMaterialsQty;
          });
          addState.slaveData = slaveList;
          addState.slaveSelectedRowKeys = newSelectedRowKeys;
          addState.slaveSelectedData = newSlaveSelectedData;
          addState.slaveInfoSelectedRowKeys = selectedRowKeys;
          addState.slaveInfoSelectedData = newSlaveInfoSelectedData;
        }
      }
      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%' }}>
            <MaterialRequirementsPlanningComponent
              {...this.props}
              {...this.state}
              onTableFilterData={this.handleTableFilterData}
              onTableSelectRowChange={this.handleTableSelectRowChange}
            />
          </div>
        </Spin>
      </div>
    );
  }
}

const MaterialRequirementsPlanningComponent = Form.create({
  mapPropsToFields(props) {
    const { masterData } = props;
    const obj = commonFunc.mapPropsToFields(masterData, Form);
    return obj;
  },
})((props) => {
  const { form, onReturnForm, slavePagination } = 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: 'sMaterialsGS', pagination, onChange: props.onTitleChange },
  };
  const tableInfoProps = {
    ...commonBusiness.getTableTypes('slaveInfo', props),
    tableProps: { rowKey: 'sWorkMaterialsId', pagination, onChange: props.onTitleChange },
    tableBelone: 'list',
    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} setSearchSlaveInfo="Y" />
          </div>
          <div
            style={{ marginTop: 5 }}
            className="xly-normal-list materialRequirementPlane"
          >
            <StaticEditTable {...tableProps} footer="hidden" slaveInfo={tableInfoProps} setExpandedRowRender="Y" />
          </div>
        </Layout>
      </Layout>
    </Form>
  );
});

export default CommonBase(CommonListEvent(MaterialRequirementsPlanning));
