index.tsx 20 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 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
import React, { useEffect, useImperativeHandle, useRef, useState } from 'react';
import { CloseOutlined } from '@ant-design/icons';
import { useForm } from '@qx/form-render';
import { Button, Card, Divider, Drawer, Modal, Space, Spin } from 'antd';
import Draggable from 'react-draggable';
import { history, useLocation, useParams } from 'umi';
import HeadButton from './components/head-button';
import RuntimeForm from './components/runtime-form';
import { getData, getRelData, detailRelSchema } from './services';
import { handleViewFormSchema } from './util';
import _ from 'lodash';
// TODO:
import QxFormRender from '@/packages/qx-form-generator/src/form-render';
import QxIcon from '@/packages/qx-icon';

import './index.less';

const RuntimeFormPage: React.FC = () => {
  const { appCode, funCode, type } = useParams<any>();
  // @ts-ignore
  const { query } = useLocation();
  const { viewCode, id } = query;
  const cRef = useRef({
    doSave: () => {},
  });

  const handleCallback = () => {};

  return (
    <>
      <Card
        bordered={false}
        className="view-card"
        style={{ margin: '10px auto', maxWidth: 1000 }}
      >
        <RuntimeForm
          cRef={cRef}
          dataId={id}
          type={type}
          appCode={appCode}
          funCode={funCode}
          viewCode={viewCode}
          submitCallback={handleCallback}
          mode="page"
        />
        {type !== 'view' ? (
          <Button
            type="primary"
            onClick={() => {
              cRef.current.doSave();
              history.goBack();
            }}
          >
            保存
          </Button>
        ) : null}
      </Card>
    </>
  );
};

export const PageCtrlTypes = {
  add: '新增',
  edit: '编辑',
  view: '查看',
};

interface RuntimeFormDrawerProp {
  from?: 'rel' | 'button' | 'button-rel' | string | undefined;
  title?: string;
  dRef?: any; //TODO
  type: string; //add,edit,view
  dataId?: string | undefined;
  params?: Record<string, any>;
  appCode: string;
  funCode: string;
  viewCode: string;
  excessData?: any;
  childFun?: boolean;
  radioValue?: string;
  parentfunCode?: string;
  parentappCode?: string;
  modelId?: string;
  datasetItem?: any;
  successCallback?: (result: any) => void;
  onCustomBtnClick?: (btn: any, record?: any, from?: string) => void;
  referQuery?: { appCode?: string; funCode?: string; fieldName?: string };
  viewType?: string;
  parentId?: string;
  currDataItemCtrl?: any;
}

/*表单页--抽屉的形式*/
export const RuntimeFormDrawer: React.FC<RuntimeFormDrawerProp> = (props) => {
  const {
    appCode,
    funCode,
    viewCode,
    viewType,
    parentId,
    modelId,
    datasetItem,
    currDataItemCtrl,
  } = props;
  const { type, dataId } = props;
  const [headConfig, setHeadConfig] = useState<any>({});

  const [formKey, setFormKey] = useState('1');
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [isFull, setIsFull] = useState(false);
  const cRef = useRef({
    doSave: (res: (res: any) => void) => {
      console.log(res);
    },
  });
  useEffect(() => {
    setHeadConfig({});
  }, [type]);

  const handleReload = () => {
    setFormKey(`${new Date().getTime()}`);
  };

  const handleCallback = (result: {
    success: boolean;
    close?: boolean;
    reload?: any;
  }) => {
    setLoading(false);
    if (result && result.success) {
      if (result.reload) {
        handleReload();
      } else if (result.close !== false) {
        setVisible(false);
      }
      if (props.successCallback) {
        props.successCallback(result);
      }
    }
  };

  const doSave = () => {
    setLoading(true);
    const { btn } = currDataItemCtrl;
    if (btn.needConfirm && btn.confirmContent) {
      Modal.confirm({
        content: btn.confirmContent,
        cancelText: '取消',
        okText: '确定',
        onOk: () => {
          cRef.current.doSave((res) => {
            if (res?.success === false) {
              setLoading(false);
            }
          });
        },
        onCancel: () => {
          setLoading(false);
        },
      });
    } else {
      cRef.current.doSave((res) => {
        if (res?.success === false) {
          setLoading(false);
        }
      });
    }
  };

  useImperativeHandle(props.dRef, () => ({
    // 暴露给父组件
    open: () => {
      setVisible(true);
    },
    close: () => {
      setLoading(false);
      setVisible(false);
    },
    runtimeFormRef: cRef,
  }));

  // const handleSchema = (_schema) => {
  //   if (type === 'view') {
  //     setHeadConfig(_schema.ext || { autoSave: true })
  //   }
  // }

  const handleBySchemaAndData = (_schema: any, data: any) => {
    if (type === 'view') {
      if (!_schema.ext) {
        setHeadConfig({ autoSave: true });
      } else {
        const { buttons = [], ...other } = _schema.ext;
        const resButtons = buttons.filter(
          ({ flag }: { flag: string }) => data[flag],
        );
        setHeadConfig({
          buttons: resButtons,
          ...other,
        });
      }
    }
  };

  const handleBtnClick = (button: any) => {
    if (props.onCustomBtnClick) {
      props.onCustomBtnClick(button, { id: dataId }, type);
    }
  };

  useEffect(() => {
    if (!visible) {
      setIsFull(false);
      //删除富文本创建的dom元素
      let data: any = document.getElementsByClassName('qx-append-rich-none');
      data = [].slice.apply(data);
      if (data?.length) {
        for (let i = 0; i < data.length; i++) {
          document.body.removeChild(data[i]);
        }
      }
    }
  }, [visible]);

  return (
    <>
      <Drawer
        title={props.title ? props.title : PageCtrlTypes[type || 'add']}
        placement="right"
        width={isFull ? '100vw' : '1100px'}
        className={`ant-drawer-form ${
          type === 'view' ? 'ant-drawer--view' : ''
        }`}
        onClose={() => setVisible(false)}
        visible={visible}
        destroyOnClose={true}
        maskClosable={type === 'view'}
        closable={false}
        footerStyle={{ height: '56px', textAlign: 'right' }}
        footer={
          type !== 'view' || headConfig.autoSave === false ? (
            <Button type="primary" onClick={doSave} loading={loading}>
              保存
            </Button>
          ) : null
        }
        extra={
          <Space>
            {type === 'view' && props.onCustomBtnClick ? (
              <HeadButton
                buttons={headConfig.buttons}
                handleBtnClick={handleBtnClick}
              />
            ) : null}
            {/* 如有必要,可将注释放开(回滚)*/}
            {/*<Button*/}
            {/*  type={'text'}*/}
            {/*  icon={<QxIcon type={isFull ? 'icon-narrow' : 'icon-enlarge'} />}*/}
            {/*  onClick={(e: any) => {*/}
            {/*    e.target.parentNode.blur();*/}
            {/*    setIsFull(!isFull);*/}
            {/*  }}*/}
            {/*  style={{ color: 'rgba(0,0,0,0.45)', transform: 'scale(0.9)' }}*/}
            {/*/>*/}
            {/*<Button*/}
            {/*  type={'text'}*/}
            {/*  icon={<CloseOutlined />}*/}
            {/*  onClick={() => setVisible(false)}*/}
            {/*  style={{ color: 'rgba(0,0,0,0.45)', transform: 'scale(0.9)' }}*/}
            {/*/>*/}
            <div
              className={'qx-form-drawer-right-top-icon'}
              onClick={() => {
                setIsFull(!isFull);
              }}
            >
              <QxIcon type={isFull ? 'icon-narrow' : 'icon-enlarge'} />
            </div>
            <div
              className={'qx-form-drawer-right-top-icon'}
              onClick={() => setVisible(false)}
            >
              <CloseOutlined style={{ color: 'rgba(0, 0, 0, 0.45)' }} />
            </div>
          </Space>
        }
      >
        {visible ? (
          <RuntimeForm
            cRef={cRef}
            key={formKey}
            from={props.from}
            dataId={dataId}
            type={type}
            appCode={appCode}
            funCode={funCode}
            viewCode={viewCode}
            treeViewType={viewType || ''}
            parentId={parentId || ''}
            modelId={modelId}
            datasetItem={datasetItem}
            handleBySchemaAndData={handleBySchemaAndData}
            excessData={props.excessData}
            childFun={props.childFun}
            radioValue={props.radioValue}
            parentfunCode={props.parentfunCode}
            parentappCode={props.parentappCode}
            submitCallback={handleCallback}
            mode="drawer"
            handleReload={handleReload}
          />
        ) : null}
      </Drawer>
    </>
  );
};

interface RuntimeFormDialogProp extends RuntimeFormDrawerProp {
  schema?: any;
  width?: string | number;
  onSave?: (data: any) => void;
  isApprove?: any;
  onAfterSave?: (id?: string) => void;
  isRel?: any;
  customResult?: any;
  clearSchema?: () => void;
}

/*表单页--弹框的形式*/
export const RuntimeFormDialog: React.FC<RuntimeFormDialogProp> = (props) => {
  const {
    appCode,
    funCode,
    viewCode,
    schema,
    onAfterSave,
    isRel,
    type,
    dataId,
    customResult,
    clearSchema,
  } = props;
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [initialLoading, setInitialLoading] = useState<boolean>(false);
  const cRef = useRef({
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    doSave: (fun1: any, fun2: any) => {},
  });

  const handleCallback = (result: { success: boolean }) => {
    setLoading(false);
    if (result && result.success) {
      if (props.successCallback) {
        setVisible(true);
        props.successCallback(result);
      } else {
        setVisible(false);
      }
    } else {
      setVisible(false);
    }
  };

  const doSave = () => {
    setLoading(true);
    cRef.current.doSave(
      () => {},
      () => {
        setLoading(false);
      },
    );
  };

  useImperativeHandle(props.dRef, () => ({
    // 暴露给父组件
    open: () => {
      setVisible(true);
      setInitialLoading(true);
      setTimeout(() => {
        setInitialLoading(false);
      }, 200);
    },
    close: () => {
      setLoading(false);
      setVisible(false);
    },
    setLoading: (isLoading: boolean) => {
      setLoading(isLoading || false);
    },
  }));

  useEffect(() => {
    if (!visible && clearSchema) clearSchema();
  }, [visible]);

  return (
    <>
      <Modal
        title={
          <div className={'rel-more_title'}>
            {props.title ? props.title : PageCtrlTypes[type || 'add']}
          </div>
        }
        width={props.width ? props.width : '864px'}
        bodyStyle={type !== 'view' ? { padding: '20px' } : {}} // 不能加 对其详情有影响
        onCancel={() => setVisible(false)}
        onOk={doSave}
        visible={visible}
        destroyOnClose={true}
        footer={
          type !== 'view'
            ? [
                <Button onClick={() => setVisible(false)}>关闭</Button>,
                <Button type="primary" onClick={doSave} loading={loading}>
                  保存
                </Button>,
              ]
            : [<Button onClick={() => setVisible(false)}>关闭</Button>]
        }
        className={'runtime-single-modal'}
        modalRender={(node) => (
          <Draggable handle=".ant-modal-header">
            <div>{node}</div>
          </Draggable>
        )}
      >
        {initialLoading && (
          <div style={{ textAlign: 'center', paddingTop: '10px' }}>
            <Spin spinning={initialLoading} />
          </div>
        )}
        <RuntimeForm
          key={dataId}
          cRef={cRef}
          from={props.from}
          dataId={dataId}
          type={type}
          params={props.params}
          appCode={appCode}
          funCode={funCode}
          approveData={props?.isApprove}
          viewCode={viewCode}
          schema={schema}
          onSave={props.onSave}
          customResult={customResult}
          referQuery={props.referQuery}
          submitCallback={handleCallback}
          onAfterSave={onAfterSave}
          mode="dialog"
          isRel={isRel}
        />
      </Modal>
    </>
  );
};

interface RelMoreModalProp {
  cRef?: any;
}

/*表单页--关联记录(多)/子表的弹出框*/
export const RelMoreModal: React.FC<RelMoreModalProp> = (props) => {
  const form = useForm();
  // const relMoreFormRef = useRef<any>();
  const [isFullscreen, setFullscreen] = useState<boolean>(false);
  const [formSchema, setSchema] = useState<API.Schema>({});
  const [initialSchema, setInitialSchema] = useState<API.Schema>({});
  const [visible, setVisible] = useState(false);
  const [params, setParams] = useState<any>(); //点击时传递的参数

  const changeSchema = (_schema: any) => {
    const originSchema = _.cloneDeep(_schema);
    if (
      originSchema &&
      originSchema.properties &&
      Object.keys(originSchema.properties).length
    ) {
      Object.keys(originSchema.properties).forEach((it: any) => {
        const inner = originSchema.properties[it];
        if (
          inner &&
          inner.items &&
          inner.items.properties &&
          Object.keys(inner.items.properties).length
        ) {
          inner.isFullScreen = true; // 全屏状态时表格不设置最大高度
          Object.keys(inner.items.properties).forEach((o: any) => {
            if (inner.items.properties[o]?.props?.column?.width) {
              // delete inner.items.properties[o].props.column.width
              // todo 待优化 这里要考虑调整VirtualList组件的取值逻辑(没有width时,VirtualList组件默认渲染'170px')
              inner.items.properties[o].props.column.width = '220';
            }
          });
        }
      });
    }
    setSchema({ ...originSchema });
  };

  useEffect(() => {
    // console.log(formSchema)
    if (visible) {
      if (isFullscreen) {
        // 进入全屏状态时  更改表头的宽度
        changeSchema(formSchema);
      } else {
        // 退出全屏时
        setSchema({ ...initialSchema });
      }
    }
  }, [visible, isFullscreen]);

  const handleRefSchema = (_schema: any) => {
    Object.keys(_schema.properties).forEach((item) => {
      // _schema.properties[item].title = '';
      // _schema.properties[item].description = '';
      let property = _schema.properties[item];
      property.title = '';
      property.description = '';
      if (property.widget === 'relField' && property.props.render) {
        const renderData = property.props.render;
        renderData.title = '';
        renderData.description = '';
        delete property.props;
        property = { ...property, ...renderData };
      }
      _schema.properties[item] = property;
      // if(widget === 'subform'){
      //   console.log(_schema);
      //   //子表
      //     _schema.properties[item].title = '';
      //     _schema.properties[item].description = '';
      // }
      // else{
      //   //关联记录
      //   const inner = _schema.properties[item].properties
      //   if (inner) {
      //     Object.keys(inner).forEach((_it: any) => {
      //       inner[_it].title = '';
      //       inner[_it].description = '';
      //     })
      //   }
      // }
    });
  };
  const getFormData = async (_schema: any, data: any) => {
    const { appCode, funCode, viewCode, dataId, fieldName, widget } = data;
    let result;
    if (widget === 'subform') {
      result = await getData({ appCode, funCode, viewCode, id: dataId }); // 这里获取的是点击"编辑"图标时的所有数据
    } else {
      const res = await getRelData(
        fieldName,
        appCode,
        funCode,
        viewCode,
        'ADD',
        {
          data: { ids: data.idArr },
        },
      );
      result = {
        id: dataId,
        [fieldName]: data.idArr,
        [fieldName + '_info_']: res,
      };
    }
    handleViewFormSchema(
      _schema,
      result,
      {
        appCode,
        funCode,
        viewCode,
        from: undefined,
      },
      false,
    );
    form.setValues(result); // 更新值,解决子表点击数据不更新问题
    setSchema({ ..._schema });
    setInitialSchema({ ..._schema });
    setVisible(true);
  };
  const getTableSchema = async (data: any) => {
    const _schema = await getRelSchema(
      data.appCode,
      data.funCode,
      data.fieldName,
    ); //这个接口拿到的是筛选过的schema
    if (_schema) {
      handleRefSchema(_schema); //将标题和描述赋空
      getFormData(_schema, data);
    }
  };
  useImperativeHandle(props.cRef, () => ({
    open: (values: any) => {
      setSchema({});
      setInitialSchema({});
      setParams(values);
      getTableSchema(values);
    },
    close: () => {
      setVisible(false);
    },
  }));
  return (
    <div className={'rel-more'}>
      <Modal
        width={800}
        onCancel={() => setVisible(false)}
        visible={visible}
        footer={[<Button onClick={() => setVisible(false)}>关闭</Button>]}
        className={`rel-more_modal ${
          isFullscreen ? 'rel-more_modal_full' : ''
        }`}
        destroyOnClose={true}
        modalRender={(node) => (
          <Draggable
            handle=".drag-handler"
            disabled={isFullscreen}
            position={isFullscreen ? { x: 0, y: 0 } : undefined}
          >
            <div>{node}</div>
          </Draggable>
        )}
      >
        <div style={{ background: 'white' }}>
          <div
            className={'drag-handler'}
            style={{ padding: '12px 24px 0 24px' }}
          >
            <div
              style={{
                display: 'inline-block',
                fontSize: 16,
                fontWeight: 500,
                marginTop: 5,
              }}
              className={'rel-more_title'}
            >
              {params?.modalTitle}
            </div>
            <Button
              type="text"
              icon={
                <QxIcon type={isFullscreen ? 'icon-narrow' : 'icon-enlarge'} />
              }
              onClick={() => setFullscreen(!isFullscreen)}
              style={{ float: 'right', right: 32 }}
            />
          </div>
          <Divider style={{ margin: '5px 0' }} />
          {params?.widget === 'subform' ? (
            <div className={'child-form'}>
              <QxFormRender form={form} schema={formSchema} />
            </div>
          ) : null}
          {params?.widget === 'relSelector' ? (
            <div className={'rel-more-form'}>
              <QxFormRender form={form} schema={formSchema} />
            </div>
          ) : null}
        </div>
      </Modal>
    </div>
  );
};

interface RelSingleModalProp {
  cRef?: any;
}

/*表单页--关联记录(单)的弹出框*/
export const RelSingleModal: React.FC<RelSingleModalProp> = (props) => {
  const [detailSchema, setDetailSchema] = useState<any>({});
  const [dataInfo, setDataInfo] = useState<any>({}); //传过来的参数
  const [relCode, setRelCode] = useState<any>({}); //relAppCode、relFunCode
  const formRef = useRef({
    open: () => {},
    close: () => {},
  });

  const getSchema = async (data: any) => {
    if (!data.params) {
      return;
    }
    detailRelSchema(
      data.params.appCode,
      data.params.funCode,
      data.params.fieldName,
    ).then((res) => {
      // console.log(res);
      setRelCode({ relAppCode: res?.appCode, relFunCode: res?.funCode });
      setDetailSchema(res || {});
      formRef.current.open();
    });
  };

  useImperativeHandle(props.cRef, () => ({
    // 暴露给父组件
    open: (values: {}) => {
      setDataInfo(values);
      getSchema(values);
    },
    close: () => {},
  }));
  return (
    <>
      {dataInfo.relFormId ? (
        <RuntimeFormDialog
          from={'rel'}
          title={dataInfo.modalTitle ? dataInfo.modalTitle : '详情'}
          dataId={dataInfo.relFormId}
          appCode={relCode?.relAppCode}
          funCode={relCode?.relFunCode}
          // appCode={dataInfo.appCode}
          // funCode={dataInfo.funCode}
          viewCode={dataInfo.fieldName}
          params={dataInfo.params}
          schema={detailSchema}
          dRef={formRef}
          type={'view'}
        />
      ) : null}
    </>
  );
};

export default RuntimeFormPage;