You need to sign in before continuing.
index.js 17.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
/* eslint-disable */
import React, {
  useContext,
  useEffect,
  useReducer,
  useRef,
  useState
} from "react";
// import "@ant-design/compatible/assets/index.css";
import { Tabs, Tooltip, message } from "antd-v4";
import ShowType from "@/components/Common/CommonComponent";
import * as commonBusiness from "@/components/Common/commonBusiness";
import StaticEditTable from "@/components/Common/CommonTable";
import * as commonUtils from "@/utils/utils";
import * as rglUtils from "./rglUtils";
import RGL, { WidthProvider } from "react-grid-layout";
import styles from "./index.less";

const ReactGridLayout = WidthProvider(RGL);
const { myContext, reducer } = commonUtils;

const initialState = {
  // sParamList: ["sProcess", "sReport", "sWorkOrder", "sNorm", "sTest"],
  // sParamNameList: ["工序参数", "上报参数", "工单参数", "标准书参数", "测试参数"],
  selectedData: {} // 当前选中数据
};

// 可拖拽组件
const CommonViewDragable = props => {
  const { tableName } = props;
  const [state, dispatch] = useReducer(reducer, initialState);

  let selectedRowKeys = props[`${tableName}SelectedRowKeys`] || [];
  if(commonUtils.isEmptyArr(selectedRowKeys) && commonUtils.isNotEmptyArr(props[`${tableName}Data`]) ) {
    selectedRowKeys =  [props[`${tableName}Data`][0]]
  }
  const key = selectedRowKeys[0] || commonUtils.createSid();
  const selectedData = handleGetSelectedData(props);

  // 根据选中节点获取选中数据
  useEffect(
    () => {
      dispatch(["saveState", { selectedData }]);
    },
    [selectedRowKeys[0], JSON.stringify(selectedData)]
  );

  return (
    <myContext.Provider
      value={{
        props,
        hooksProps: { ...state, dispatch }
      }}
    >
      <div className={`viewStyle ${styles.commonViewDragable}`} key={key}>
        <TabComponent />
      </div>
    </myContext.Provider>
  );
};

const TabComponent = () => {
  const { props } = useContext(myContext);
  const { hideTabsNav, sParamData = [] } = props;
  return (
    <Tabs
      className={hideTabsNav ? "hideTabsNav" : ""}
      items={sParamData.map(({ sParamType, sParamName }) => ({
        label: sParamName,
        key: sParamType,
        children: <TabPaneComponent sParamType={sParamType} />
      }))}
    />
  );
};

const TabPaneComponent = childProps => {
  const { props } = useContext(myContext);
  const { sParamType } = childProps;
  const selectedData = handleGetSelectedData(props);
  const fieldsName = `b${sParamType.replace("s", "").trim()}ParamTable`;
  const bTable = selectedData[fieldsName];
  return (
    <div className="tabPaneComponent">
      {bTable ? (
        <ParamTableComponent {...childProps} />
      ) : (
        <RGLComponent {...childProps} />
      )}
    </div>
  );
};

const ParamTableComponent = childProps => {
  const { props, hooksProps } = useContext(myContext);
  const { tableName } = props;
  const { selectedData } = hooksProps;
  const { sParamType } = childProps;

  const [paramListTableProps, setParamListTableProps] = useState(null);
  const xlyTableRef = useRef(null);

  const tableData = props[`${tableName}Data`] || [];
  useEffect(
    () => {
      if (commonUtils.isNotEmptyObject(selectedData)) {
        const result = rglUtils.getTableParams(
          sParamType,
          selectedData,
          xlyTableRef
        );
        setParamListTableProps({
          ...commonBusiness.getTableTypes(sParamType, {
            ...props,
            ...result
          }),
          bSParamTable: true,
          // enabled: true,
          tableProps: {
            AutoTableHeight: handleGetTableHeight(props, xlyTableRef, true)
          },
          onDataChange: (...args) => {
            handleDataChange(props, args);
          }
        });
      }
    },
    [JSON.stringify(selectedData), tableData.length]
  );

  return (
    <div className="xly-workorder-list xlyTable" ref={xlyTableRef}>
      {paramListTableProps && <StaticEditTable {...paramListTableProps} />}
    </div>
  );
};

const RGLComponent = childProps => {
  const { props, hooksProps } = useContext(myContext);
  const { tableName } = props;
  const { selectedData } = hooksProps;
  const { sParamType } = childProps;
  const xlyRGLRef = useRef(null);
  // const [maxHeight, setMaxHeight] = useState("auto");
  const [rglConfig, setRglConfig] = useState({});
  const {
    layout = [],
    configs = [],
    paramData = {},
    record = {},
    recordDefault = {}
  } = rglConfig;
  const [layoutKey, setLayoutKey] = useState(0);
  useEffect(
    () => {
      if (commonUtils.isNotEmptyObject(selectedData)) {
        const result = rglUtils.getReactGridLayout(
          sParamType,
          selectedData,
          props.sModelsId,
          props.formRoute
        );
        setLayoutKey(selectedData.sId);
        setRglConfig(result);
      }
    },
    [JSON.stringify(selectedData)]
  );

  // const tableData = props[`${tableName}Data`] || [];
  // useEffect(
  //   () => {
  //     setMaxHeight(handleGetTableHeight(props, xlyRGLRef));
  //   },
  //   [tableData.length]
  // );

  return configs.length ? (
    <div
      style={{
        width: "100%",
        height: "100%",
        overflowY: "auto"
        // maxHeight
      }}
      key={layoutKey}
      ref={xlyRGLRef}
    >
      <ReactGridLayout
        margin={[0, 2]}
        verticalCompact={false}
        layout={layout}
        cols={24}
        rowHeight={28}
        isDraggable={false}
        isResizable={false}
        isDroppable={false}
      >
        {configs.map(child => {
          const showTypeProps = handleGetShowTypeProps({
            sParamType,
            child,
            props,
            layout,
            record,
            recordDefault
          });

          return (
            <div key={child.sName} id={child.sName} className="showType">
              {/* {showTypeProps.layoutW === 1 ? (
                <Tooltip placement="top" title={`${child.showName}:${showTypeProps.dataValue}`}>
                  <div>
                    <ShowType {...showTypeProps} />
                  </div>
                </Tooltip>
              ) : (  */}
              <Tooltip placement="top" title={showTypeProps.dataValue}>
                <div>
                  <ShowType {...showTypeProps} />
                </div>
              </Tooltip>
              {/* )} */}
            </div>
          );
        })}
      </ReactGridLayout>
    </div>
  ) : (
    <EmptyComponent />
  );
};

const EmptyComponent = () => {
  return <div className="emptyComponent">暂无数据</div>;
};

// 获取选中数据
const handleGetSelectedData = props => {
  const { tableName } = props;
  const iIndex = handleGetSelectedDataIndex(props);
  if (iIndex !== -1) {
    return props[`${tableName}Data`][iIndex];
  } else {
    return {};
  }
};

// 获取选中数据index
const handleGetSelectedDataIndex = props => {
  const { tableName } = props;
  const selectedRowKeys = props[`${tableName}SelectedRowKeys`] || [];

  let selectedDataIndex = -1;
  const tableData = props[`${tableName}Data`];
  if (commonUtils.isNotEmptyArr(tableData)) {
    if (commonUtils.isNotEmptyArr(selectedRowKeys)) {
      selectedDataIndex = tableData.findIndex(
        item => item.sId === selectedRowKeys[0]
      );
    } else {
      selectedDataIndex = 0;
    }
  }
  return selectedDataIndex;
};

// 获取表单参数
const handleGetShowTypeProps = params => {
  const { sParamType, child, props, layout, record, recordDefault } = params;
  const { app, form, tableName, comparedTableId, bSimpleMode } = props;

  // 计算标题和组件的宽度比
  let w = 6;
  let h = 1;
  const iIndex = layout.findIndex(item => item.i === child.sName);
  if (iIndex !== -1) {
    w = layout[iIndex].w;
    h = layout[iIndex].h;
  }
  const flexWidth = w > 2 ? (3 * 66) / w : 0;
  const formItemLayout = {
    labelCol: {
      flex: flexWidth + "%",
      style: {
        color: "rgba(0, 0, 0, 0.65)",
        backgroundColor: "#BFEFFF"
      }
    },
    wrapperCol: { flex: "auto" }
  };

  if (props.processTitleWidth) {
    formItemLayout.labelCol.flex = props.processTitleWidth;
  }

  let bDisabled = !props.enabled;
  const config = props[`${tableName}Config`];
  if (commonUtils.isNotEmptyObject(config)) {
    const sParamsConfig = config.gdsconfigformslave.find(
      item => item.sName === "sParams"
    );
    if (sParamsConfig && sParamsConfig.iTag === 1) {
      bDisabled = true;
    }
  }

  if (child.bReadOnly) {
    bDisabled = true;
  }

  const selectData = handleGetSelectedData(props);

  const bIFace = ["单双面", "印面"].includes(child.showName);
  const bAlumiteBomBillNo =
    child.showName === "电化铝BOM" || child.showName === "电化铝版本";

  let iFaceConfig = {};
  let alumiteBomBillNoConfig = {};

  let showConfig = { ...child };
  if (!bSimpleMode) {
    if (bIFace) {
      iFaceConfig = config.gdsconfigformslave.find(
        item => item.sName === "iFace"
      );
      showConfig = {
        ...iFaceConfig,
        sName: showConfig.sName,
        showName: showConfig.showName,
        bVisible: showConfig.bVisible
      };
    } else if (bAlumiteBomBillNo) {
      alumiteBomBillNoConfig = config.gdsconfigformslave.find(
        item => item.sName === "sAlumiteBomBillNo"
      );
      showConfig = {
        ...alumiteBomBillNoConfig,
        sName: showConfig.sName,
        showName: showConfig.showName,
        bVisible: showConfig.bVisible
      };
    }
  }

  const getDataValue = () => {
    if (props.bSimpleMode) {
      return record[child.sName];
    } else if (child.showName === "色序") {
      return selectData.sColorSerialMemo;
    } else if (bIFace) {
      if (commonUtils.isNotEmptyObject(iFaceConfig)) {
        const showDropDown = commonUtils.convertStrToObj(
          iFaceConfig.showDropDown
        );
        return showDropDown[selectData.iFace] || "";
      } else {
        return record[child.sName];
      }
    } else if (bAlumiteBomBillNo) {
      return selectData.sAlumiteBomBillNo;
    } else {
      return record[child.sName];
    }
  };

  const processTbName =
    location.pathname === "/indexPage/commonCostomTabBill"
      ? "slave0"
      : "process";

  return {
    ...props,
    className: h > 1 ? "multiLine" : "",
    key: `${child.sName}_${flexWidth}`,
    name: !bSimpleMode && bAlumiteBomBillNo ? tableName : sParamType,
    formItemLayout,
    onChange: (...args) => {
      handleDataChange(
        { ...props, bIFace, bAlumiteBomBillNo, showConfig, recordDefault },
        args
      );
    },
    onViewClick: props.handleViewClick,
    enabled: !bDisabled,
    bTable: true,
    bViewTable: true,
    dataValue: getDataValue(),
    costomClassName: "",
    layoutW: w,
    bSColorSerialMemo:
      !bSimpleMode && child.showName === "色序" && props.onViewChoose,
    onViewChoose: () => {
      props.onViewChoose("process", "sColorSerialMemo", selectData);
    },
    onFieldPopupModal: showConfig => {
      if (window[`${comparedTableId}FieldPopupModal`]) {
        if (bAlumiteBomBillNo) {
          window[`${comparedTableId}FieldPopupModal`](
            { ...showConfig, sName: "sAlumiteBomBillNo" },
            processTbName
          );
        } else {
          window[`${comparedTableId}FieldPopupModal`](showConfig, "process");
        }
      }
    },
    record: !bSimpleMode && bAlumiteBomBillNo ? selectData : record,

    // record: { 'sParam1': 111, 'sParam2': 222,'sParam3': 333,'sParam4': 444,'sParam5': 555 },
    // sId: viewRow.sId,
    app,
    form,
    getSqlDropDownData: props.getSqlDropDownData,
    getSqlCondition: props.getSqlCondition,
    handleSqlDropDownNewRecord: props.handleSqlDropDownNewRecord,
    getFloatNum: props.getFloatNum,
    showConfig: {
      ...showConfig,
      sName: showConfig.sNameParam ? showConfig.sNameParam : showConfig.sName
    },
    textArea: h > 2,
    formRoute: props.formRoute,
    onFieldDoubleClick: props.handleFieldDoubleClick
  };
};

// 判断是否在弹出框
const bInModal = el => {
  if (commonUtils.isEmpty(el) || commonUtils.isEmpty(el.classList)) {
    return false;
  } else if (el.classList.contains("ant-modal-root")) {
    return true;
  } else {
    return bInModal(el.parentNode);
  }
};

// 获取表格高度
const handleGetTableHeight = (props, ref, bTable) => {
  let tableHeight = "auto";
  if (bInModal(ref.current)) {
    tableHeight = "60vh";
  } else {
    const { comparedTableId } = props;
    if (comparedTableId) {
      const oTable = document.querySelector(`#${comparedTableId}`);
      if (oTable) {
        const oContainer = oTable.querySelector(".ant-table-container");
        if (oContainer) {
          tableHeight = oContainer.getBoundingClientRect().height;
          if (bTable) {
            tableHeight -= 30;
          }
          tableHeight = Math.max(tableHeight, 29 * 3); // 最少三行高度
        }
      }
    }
  }
  return tableHeight;
};

// 数据修改
const handleDataChange = (props, args) => {
  const {
    tableName,
    bIFace,
    bAlumiteBomBillNo,
    bSimpleMode,
    recordDefault
  } = props;
  const [sParamType, sName, returnValue, _sId, _dropDownDataNew, record] = args;

  if (
    returnValue[sName] &&
    typeof returnValue[sName] === "string" &&
    returnValue[sName].includes('"')
  ) {
    message.error("输入框不允许输入双引号");
    return;
  }
  const iIndex = handleGetSelectedDataIndex(props);
  if (iIndex !== -1) {
    const tableData = props[`${tableName}Data`];

    // 获取params数据
    const { sParams, [`${sParamType}Param`]: sParamStr } = tableData[iIndex];
    const recordDataAll = commonUtils.convertStrToObj(sParams, []);
    const recordItemIndex = recordDataAll.findIndex(
      item => item.sParamType === sParamType
    );

    let dataNew = {};
    if (props.showConfig && props.showConfig.sNameParam) {
      dataNew[props.showConfig.sName] = returnValue[sName];
    }
    dataNew =
      record && record.sParamKey
        ? { [record.sParamKey]: returnValue[sName] }
        : { ...dataNew, ...returnValue };

    if (recordItemIndex !== -1) {
      let tempData = {
        ...recordDefault,
        ...recordDataAll[recordItemIndex].data,
        ...dataNew
      };
      tempData = handleAssignField(
        props,
        recordDefault,
        tempData,
        sParamStr,
        sName
      );
      recordDataAll[recordItemIndex].data = tempData;
    } else {
      let tempData = {
        ...recordDefault,
        ...dataNew
      };
      tempData = handleAssignField(
        props,
        recordDefault,
        tempData,
        sParamStr,
        sName
      );
      recordDataAll.push({
        sParamType,
        data: tempData
      });
    }

    const { [`${sParamType}Param`]: paramConfigStr } = tableData[iIndex];
    const paramConfig = commonUtils.convertStrToObj(paramConfigStr);
    const sAssFieldName = sName.replace("sParam", "sParamAssFieldName");
    if (commonUtils.isNotEmptyStr(paramConfig[sAssFieldName])) {
      paramConfig[sAssFieldName].split(",").map(item => {
        tableData[iIndex][item] = dataNew[sName];
      });
    }

    tableData[iIndex].sParams = commonUtils.convertObjToStr(recordDataAll);
    tableData[iIndex].handleType = tableData[iIndex].handleType || "update";

    if (!bSimpleMode) {
      if (bIFace) {
        tableData[iIndex].iFace = isNaN(returnValue[sName])
          ? returnValue[sName]
          : Number(returnValue[sName]);
      }
      if (bAlumiteBomBillNo) {
        tableData[iIndex].sAlumiteBomBillNo = returnValue[sName];
      }
    }

    if (props.onCostomSaveData) {
      props.onCostomSaveData(tableData);
    } else {
      props.onSaveState({ [`${tableName}Data`]: tableData });
    }
  }
};

// 处理赋值字段
const handleAssignField = (
  props,
  recordDefault,
  tempData,
  sParamStr,
  sName
) => {
  const sParam = commonUtils.convertStrToObj(sParamStr);
  let sParamAssignFieldList = Object.keys(sParam).reduce((result, key) => {
    if (key.startsWith("sParamAssignField")) {
      const assignField = sParam[key];
      const iOrder = Number(key.replace("sParamAssignField", ""));
      if (!sParam[`sParamDropDownType${iOrder}`]) {
        const sParamName = `sParam${iOrder}`;
        const sParamFieldName = sParam[`sParamFieldName${iOrder}`];
        result.push({
          sParamName,
          sParamFieldName,
          assignField
        });
      }
    }
    return result;
  }, []);

  sParamAssignFieldList = sParamAssignFieldList.filter(item => {
    const { assignField } = item;
    const result = assignField.split(/[^a-zA-Z0-9]+/).filter(Boolean);
    return result.includes(sName);
  });

  if (sParamAssignFieldList.length) {
    sParamAssignFieldList.forEach(item => {
      const { sParamName, sParamFieldName, assignField } = item;
      let result;
      try {
        const str = Object.keys({ ...recordDefault, ...tempData }).reduce(
          (pre, cur) => {
            if (cur.startsWith("d") || cur.startsWith("i")) {
              return `${pre}let ${cur} = ${tempData[cur]}; `;
            } else {
              return `${pre}let ${cur} = "${tempData[cur]}"; `;
            }
          },
          ""
        );
        try {
          result = eval(str + assignField);
        } catch (error) {
          result = eval(str.replace(/let\ /g, "var ") + assignField);
        }
      } catch (error) {}
      if (result !== undefined) {
        tempData[sParamName] = result;
        if (sParamFieldName) {
          tempData[sParamFieldName] = result;
        }
      }
    });
  }

  return tempData;
};

export default CommonViewDragable;

/*
  props参数:
  {
    hideTabsNav: boolean, // 是否隐藏tab导航
    sParamData: Array, // tab展示的参数 格式[{ sParamType: 'sWorkOrder', sParamName: '工单参数' }, ...{} ]
    selectedData: {}, // 当前选中数据
    tableName: 'process', // 工序表名,用于修改数据
  }
**/