/* eslint-disable */
/* 此组件作用是 成品工序多选产品 */

import React, { Component } from 'react';
import { Form } from '@ant-design/compatible';
// import '@ant-design/compatible/assets/index.css';
import { Layout, Spin, Button, Row, Col } from 'antd-v4';
import CommonListEvent from './CommonListEvent';/* 继承销售模块业务功能 */
// import * as commonUtils from '../../utils/utils'; /* 通用方法 */
import * as commonFunc from './commonFunc';/* 通用单据方法 */ /* 通用单据方法 */
// eslint-disable-next-line import/no-named-as-default
import StaticEditTable from './CommonTable';/* 可编辑表格 */
import StaticEditTree from '../Common/Tree/StaticTree';
import styles from '../../index.less';
import CommonBase from './CommonBase';/* 获取配置及数据 */
import * as commonBusiness from './commonBusiness';/* 单据业务功能 */
import SearchComponent from './SearchComponent';
import AntdDraggableModal from './AntdDraggableModal';
import * as commonUtils from '../../utils/utils';
import ShowType from './CommonComponent';

const { Content } = Layout;

class CommonList extends Component {
  constructor(props) {
    super(props);
    this.state = {
    };
  }
  componentWillReceiveProps(nextProps) {
    const {
      slaveData, selectedRowKeys, sModelsType, slaveFilterData, slaveSelectedData,
    } = nextProps;
    if (slaveFilterData === undefined && sModelsType === 'search/sisColor') {
      if (commonUtils.isNotEmptyArr(slaveData) && commonUtils.isNotEmptyArr(selectedRowKeys)) {
        const slaveFilterData = slaveData.filter(item => selectedRowKeys.includes(item.sSlaveId));
        if (commonUtils.isNotEmptyArr(slaveFilterData)) {
          this.props.onSaveState({
            slaveFilterData, slaveSelectedRowKeys: selectedRowKeys,
          });
        }
      }
    } else if (commonUtils.isEmptyArr(slaveFilterData) && sModelsType === 'search/commonPopup') {
      if (commonUtils.isNotEmptyArr(slaveData) && commonUtils.isNotEmptyArr(slaveSelectedData)) {
        this.props.onSaveState({
          slaveFilterData: slaveSelectedData,
        });
      }
    }
  }
  /**   确认下单   */
  handleSelect = () => {
    const {
      slaveFinalSelectedRowKeys, app, slaveSelectedData, slaveFinalData,
    } = this.props;
    let slaveFinalSelectedData = [];
    if (commonUtils.isNotEmptyArr(slaveFinalSelectedRowKeys)) {
      slaveFinalSelectedData = slaveFinalData.filter(item => slaveFinalSelectedRowKeys.includes(item.sSlaveId));
    }
    this.props.app.currentPane.select(app.currentPane.name, app.currentPane.config, slaveSelectedData, slaveFinalSelectedData);
    /* 成品没选择产品时 Modal不关闭 */
    if (commonUtils.isNotEmptyArr(slaveFinalSelectedData)) {
      this.props.app.currentPane.selectCancel(app.currentPane.name);
    }
    this.props.onSaveState({
      slaveFilterData: [],
    });
  };
  handleDoubleClickSelect = () => {
    const { slaveConfig } = this.props;
    if (commonUtils.isNotEmptyObject(slaveConfig) && !slaveConfig.bMutiSelect) { // 单选时双击选中数据
      this.handleSelect();
    }
  }
  /**   关闭   */
  handleCancelModal = () => {
    const { app } = this.props;
    this.props.app.currentPane.selectCancel(app.currentPane.name);
  };
  /**   树节点多选框选中   */
  handleTreeCheck = (checkedKeys, e) => {
    this.props.onCheck(checkedKeys, e); /* 调用CommonListEvent通用处理 */
  };
  /**   树节点选中   */
  handleTreeSelect = (name, checkedKeys, e) => {
    this.props.onSelect(name, checkedKeys, e); /* 调用CommonListEvent通用处理 */
  };
  handleTableSelectRowChange = (name, selectedRowKeys, changeValue, chooseProcessParams) => { /* 表格行选择 */
    this.props.onTableSelectRowChange(name, selectedRowKeys);
    if (name === 'slave') { /* 选择工序 从表表 */
      const { [`${name}Data`]: tableData, slaveConfig, fatherModelsType } = this.props;
      const { selectedRowKeysLength } = this.props;
      let { slaveFilterData } = this.props;
      slaveFilterData = slaveFilterData === undefined ? [] : slaveFilterData;
      const tableSelectedData = tableData.filter(item => selectedRowKeys.includes(item.sId));
      tableSelectedData.forEach((item) => {
        const iIndex = slaveFilterData.findIndex(itemFilter => itemFilter.sId === item.sId);
        if (iIndex === -1) {
          slaveFilterData.push(item);
        }
      });
      slaveFilterData = slaveFilterData.filter(item => selectedRowKeys.includes(item.sId));
      this.props.onSaveState({
        slaveFilterData,
      });
      if (chooseProcessParams) {
        let modalVisible = false;
        let slaveSelectOneData = {};
        let slaveSelectOneDataIndex = -1;
        if (commonUtils.isNotEmptyArr(tableData)) {
          if (selectedRowKeys instanceof Array) { // 多选情况下
            if (commonUtils.isEmpty(selectedRowKeysLength) || (selectedRowKeys.length - selectedRowKeysLength) > 0) {
              modalVisible = true;
            }
            slaveSelectOneDataIndex = tableData.findIndex(item => item.sId === selectedRowKeys[selectedRowKeys.length - 1]); // 多选选择最后一个
          } else { // 单选情况下
            slaveSelectOneDataIndex = tableData.findIndex(item => item.sId === selectedRowKeys);
          }
          if (slaveSelectOneDataIndex > -1) {
            slaveSelectOneData = tableData[slaveSelectOneDataIndex];
          }
        }
        // let masterData = {};
        const sProcessParamsSelects = [];
        let paramType = '';
        if (commonUtils.isNotEmptyObject(slaveSelectOneData) && commonUtils.isNotEmptyObject(fatherModelsType)) {
          if (fatherModelsType.includes('manufacture/')) {
            paramType = slaveSelectOneData.sWorkOrderParam;
          } else if (fatherModelsType.includes('quotation/')) {
            paramType = slaveSelectOneData.sProcessParam;
          }
        }
        if (commonUtils.isNotEmptyObject(paramType)) {
          // eslint-disable-next-line no-plusplus
          for (let i = 1; i < 7; i++) {
            const iIndex = slaveConfig.gdsconfigformslave.findIndex(item => item.sName === `sParamValue${i.toString()}`);
            if (iIndex > -1 && !commonUtils.isEmpty(slaveSelectOneData[`sParam${i.toString()}`])) {
              slaveConfig.gdsconfigformslave[iIndex].showName = slaveSelectOneData[`sParam${i.toString()}`];
              slaveConfig.gdsconfigformslave[iIndex].bVisible = !slaveSelectOneData[`sParam${i.toString()}`].includes('参数值');
              // masterData = { ...masterNewData, ...commonUtils.convertStrToObj(slaveFilterData[0].sProcessParam) };
              sProcessParamsSelects.push(slaveConfig.gdsconfigformslave[iIndex]);
            } else if (iIndex > -1) {
              slaveConfig.gdsconfigformslave[iIndex].bVisible = false;
            }
          }
        } else {
          modalVisible = false;
          // eslint-disable-next-line no-plusplus
          for (let i = 1; i < 7; i++) {
            const iIndex = slaveConfig.gdsconfigformslave.findIndex(item => item.sName === `sParamValue${i.toString()}`);
            if (iIndex > -1) {
              slaveConfig.gdsconfigformslave[iIndex].bVisible = false;
            }
          }
        }
        this.props.onSaveState({
          sProcessParamsModalVisible: modalVisible,
          sProcessParamsSelects,
          slaveSelectOneDataIndex,
          selectedRowKeysLength: selectedRowKeys.length,
        });
      }
    }
  }
  handleCancelProcessParamsModalVisible = () => {
    this.props.onSaveState({
      sProcessParamsModalVisible: false,
    });
  }
  handleProcessParamsOk = () => {
    const {
      slaveData, slaveSelectOneDataIndex, slaveFilterData, sProcessParamsSelects,
    } = this.props;
    let sProcessParamStr = '';
    if (commonUtils.isNotEmptyArr(slaveData) && !commonUtils.isEmpty(slaveSelectOneDataIndex) && commonUtils.isNotEmptyArr(slaveFilterData) && commonUtils.isNotEmptyArr(sProcessParamsSelects)) {
      // eslint-disable-next-line array-callback-return
      sProcessParamsSelects.map((item) => {
        sProcessParamStr += `${item.showName}:${slaveData[slaveSelectOneDataIndex][item.sName]},`;
      });
      slaveFilterData[slaveFilterData.length - 1].sProcessParamStr = sProcessParamStr;
      slaveFilterData[slaveFilterData.length - 1] = { ...slaveFilterData[slaveFilterData.length - 1], ...slaveData[slaveSelectOneDataIndex] };
    }
    this.props.onSaveState({
      slaveFilterData,
      sProcessParamsModalVisible: false,
    });
  }
  // ----------------------------数据修改回带end  ---------------------------- //
  render() {
    const { pageLoading } = this.props;
    return (
      <div style={{ height: '100%' }}>
        <Spin spinning={pageLoading}>
          <div style={{ height: '100%' }}>
            <CommonListComponent
              {...this.props}
              {...this.state}
              onSelect={this.handleSelect}
              onCancel={this.handleCancelModal}
              onDoubleClick={this.handleDoubleClickSelect}
              onCheck={this.handleTreeCheck}
              onSelectTree={this.handleTreeSelect}
              // onTableSelectRowChange={this.handleTableSelectRowChange}
              onProcessParamsOk={this.handleProcessParamsOk}
              onCancelProcessParamsModalVisible={this.handleCancelProcessParamsModalVisible}
            />
          </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,
    app,
    // masterData: masterDataNew,
    slaveData,
    sProcessParamsSelects,
    slaveSelectedRowKeys: selectedRowKeys,
    sModelsType,
  } = props;
  /*   回带表单   */
  onReturnForm(form);
  const pagination = {
    ...slavePagination,
    size: 'large',
    pageSize: 1000,
    showQuickJumper: true,
    hideOnSinglePage: true,
  };
  const tableProps = {
    ...commonBusiness.getTableTypes('slave', props),
    tableProps: {
      rowKey: 'sSlaveId', pagination, onChange: props.onTitleChange, chooseProcessParams: true, sModelsType, AutoTableHeight: 350, // chooseProcessParams为选择工序中点击工序名称表格行出现弹窗
    },
  };
  const tableFilterProps = {
    ...commonBusiness.getTableTypes('slaveFinal', props),
    rowSelectionType: 'checkbox',
    tableProps: { rowKey: 'sSlaveId', onChange: props.onTitleChange, AutoTableHeight: 350 },
  };
  const name = 'filterTree';
  const treeProps = {
    ...commonBusiness.getTreeTypes('tree', props),
    isSearch: false,
    checkable: 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,
    onCheck: props.onCheck,
    onSelect: props.onSelectTree,
    disabled: false,
    checkedAll: false,
    unChecked: false,
    defaultExpandAll: true,
    multiple: false,
    expandedKeys: props.expandedKeys,
  };
  const sProcessParams = commonFunc.showMessage(app.commonConst, 'sProcessParams');/* 选择工艺参数标题s */
  const displayLeft = (sModelsType !== 'search/sisColor' && sModelsType !== 'search/commonPopup');

  // let slaveFilterCondition = [];
  // if (props.slaveFilterCondition) {
  //   slaveFilterCondition = props.slaveFilterCondition.slice(0);
  //   slaveFilterCondition.push({ bFilterCondition: '=', bFilterName: 'sType', bFilterValue: '3' });
  // }
  return (
    <div className="modalChooseProcessContent">
      <Form >
        <Layout>
          <Layout>
            <div id="modalChooseProcess">
              <div style={{ maxHeight: '100%', zIndex: 20 }}>
                <SearchComponent {...props} />
              </div>
              <Content
                className="xly-normal-list"
                style={{ paddingLeft: '10px' }}
              >
                <Row gutter={[8, 0]}>
                  {displayLeft ?
                    <Col span={4}>
                      <div className="xly-tree-box">
                        <div className="xly-tree-title">过滤项</div>
                        <StaticEditTree {...treeProps} />
                      </div>
                    </Col> : ''
                  }
                  <Col span={sModelsType === 'search/commonPopup' ? 15 : 5}>
                    <StaticEditTable {...tableProps} footer="hidden" tableBelone="list" showConfig={props.showConfig} />
                  </Col>
                  <Col span={displayLeft ? 15 : sModelsType === 'search/commonPopup' ? 9 : 19} >
                    <StaticEditTable {...tableFilterProps} footer="hidden" tableBelone="list" showConfig={props.showConfig} />
                  </Col>
                </Row>
              </Content>
            </div>
          </Layout>
          <div style={{ textAlign: 'right', marginRight: '9px', marginBottom: '9px' }}>
            <Button key="back" style={{ marginRight: '8px' }} onClick={props.onCancel}>取消</Button>
            <Button type="primary" onClick={props.onSelect}>确认</Button>
          </div>
        </Layout>
        {
          props.sProcessParamsModalVisible ?
            <AntdDraggableModal
              width="33%"
              title={sProcessParams}
              visible={props.sProcessParamsModalVisible}
              onOk={props.onProcessParamsOk}
              onCancel={props.onCancelProcessParamsModalVisible}
              // footer={null}
            >
              <div className="sProcessParamsModal" style={{ height: '80%', overflowY: 'auto' }}>
                { commonUtils.isNotEmptyArr(sProcessParamsSelects) && commonUtils.isNotEmptyArr(selectedRowKeys) ?
                  sProcessParamsSelects.map((child) => {
                    const sMemo = child.sName.toLowerCase().endsWith('memo');
                    let enabledNew = !child.bReadonly;
                    if (child.iTag === 1) {
                      enabledNew = false;
                    } else if (child.iTag === 3) {
                      enabledNew = true;
                    }
                    const slaveSelectOneDataIndex = slaveData.findIndex(item => item.sId === selectedRowKeys[selectedRowKeys.length - 1]); // 多选选择最后一个
                    const showTypeProps = {
                      name: 'slave',
                      form: props.form,
                      record: slaveData[slaveSelectOneDataIndex],
                      sId: slaveData[slaveSelectOneDataIndex].sId,
                      getSqlDropDownData: props.getSqlDropDownData,
                      getSqlCondition: props.getSqlCondition,
                      handleSqlDropDownNewRecord: props.handleSqlDropDownNewRecord,
                      getFloatNum: props.getFloatNum,
                      onChange: props.onDataChange,
                      showConfig: child,
                      formItemLayout: {},
                      textArea: sMemo,
                      enabled: enabledNew,
                      dataValue: slaveData[slaveSelectOneDataIndex][child.sName],
                      bTable: true,
                      formRoute: props.formRoute,
                    };
                    return (
                      <div className="sProcessParamsModalType">
                        <span>{`${child.showName}:`}</span>
                        <ShowType {...showTypeProps} />
                      </div>
                    );
                  }) : ''
                }
              </div>
            </AntdDraggableModal>
            : ''
        }
      </Form>
    </div>
  );
});

export default CommonBase(CommonListEvent(CommonList));
