/* eslint-disable */
/* eslint-disable object-curly-newline,prefer-destructuring */
import React, { Component } from 'react';
// import '@ant-design/compatible/assets/index.css';
import { Row, Col, Divider, Tooltip } from 'antd-v4';
import ShowType from '@/components/Common/CommonComponent';
import AntdDraggableModal from '@/components/Common/AntdDraggableModal';
import CommonListSelectTree from '@/components/Common/CommonListSelectTree';
import CommonListSelect from '@/components/Common/CommonListSelect';
import * as commonUtils from '@/utils/utils';/* 通用方法 */


export default class CommonViewTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      openNewTabFlag: false,
      commonFieldPopupVisible: false,
      commonFieldPopupTbName: 'name',
      commonFieldPopupShowConfig: {},
      randomId: commonUtils.createSid(),
    };
  }

  componentWillReceiveProps() {
    if (this.state.openNewTabFlag) {
      const dom = document.getElementsByClassName(`${this.state.randomId}-CommonListSelectTree`)[0];
      dom.parentElement.parentElement.style.display = 'block';
      this.setState({
        openNewTabFlag: false,
      });
    }
  }

  // shouldComponentUpdate(nextProps) {
  //   const { masterData, expandView, enabled } = this.props;
  //   return masterData !== nextProps.masterData || expandView !== nextProps.expandView || enabled !== nextProps.enabled;
  // }
  onOpenNewTab = () => {
    const dom = document.getElementsByClassName(`${this.state.randomId}-CommonListSelectTree`)[0];
    dom.parentElement.parentElement.style.display = 'none';
    this.setState({
      openNewTabFlag: true,
    });
  };
  handleToggle = () => {
    const { expandView } = this.props;
    this.props.onSaveState({ expandView: !expandView });
  };
  handleViewClick = (name, sName, sId) => {
    this.props.onViewClick(name, sName, sId);
  };
  /* 字段弹窗 */
  handleFieldPopupModal= (showConfig, name, type) => {
    if (type) {
      this.setState({
        commonFieldPopupVisible: true,
        commonFieldPopupType: type,
        commonFieldPopupTbName: name,
        commonFieldPopupShowConfig: showConfig,
      });
    } else {
      this.setState({
        commonFieldPopupVisible: true,
        commonFieldPopupTbName: name,
        commonFieldPopupShowConfig: showConfig,
      });
    }
  }
  handleSelectCommonFieldPopup = (name, selectConfig, selectData) => {
    const { commonFieldPopupTbName, commonFieldPopupShowConfig } = this.state;
    if (selectConfig.sControlName && selectConfig.sControlName.includes('sumeQty')) { /* 数据汇总求和 */
      this.props.onSelectCommonPopupSum(name, selectConfig, selectData, commonFieldPopupTbName, commonFieldPopupShowConfig);
    } else {
      this.props.onSelectCommonPopup(name, selectConfig, selectData, commonFieldPopupTbName, commonFieldPopupShowConfig);
    }
  };
  handleSelectCancel = (modelVisible) => {
    this.setState({
      [modelVisible]: false,
    });
  };

  render() {
    // eslint-disable-next-line no-unused-vars
    const { iColValueView, viewRow = {}, app, tableConfigType, viewConfigs, tableConfig, tableName, slaveName, enabled, viewOrder } = this.props;
    const { commonFieldPopupVisible, randomId, commonFieldPopupShowConfig, commonFieldPopupType } = this.state;
    // eslint-disable-next-line no-unused-vars
    let masterShowConfig = [];
    if (tableConfigType) {
      masterShowConfig = commonUtils.isNotEmptyObject(tableConfig) ? tableConfig.gdsconfigformslave.filter(item => item.bVisible && item.sName !== '' && item.sControlName.split('_')[1] === tableConfigType) : [];
    } else {
      masterShowConfig = commonUtils.isNotEmptyObject(tableConfig) ? tableConfig.gdsconfigformslave.filter(item => item.bVisible && item.sName !== '' && (item.sControlName?.indexOf('_') === -1)) : [];
    }
    const formItemLayout = { labelCol: { span: 7, style: { color: 'rgba(0, 0, 0, 0.65)', backgroundColor: '#BFEFFF' } }, wrapperCol: { span: 17 } };

    /* 字段弹窗功能 */
    let commonFieldPopupProps = {};
    let commonFieldPopupTitle = '选择弹窗';
    if (commonFieldPopupType === 'CommonListSelect') {
      const { sModelsId } = this.props;
      const commonFieldPopupConfig = commonFieldPopupShowConfig;
      commonFieldPopupTitle = commonFieldPopupConfig.sActiveName || '详情';
      const bPassRate = commonFieldPopupShowConfig.sControlName && ( commonFieldPopupShowConfig.sControlName.includes('dReviewPassRate')
       || commonFieldPopupShowConfig.sControlName.includes('dFeedingPassRate') ); /* 合格率评审数据取过滤后的工序表 */
      let slaveData = [];
      if (bPassRate) {
        const { currentProductTechnologyVer, currentProductCardId, slave0Child1Data, slave0Child1SelectedRowKeys, slave0Data } = this.props;
        const iSIndex = commonUtils.isNotEmptyArr(slave0Child1Data) ?  slave0Child1Data.findIndex(item => slave0Child1SelectedRowKeys.includes(item.sId)) : -1;
        let controlRow ={};
        if(iSIndex > -1 ){
          controlRow = slave0Child1Data[iSIndex];
        } else if(commonUtils.isNotEmptyArr(slave0Child1Data)) {
          const controlFilterData = slave0Child1Data.filter(item=> item.sProductCardId === currentProductCardId && item.sProductTechnologyVer === currentProductTechnologyVer );
          if(commonUtils.isNotEmptyArr(controlFilterData) && controlFilterData.length ===1 ) {
            controlRow = controlFilterData[0];
          }

        }
        const filterData = slave0Data.filter(item=> item.sControlId === controlRow.sId);
        if(commonUtils.isNotEmptyArr(filterData)) {
          filterData.forEach((item,index ) => {
            const newSlaveId = commonUtils.createSid();
            filterData[index] ={...filterData[index], sSlaveId :newSlaveId};
          });
        }
        slaveData = filterData;
      }

      commonFieldPopupProps = {
        app: {
          ...this.props.app,
          currentPane: {
            name: 'commonPopup',
            config: commonFieldPopupConfig,
            conditonValues: this.props.getSqlCondition(commonFieldPopupConfig),
            title: commonFieldPopupTitle,
            route: '/indexPage/commonList',
            formRoute: '/indexPage/commonList',
            formId: commonFieldPopupConfig.sActiveId,
            key: sModelsId + commonFieldPopupConfig.sId,
            sModelsType: bPassRate ? 'search/commonPopupPassRate' : 'search/commonPopup',
            select: this.handleSelectCommonFieldPopup,
            // select: () => {},
            selectCancel: this.handleSelectCancel.bind(this, 'commonFieldPopupVisible'),
          },
          bEdit: this.props.enabled,
        },
        dispatch: this.props.dispatch,
        content: this.props.content,
        id: randomId,
        onOpenNewTab: this.onOpenNewTab,
        outerMasterData: this.props.masterData,
        realizeHeight: this.props.realizeHeight, /* 拖动偏移高度 */
        readOnly: !enabled || commonFieldPopupConfig.bReadOnly,
        noChangeDiffMap: true,
      };
      if (bPassRate) {
        commonFieldPopupProps.data = JSON.parse(JSON.stringify(slaveData));
      }
      if(commonFieldPopupConfig.sControlName && (
        commonFieldPopupConfig.sControlName.includes('BtnPopup.dStockUpConsumeQty') ||
        commonFieldPopupConfig.sControlName.includes('BtnPopup.dMergeProductionQty') ||
        commonFieldPopupConfig.sControlName.includes('BtnPopup.dWorkPeriodQty') ||
        commonFieldPopupConfig.sControlName.includes('BtnPopup.dSplitworkQty') ||
        commonFieldPopupConfig.sControlName.includes('BtnPopup.dCombinedQty') ||
        commonFieldPopupConfig.sControlName.includes('BtnPopup.dPreMatProductQty')
      )) {
        const { slaveData, slaveSelectedRowKeys, sModelsId } = this.props;
        commonFieldPopupProps.app.currentPane.bEdit = this.props.enabled;
        if( commonFieldPopupConfig.sControlName.includes('BtnPopup.dCombinedQty')) {
          /* 工艺评审界面已经选了合版订单，拆分工单界面合版订单的数量不应该能再修改   补印工艺评审 */
          commonFieldPopupProps.app.currentPane.bEdit = this.props.enabled && (sModelsId === '12710101117054908553170' || sModelsId === '12710101117183304335380');
          commonFieldPopupProps.readOnly = !commonFieldPopupProps.app.currentPane.bEdit;
        }

        if( commonFieldPopupConfig.sControlName.includes('BtnPopup.dMergeProductionQty') || commonFieldPopupConfig.sControlName.includes('BtnPopup.dSplitworkQty')
        || commonFieldPopupConfig.sControlName.includes('BtnPopup.dWorkPeriodQty') ) { /* 合并订单/拆分工单/在制品数量 */
          /* 拆分工单 */
          commonFieldPopupProps.app.currentPane.bEdit = this.props.enabled && sModelsId === '12710101117055453458840';
          commonFieldPopupProps.readOnly = !commonFieldPopupProps.app.currentPane.bEdit;
        }

        if( commonFieldPopupConfig.sControlName.includes('BtnPopup.dPreMatProductQty')) {
          /* 销售订单 */
          commonFieldPopupProps.app.currentPane.bEdit = this.props.enabled && sModelsId === '101251240115016086186007360';
          commonFieldPopupProps.readOnly = !commonFieldPopupProps.app.currentPane.bEdit;
        }

        let slaveDataSource = [];
        if (commonUtils.isNotEmptyArr(slaveSelectedRowKeys)) {
          const iIndex = slaveData.findIndex(item => item.sId === slaveSelectedRowKeys[0]);
          if (iIndex > -1) {
            slaveDataSource = [slaveData[iIndex]];
          } else if (commonUtils.isNotEmptyArr(slaveData)) {
            slaveDataSource = [slaveData[0]];
          }
        } else if (commonUtils.isNotEmptyArr(slaveData)) {
          slaveDataSource = [slaveData[0]];
        }

        /* 将备货消耗数据JSON 回传到弹窗，并完成勾选 */
        commonFieldPopupProps.app.currentPane.slaveDataSource = slaveDataSource; /* 父组件的从表数据集 */

      }
      // else if(commonFieldPopupConfig.sControlName && commonFieldPopupConfig.sControlName.includes('BtnPopup.dMergeProductionQty')) {
      //   const { slaveData : slaveDataSource } = this.props;
      //   commonFieldPopupProps.app.currentPane.bEdit = this.props.enabled;
      //   /* 将合并生产数据JSON 回传到弹窗，并完成勾选 */
      //   commonFieldPopupProps.app.currentPane.slaveDataSource = slaveDataSource; /* 父组件的从表数据集 */
      //
      // } else if(commonFieldPopupConfig.sControlName && commonFieldPopupConfig.sControlName.includes('BtnPopup.dSplitworkQty')) { /* 拆分工单数量 */
      //   const { slaveData : slaveDataSource } = this.props;
      //   commonFieldPopupProps.app.currentPane.bEdit = this.props.enabled;
      //   /* 将合并生产数据JSON 回传到弹窗，并完成勾选 */
      //   commonFieldPopupProps.app.currentPane.slaveDataSource = slaveDataSource; /* 父组件的从表数据集 */
      //
      // }else if(commonFieldPopupConfig.sControlName && commonFieldPopupConfig.sControlName.includes('BtnPopup.dPreMatProductQty')) { /* 消耗备料数 */
      //   const { slaveData : slaveDataSource } = this.props;
      //   commonFieldPopupProps.app.currentPane.bEdit = this.props.enabled;
      //   /* 将合并生产数据JSON 回传到弹窗，并完成勾选 */
      //   commonFieldPopupProps.app.currentPane.slaveDataSource = slaveDataSource; /* 父组件的从表数据集 */
      //
      // }
    } else if (commonUtils.isNotEmptyObject(this.props)) {
      let commonFieldPopupConfig = {};
      const { masterConfig, sModelsId } = this.props;
      if (commonUtils.isNotEmptyObject(masterConfig)) {
        const iIndex = masterConfig.gdsconfigformslave.findIndex(item => commonUtils.isNotEmptyObject(item.sName) && item.sDropDownType === 'popup');
        if (iIndex > -1) {
          commonFieldPopupConfig = masterConfig.gdsconfigformslave[iIndex];
          commonFieldPopupTitle = commonUtils.isNotEmptyObject(commonFieldPopupConfig) && commonUtils.isNotEmptyObject(commonFieldPopupConfig.sActiveName) ? commonFieldPopupConfig.sActiveName : commonFieldPopupTitle;
          commonFieldPopupProps = {
            app: {
              ...this.props.app,
              currentPane: {
                name: 'commonPopup',
                config: commonFieldPopupConfig,
                conditonValues: this.props.getSqlCondition(commonFieldPopupConfig),
                title: commonFieldPopupTitle,
                route: '/indexPage/commonList',
                formRoute: '/indexPage/commonList',
                formId: commonFieldPopupConfig.sActiveId,
                key: sModelsId + commonFieldPopupConfig.sId,
                sModelsType: 'search/commonPopup',
                select: this.handleSelectCommonFieldPopup,
                selectCancel: this.handleSelectCancel.bind(this, 'commonFieldPopupVisible'),
              },
            },
            dispatch: this.props.dispatch,
            content: this.props.content,
            id: randomId,
            onOpenNewTab: this.onOpenNewTab,
            outerMasterData: this.props.masterData,
            realizeHeight: this.props.realizeHeight, /* 拖动偏移高度 */
          };
        }
      }
    }

    // 解决新增数据时组件没有刷新问题
    const viewRowSId = viewRow.sId || commonUtils.createSid();

    return (
      commonUtils.isNotEmptyArr(viewConfigs) ?
        <Col key={viewRowSId} span={iColValueView} order={viewOrder || 5} style={{ flex: app.currentPane.title === '功能模块界面设置单据' ? 1 : undefined }}>
          <Row type="flex" className="viewStyle" style={{ height: 'auto', overflow: 'auto', marginTop: 0 }}>
              {
                tableConfig.sChinese === '上批对比1' ?
                  <Col span={24}>
                    <Divider
                      orientation={'left'}
                      orientationMargin={0}
                      style={{
                        margin: '6px 0',
                        borderTopColor: 'rgba(0, 0, 0, 0.3)',
                      }}
                    >
                      <div>
                        <div
                          style={{
                            borderTop: '1px solid rgba(0, 0, 0, 0.3)',
                            width: 15,
                            position: 'absolute',
                            left: 0,
                            top: 16,
                          }}
                        />
                        <div
                          style={{
                            width: 4,
                            height: 4,
                            background: 'black',
                            position: 'absolute',
                            top: 15,
                            left: 26,
                            borderRadius: '50%',
                          }}
                        />
                      </div>
                      <span style={{ padding: '0 0 0 36px' }}>{tableConfig.sChinese}</span>
                    </Divider>
                  </Col> : ''
              }
            </Row>
          <Tooltip title={slaveName} placement="topLeft" visible={this.props.showTableName}>
            <Row type="flex" className="viewStyle" style={{ height: 'auto', overflow: 'auto', marginTop: viewOrder ? 0 : '8px' }}>
              {
                viewConfigs && viewConfigs.map((child) => {
                  const iOrder = sMemo ? 100 : child.iOrder > 100 ? 100 : child.iOrder; /* 排序 */
                  if (child.sControlName?.includes('DividerArea')) {
                    return (
                      <Col key={child.sId} span={24} order={iOrder}>
                        <Divider
                          orientation={child.sDefault || 'center'}
                          orientationMargin={child.sDefault === 'left' ? 0 : undefined}
                          style={{
                            margin: '6px 0',
                            borderTopColor: 'rgba(0, 0, 0, 0.3)',
                          }}
                        >
                          {child.sDefault === 'left' ?
                            <div>
                              <div
                                style={{
                                  borderTop: '1px solid rgba(0, 0, 0, 0.3)',
                                  width: 15,
                                  position: 'absolute',
                                  left: 0,
                                  top: 16,
                                }}
                              />
                              <div
                                style={{
                                  width: 4,
                                  height: 4,
                                  background: 'black',
                                  position: 'absolute',
                                  top: 15,
                                  left: 26,
                                  borderRadius: '50%',
                                }}
                              />
                            </div>
                            : ''
                          }
                          <span style={child.sDefault === 'left' ? { padding: '0 0 0 36px' } : {}}>{child.showName}</span>
                        </Divider>
                      </Col>
                    );
                  }

                  const iRowNum = child.iColValue === 1 ? 6 : 1; /* 1个字段占的网格个数 ，网格总个数是24 */
                  const iColValue = sMemo ? 24 : child.iColValue * iRowNum; /* 跨度 */ /* 产品部要求 备注设置成一行到底 */
                  const sMemo = child.sName.toLowerCase().endsWith('memo');
                  let enabledNew = (enabled && !child.bReadonly && !child.specialControl);
                  const sFormulaMemo = child.sName.toString() === 'sFormulaMemo' ? 'none' : 'block';
                  if (child.iTag === 1) {
                    enabledNew = false;
                  } else if (child.iTag === 3) {
                    enabledNew = true;
                  }

                  const viewRowNew = this.props.getViewRow?.(child) || viewRow;

                  const showTypeProps = {
                    app,
                    iColValue,
                    name: tableName,
                    record: viewRowNew,
                    sId: commonUtils.isNotEmptyObject(viewRowNew) ? viewRowNew.sId : commonUtils.createSid(),
                    form: this.props.form,
                    getSqlDropDownData: this.props.getSqlDropDownData,
                    getSqlCondition: this.props.getSqlCondition,
                    handleSqlDropDownNewRecord: this.props.handleSqlDropDownNewRecord,
                    getFloatNum: this.props.getFloatNum,
                    onChange: this.props.onDataChange,
                    showConfig: child,
                    slaveConfig: this.props[`${slaveName || tableName}Config`],
                    formItemLayout,
                    textArea: sMemo,
                    enabled: enabledNew,
                    sysEnabled: enabled,
                    dataValue: commonUtils.isNotEmptyObject(viewRowNew) ? viewRowNew[child.sName] : null,
                    bTable: true,
                    bViewTable: true,
                    formRoute: this.props.formRoute,
                    onDropDownBlur: this.props.onDropDownBlur, /* 下拉框多选离开事件 */
                    onViewClick: this.handleViewClick,
                    onFieldDoubleClick: this.props.handleFieldDoubleClick,
                    getDateFormat: this.props.getDateFormat,
                    onFieldPopupModal: this.props.onFieldPopupModal || this.handleFieldPopupModal,
                    onCostomChange: this.props.onCostomChange, // 控件后自定义按钮事件
                    sBtnSendDialogConfigList: this.props.sBtnSendDialogConfigList, // 校验并获取物料主数据按钮配置
                    onToolBarBtnClick: this.props.onToolBarBtnClick, // 工具栏按钮事件
                    onExecInstructSet: this.props.onExecInstructSet, // 调用指令集
                    onCostomClick: this.props.onCostomClick,
                  };
                  return (
                    <Col key={child.sId} span={iColValue} order={iOrder} style={{ display: sFormulaMemo, position: 'relative' }}>
                      <ShowType {...showTypeProps} />
                      {this.props.extraContent && this.props.extraContent(child)}
                      {this.props.extraContent2 && this.props.extraContent2(child)}
                    </Col>
                  );
                })
              }
            </Row>
          </Tooltip>
          {
            commonFieldPopupVisible ?
              <AntdDraggableModal
                width={1300}
                zIndex={1000}
                title={commonFieldPopupTitle}
                visible={commonFieldPopupVisible}
                onCancel={this.handleSelectCancel.bind(this, 'commonFieldPopupVisible')}
                footer={null}
                onSaveState={this.props.onSaveState}
                className={`${randomId}-CommonListSelectTree`}
              >
                {[''].map(() => {
                  const { commonFieldPopupType } = this.state;
                  if (commonFieldPopupType === 'CommonListSelect') {
                    return <CommonListSelect {...commonFieldPopupProps} />;
                  } else {
                    return <CommonListSelectTree {...commonFieldPopupProps} />;
                  }
                })}
              </AntdDraggableModal>
              : ''
          }

        </Col> : ''
    );
  }
}
