index.tsx 16.9 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
import React, {
  useCallback,
  useEffect,
  useImperativeHandle,
  useMemo,
  useRef,
  useState,
} from 'react';
import './index.less';

import {
  CloseOutlined,
  CompressOutlined,
  ExpandOutlined,
} from '@ant-design/icons';
import { handleWindowOpen } from '@qx/utils';
import { Button, Modal, Switch } from 'antd';
import { ModalProps, TreeDataNode } from 'antd/lib';
import _ from 'lodash-es';
import { FIELD_TYPE_PROPS } from '../constant';
import CodeEditor from '../qx-code-editor';
import DescBox from './components/desc-box';
import FxPicker from './components/fx-picker';
import VarPicker from './components/var-picker';
import { getFunctionList } from './service';
import {
  SYSVariable,
  checkFormulaExpress,
  copyText,
  handleFlattenList,
} from './util';

export interface FunctionProps {
  title: string;
  titleDesc?: string;
  key: string;
  selectable?: boolean;
  icon?: any;
  children?: FunctionProps[];
  desc?: string;
  formula?: string;
  params?: any;
  returnType?: string;
  demon?: string;
  funcNameEg: string;
}
export interface ColsTreeSelectProps extends TreeDataNode {
  attrs?: {
    titleStr: string;
    fieldGroupType: 'TEXT' | 'OBJECT' | 'DATE';
    key: string;
  }[];
  key: string;
  titleStr?: string;
  iconName?: string;
  widget?: string;
  fieldGroupType?: 'TEXT' | 'OBJECT' | 'DATE';
  children?: ColsTreeSelectProps[];
}

interface QxFunOperationProps {
  appCode: string;
  funCode: string;
  cRef?: any;
  value: any;
  onChange: (val: string, val2?: string[], val3?: boolean) => void;
  colsTree: ColsTreeSelectProps[];
  style?: any;
  autofocus?: boolean;
  fieldName: string;
  fieldType: 'TEXT' | 'OBJECT' | 'DATE';
  uniKey: string;
  isScriptEditMode?: boolean;
  isInSubForm?: boolean;
  isFullScreen: boolean;
}

/**
 * 启效函数运算器
 *
 * @param props
 * @constructor
 */
export const QxFunctionOperation: React.FC<QxFunOperationProps> = ({
  cRef,
  value,
  appCode,
  funCode,
  onChange,
  colsTree,
  autofocus,
  fieldName = '',
  fieldType,
  isScriptEditMode = false,
  uniKey,
  isInSubForm,
}) => {
  const editorBoxRef = useRef<any>();
  const codeEditorRef = useRef<any>();

  // 变量列表
  const [varDataList, setVarDataList] = useState<ColsTreeSelectProps[]>([]);
  // 公式函数列表
  const [funcDataList, setFuncDataList] = useState<FunctionProps[]>([]);
  // 动态设置函数释义下的"当前函数"
  const [funDescription, setFunDescription] = useState<FunctionProps | null>();
  // 新变量(插入)
  const [newVariable, setNewVariable] = useState<any>();
  // 标识脚本编辑
  const [scriptEdit, setScriptEdit] = useState(false);
  // 错误悬浮提示
  const [errorMap, setErrorMap] = useState({
    show: false,
    msg: '',
  });
  const pickedFunc = useRef<FunctionProps>(null);
  const pickFunc = (data: FunctionProps) => {
    // @ts-ignore
    pickedFunc.current = data;
    setFunDescription(data);
  };

  // const onMouseDown = (event: any) => {
  //   let startPy = event.clientY;
  //   let offsetHeight = editorBoxRef?.current.offsetHeight;
  //   document.body.onmousemove = function (e: any) {
  //     const offsetY = e.clientY - startPy;
  //     const height = offsetHeight + offsetY;
  //     if (!startPy || height > 400 || height < 200) return;
  //     editorBoxRef?.current?.setAttribute('style', `height: ${height}px`);
  //   };
  //   document.body.onmouseup = function () {
  //     document.body.onmousemove = null;
  //   };
  // };

  useEffect(() => {
    if (isScriptEditMode) setScriptEdit(isScriptEditMode);
  }, [isScriptEditMode]);

  const dealFunctionList = (originData: any) => {
    // const titleEnum: any = {
    //   TEXT: '文本函数',
    //   MATH: '数学函数',
    //   DATE: '日期函数',
    //   LOGICAL: '逻辑函数',
    //   REGULAR: '正则函数',
    //   ADVANCED: '高级函数',
    //   CUSTOM: '自定义',
    //   COMMON: '常用函数',
    // };
    if (!_.isArray(originData)) {
      return;
    }
    const funcList: any = originData?.map(
      (item: { name: string; code: string; details?: any[] }) => {
        return {
          key: item.code,
          title: item.name,
          selectable: false,
          children: (item.details || []).map((it: any) => ({
            ...it,
            title: it.funcNameEg,
            key: it.id,
            titleDesc: it.funcName,
            formula: it.methodView,
            desc: it.description,
            returnType: it.dataType,
            demon: it.executeDemo,
          })),
        };
      },
    );
    setFuncDataList(funcList);
  };

  useEffect(() => {
    let _colsTree;
    let curLevel = colsTree.filter((o) => !o.titleStr?.startsWith('【主表】'));
    const mainLevel = colsTree
      .filter((o) => o.titleStr?.startsWith('【主表】'))
      .map((o) => ({
        ...o,
        titleStr: o.titleStr?.substring(4),
      }));
    if (isInSubForm) {
      if (_.isEmpty(curLevel)) {
        _colsTree = mainLevel;
      } else {
        _colsTree = mainLevel.concat({
          key: 'SUB',
          titleStr: '子表字段',
          children: curLevel,
        });
      }
    } else {
      _colsTree = curLevel;
    }
    setVarDataList([
      {
        key: 'FORM',
        titleStr: '表单变量',
        children: _colsTree,
      },
      {
        key: 'SYS',
        titleStr: '系统变量',
        children: SYSVariable,
      },
    ]);
  }, [JSON.stringify(colsTree), SYSVariable, isInSubForm]);
  useEffect(() => {
    getFunctionList(appCode, funCode).then((res: any) => {
      if (res) {
        dealFunctionList(res);
      }
    });
  }, []);

  const flattenVarList = useMemo(() => {
    const _list: any[] = [];
    handleFlattenList(varDataList || [], _list);
    return _list;
  }, [varDataList]);

  // 编辑器光标移动
  const onHandleHoverFxChange = useCallback((data: any) => {
    if (data) {
      setFunDescription(data);
    } else if (pickedFunc.current) {
      setFunDescription(pickedFunc.current);
    } else {
      setFunDescription(null);
    }
  }, []);

  // 选中函数公式
  const onHandlerPickFunc = useCallback((data: any) => {
    setNewVariable({
      key: data.funcNameEg,
      name: data.title,
      type: 'fun',
    });
  }, []);

  // 选中变量
  const onHandlerPickVar = useCallback((data: any) => {
    setNewVariable({
      key: data.key,
      name: data.titleStr,
    });
  }, []);

  useEffect(() => {
    if (!funcDataList.length) return;
    const { errMsg, errCode } = checkFormulaExpress(
      value,
      funcDataList,
      varDataList,
      codeEditorRef?.current?.getUsedFuncList(),
      fieldType,
      flattenVarList,
    );
    setErrorMap({
      show: errCode ? true : false,
      msg: errMsg,
    });
  }, [funcDataList]);

  // 捕获编辑器内容改变
  const onHandlerEditorChange = (code: any) => {
    console.log('code: ', code);
    onChange(code);
    if (!funcDataList.length) return;
    const { errMsg, errCode } = checkFormulaExpress(
      code,
      funcDataList,
      varDataList,
      codeEditorRef?.current?.getUsedFuncList(),
      fieldType,
      flattenVarList,
    );
    setErrorMap({
      show: errCode ? true : false,
      msg: errMsg,
    });
  };

  useImperativeHandle(cRef, () => ({
    scriptEdit,
    getUsedFuncList() {
      return codeEditorRef?.current?.getUsedFuncList();
    },
  }));

  return (
    <div className="qx-operation">
      <div className="toolbar">
        <div className="field-name">{fieldName} =</div>
        <div className="tools">
          <div
            className="tool-item"
            onClick={() => {
              codeEditorRef?.current?.autoFormatSelection();
            }}
          >
            <span className="qx-f-icon-beautify" />
            {/* <UngroupOutlined /> */}
            <span className="text ">美化</span>
          </div>
          <div
            className="tool-item"
            onClick={() => {
              const editor = codeEditorRef?.current?.getEditor();
              const s_len = editor.getValue().length;
              const startPos = { line: 0, ch: 0, sticky: null };
              const endPos = editor.doc.posFromIndex(s_len);
              editor.setSelection(startPos, endPos);
              copyText(editor.getValue());
            }}
          >
            <span className="qx-f-icon-copy" />
            <span className="text ">复制</span>
          </div>
          <div className="tool-item">
            <Switch
              checked={scriptEdit}
              size="small"
              onChange={(checked) => {
                setScriptEdit(checked);
              }}
            />
            <span className="text">脚本编辑</span>
          </div>
        </div>
      </div>
      <div
        ref={editorBoxRef}
        className="editor-box"
        onClick={() => {
          const editor = codeEditorRef?.current?.getEditor();
          editor.focus();
        }}
      >
        <CodeEditor
          cRef={codeEditorRef}
          key={uniKey}
          value={value}
          isUseFun={true}
          autofocus={autofocus}
          funcDataList={funcDataList}
          varDataList={varDataList}
          newVariable={newVariable}
          onChange={onHandlerEditorChange}
          onFocusFunc={(data: any) => {
            // @ts-ignore
            pickedFunc.current = data;
            setFunDescription(data);
          }}
        />
        <div className={`error-zone ${errorMap.show ? 'show' : ''}`}>
          {errorMap.msg}
        </div>
      </div>
      <div className="custom">
        <FxPicker
          dataSource={funcDataList}
          onHover={onHandleHoverFxChange}
          onPick={onHandlerPickFunc}
          pickFunc={pickFunc}
        />
        <VarPicker dataSource={varDataList} onPick={onHandlerPickVar} />
        <DescBox scriptEdit={scriptEdit} funcData={funDescription} />
      </div>
    </div>
  );
};

interface QxFunOperationModalProps extends QxFunOperationProps {
  modalParams: ModalProps;
  defaultSetting?: any; // 函数公式 一个字段校验 所需参数 放置处
  isInSubForm?: boolean;
  appCode: string;
  funCode: string;
}

/**
 * "函数运算器"Modal弹窗版
 *
 * @param value
 * @param onChange
 * @param style
 * @param colsTree
 * @param autofocus
 * @param modalParams
 * @param fieldName
 * @param fieldType
 * @param uniKey
 * @constructor
 */
export const QxFunctionOperationModal: React.FC<QxFunOperationModalProps> = ({
  value,
  onChange,
  style,
  colsTree,
  autofocus,
  modalParams,
  fieldName,
  fieldType,
  uniKey,
  isScriptEditMode,
  isInSubForm,
  appCode,
  funCode,
}) => {
  const qxFuncOperaionRef = useRef<any>();
  const [funValues, setFunValues] = useState<any>();

  useEffect(() => {
    setFunValues(value);
  }, [value]);

  const [isFullScreen, setIsFullScreen] = useState(false);
  /**实现F11全屏效果*/
  const fullScreen = () => {
    // var docElm = document.documentElement;
    // /*W3C*/
    // if (docElm.requestFullscreen) {
    //   docElm.requestFullscreen();
    // } /*FireFox */ else if (docElm.mozRequestFullScreen) {
    //   docElm.mozRequestFullScreen();
    // } /*Chrome等 */ else if (docElm.webkitRequestFullScreen) {
    //   docElm.webkitRequestFullScreen();
    // } /*IE11*/ else if (docElm.msRequestFullscreen) {
    //   docElm.msRequestFullscreen();
    // }
    setIsFullScreen(true);
  };
  /**退出F11全屏*/
  const exitFullScreen = () => {
    // if (document.exitFullscreen) {
    //   document.exitFullscreen();
    // } else if (document.mozCancelFullScreen) {
    //   document.mozCancelFullScreen();
    // } else if (document.webkitCancelFullScreen) {
    //   document.webkitCancelFullScreen();
    // } else if (document.msExitFullscreen) {
    //   document.msExitFullscreen();
    // }
    setIsFullScreen(false);
  };

  // 点击确定 调用方法
  const onHandleCancel = () => {
    setFunValues(value || '');

    const e: any = new MouseEvent('click', {
      bubbles: true,
      cancelable: true,
    });
    setTimeout(() => modalParams?.onCancel && modalParams?.onCancel(e), 200);
  };

  // 点击确定 调用方法
  const onHandleOk = () => {
    const { getUsedFuncList, scriptEdit } = qxFuncOperaionRef.current;
    if (!_.isEqual(funValues, value) || scriptEdit !== isScriptEditMode) {
      const usedFuncList = getUsedFuncList();
      console.log(
        'code: ',
        funValues,
        ' useFuncList: ',
        usedFuncList,
        ' scriptEdit: ',
        scriptEdit,
      );
      onChange(funValues, usedFuncList, scriptEdit);
    }

    const e: any = new MouseEvent('click', {
      bubbles: true,
      cancelable: true,
    });
    setTimeout(() => modalParams?.onOk && modalParams?.onOk(e), 200);
  };

  const newColsTree = useMemo(() => {
    (colsTree || []).forEach((item) => {
      if (item.widget === 'qxSelect') {
        const code = item.key.slice(2, -1);
        item.attrs = [
          {
            key: '${' + code + '.code' + '}',
            titleStr: '编号',
            fieldGroupType: FIELD_TYPE_PROPS.TEXT,
          },
          {
            key: '${' + code + '.name' + '}',
            titleStr: '文本',
            fieldGroupType: FIELD_TYPE_PROPS.TEXT,
          },
          {
            key: '${' + code + '.score' + '}',
            titleStr: '赋值',
            fieldGroupType: FIELD_TYPE_PROPS.NUM,
          },
        ];
      }
    });
    return colsTree;
  }, [colsTree]);

  // const handleTree = (colsTree: ColsTreeSelectProps) => {
  //   console.log(colsTree);
  //   return colsTree;
  // };

  return (
    <Modal
      key={uniKey}
      visible={modalParams.visible}
      wrapClassName={`fx-wrapper`}
      width={880}
      centered={true}
      maskClosable={false}
      destroyOnClose={true}
      footer={null}
      {...modalParams}
      className={`rel-more_modal ${isFullScreen ? 'rel-more_modal_full' : ''}`}
    >
      <div className="header">
        <div className="header-item">
          <span className="title">函数编辑</span>
          <span
            className="manual"
            onClick={() => {
              handleWindowOpen(
                'https://qgutech.yuque.com/g/team-qx/helper/mlh9yzyewec7hb81/collaborator' +
                  '/join?token=mjqmsZwJo9iTTkTb&source=doc_collaborator#',
              );
            }}
          >
            <svg
              width="16"
              height="16"
              viewBox="0 0 16 16"
              fill="none"
              className="qx-f-icon-help"
            >
              <g>
                <path
                  fillRule="evenodd"
                  clipRule="evenodd"
                  d="M1.33331 7.99992C1.33331 4.31802 4.31808 1.33325 7.99998 1.33325C11.6819 1.33325 14.6666 4.31802 14.6666 7.99992C14.6666 11.6818 11.6819 14.6666 7.99998 14.6666C4.31808 14.6666 1.33331 11.6818 1.33331 7.99992ZM6.86652 6.65945V6.50573C6.86732 6.32282 6.93273 6.11993 7.07868 5.96739C7.21347 5.82651 7.4762 5.66659 7.99602 5.66659C8.48416 5.66659 8.8236 5.89964 8.99671 6.16424C9.18158 6.4468 9.14515 6.68389 9.05741 6.80234C8.94799 6.95007 8.81212 7.08651 8.64793 7.23433C8.59797 7.2793 8.5364 7.33288 8.47038 7.39032L8.47037 7.39034C8.35231 7.49307 8.22004 7.60817 8.11457 7.70852C7.74008 8.06486 7.3333 8.5622 7.3333 9.33325L7.33547 9.67087L8.66877 9.6623L8.66665 9.33143C8.66714 9.10341 8.76061 8.93428 9.03368 8.67446C9.12546 8.58712 9.20797 8.51574 9.30238 8.43406L9.30242 8.43402C9.37224 8.37362 9.44858 8.30758 9.54 8.22528C9.73012 8.05413 9.94168 7.84862 10.1288 7.59597C10.6342 6.91365 10.516 6.05112 10.1125 5.43426C9.69713 4.79943 8.94146 4.33325 7.99602 4.33325C7.17786 4.33325 6.54355 4.59802 6.11528 5.04563C5.69841 5.48133 5.5347 6.0303 5.53318 6.50235V6.65945H6.86652ZM7.33545 10.3333V11.6692H8.66879V10.3333H7.33545Z"
                />
              </g>
            </svg>
            公式使用帮助手册
          </span>
        </div>
        {/* <Tooltip placement="right" title={'公式使用帮助手册'}>
        </Tooltip> */}
        <div className="header-item">
          {isFullScreen ? (
            <CompressOutlined
              className="icon-right expand"
              onClick={exitFullScreen}
            />
          ) : (
            <ExpandOutlined
              className="icon-right expand"
              onClick={fullScreen}
            />
          )}
          <CloseOutlined
            className="icon-right close"
            onClick={onHandleCancel}
          />
        </div>
      </div>
      <QxFunctionOperation
        cRef={qxFuncOperaionRef}
        value={funValues}
        onChange={(code: string) => {
          setFunValues(code);
        }}
        appCode={appCode}
        funCode={funCode}
        isInSubForm={isInSubForm}
        style={style}
        colsTree={newColsTree}
        isScriptEditMode={isScriptEditMode}
        autofocus={autofocus}
        fieldName={fieldName}
        fieldType={fieldType}
        uniKey={uniKey}
        isFullScreen={isFullScreen}
      />
      <div className="footer">
        <Button onClick={onHandleCancel}>取消</Button>
        <Button type="primary" onClick={onHandleOk}>
          确定
        </Button>
      </div>
    </Modal>
  );
};