index.tsx 6.62 KB
import React, { useImperativeHandle, useRef, useState, useEffect } from 'react';
import { Button, Drawer, Space, Modal } from 'antd';
import { history, useLocation } from 'umi';
import { handleWindowOpen } from '@/utils';
import Draggable from 'react-draggable';

// TODO: 公共依赖
import { doBtnJump } from '@/pages/app-view/list/util';
import { RuntimeFormDrawer } from '@/pages/app-view/form';
import QxFormRender from '@/packages/qx-form-generator/src/form-render';
import { useForm } from '@qx/form-render';

const FORM_SCHEMA = {};

/* {
	"actionJson": {
		"link": {
			"funId": "SwJ7iKDN1eYLTjUmljx",
			"viewCode": "all",
			"methodCode": "LIST",
			"openType": "SELF" || "BLANK",
			"title": "数值小数"
		},
		"type": "FORM_PAGE"
	}
} */

/*表单页--弹框的形式*/
interface UrlDialogProp {
  visible: boolean;
  title: string;
  url: string;
  onVisibleChange: (visible: boolean) => void;
}

export const UrlDialog: React.FC<UrlDialogProp> = (props) => {
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    setVisible(props?.visible);
  }, [props?.visible]);

  useEffect(() => {
    props.onVisibleChange(visible);
  }, [visible]);

  return (
    <>
      <Modal
        title={props.title}
        width={'1200px'}
        visible={visible}
        bodyStyle={{ padding: '0' }} // 不能加 对其详情有影响
        onCancel={() => setVisible(false)}
        footer={false}
        destroyOnClose={true}
        modalRender={(node) => (
          <Draggable handle=".ant-modal-header">
            <div>{node}</div>
          </Draggable>
        )}
      >
        <iframe src={props.url} style={{ width: '100%', height: '500px' }} frameBorder="0" />
      </Modal>
    </>
  );
};

type ButtonFormProps = {
  cRef: any;
  title?: string;
  successCallback?: (result: any) => void;
};
const ButtonForm: React.FC<ButtonFormProps> = (props) => {
  const form = useForm();
  // const [isEdit, setEdit] = useState(false);
  const [visible, setVisible] = useState(false);
  const { pathname } = useLocation();

  const [query, setQuery] = useState<any>({});
  const [url, setUrl] = useState<string>('');
  const [urlDialogVisible, setUrlDialogVisible] = useState<boolean>(false);

  const drawerRef = useRef({
    open: () => {},
    close: () => {},
  });

  const method = {
    LIST(link: any, params: any) {
      const origin = location.href.split('#').shift(); //截取地址栏#前地址
      let URL = `/app-view/${link.appCode}/${link.formCode}/list?appId=${
        link.appId
      }&pageNum=1&pageSize=10&viewCode=${link.viewCode}&${params.join('&')}`;
      // sys下appId与_code不需要 ----晴晴 2022.7.13
      if (pathname.includes('/sys')) {
        URL = `/sys/${link.appCode}/${link.formCode}/${
          link.viewCode
        }/list?pageNum=1&pageSize=10&${params.join('&')}`;
      }
      if (link.openType === 'SELF') {
        history.push(URL);
      }
      if (link.openType === 'BLANK') {
        console.log(history, location);
        handleWindowOpen(`${origin}#${URL}`);
      }
    },
    ADD(link: object, params: any) {
      console.log(params);
      // @ts-ignore
      if (link?.appCode && link.formCode && link?.viewCode) {
        drawerRef.current.open();
      }
    },
    VIEW(link: object, params: any) {
      console.log(link, params);
    },
  };

  const getParaVal = (val: any = {}, record: any = {}) => {
    if (val.type === 'CUSTOM') {
      return val.value === 'LOCATION_PATH' ? pathname : val.value;
    }
    if (val.type === 'FIELD') {
      const dataValue = record[val.value];
      return Array.isArray(dataValue) ? dataValue.join(',') : dataValue;
    }
    return val.value;
  };

  useImperativeHandle(props.cRef, () => ({
    // 暴露给父组件
    open: (schemaItem: any, record: any) => {
      setQuery(schemaItem.link);
      const btnSchema = schemaItem;
      const params = (btnSchema.link.params || []).map((item: any) => {
        return `${item.name}=${getParaVal(item.value, record)}`;
      });
      if (btnSchema.type === 'URL') {
        //TODO,开发者模式下才有,不完善。 for 易才项目 from 史婷婷
        if (btnSchema?.link?.openType === 'DIALOG') {
          const _url = btnSchema?.link?.url;
          if (_url) {
            try {
              const _urlArr = _url.split('?');
              _urlArr[1] = params.join('&') + (_urlArr[1] ? '&' : '') + _urlArr[1];
              setUrl(_urlArr.join('?'));
              setUrlDialogVisible(true);
            } catch (e) {
              console.log(e);
            }
          }
        } else {
          doBtnJump(btnSchema, record, params);
        }
        return;
      }
      if (btnSchema.type === 'FORM_PAGE' && btnSchema.link) {
        // console.log('FORM_PAGE!!!!!!!!!!');
        const mcode = btnSchema.link.methodCode;

        if (mcode) method[mcode].call(null, btnSchema.link, params);
      }
      //setVisible(true)
    },
  }));

  const successCallback = (val: any) => {
    if (props.successCallback) {
      props.successCallback(val);
    }
  };

  const onFinish = async (data: any, error: any) => {
    console.log(data, error);
  };
  const onMount = () => {};

  return (
    <div>
      {false ? (
        <Drawer
          title="填写记录"
          placement="right"
          onClose={() => setVisible(false)}
          visible={visible}
          width={'500px'}
          keyboard={false}
          maskClosable={false}
          footer={
            <Space>
              <Button onClick={() => setVisible(false)}>关闭</Button>
              <Button type="primary" onClick={() => form.submit()}>
                保存
              </Button>
            </Space>
          }
        >
          <QxFormRender
            form={form}
            schema={FORM_SCHEMA}
            onMount={onMount}
            onFinish={onFinish}
            widgets={{}}
          />
        </Drawer>
      ) : null}
      <RuntimeFormDrawer
        appCode={query.appCode}
        viewCode={query.viewCode}
        funCode={query.formCode}
        dRef={drawerRef}
        type={'add'}
        dataId={''}
        successCallback={successCallback}
        // onCustomBtnClick={handleOpt}
      />

      {/* <RuntimeFormDialog
        // from={'rel'}
        title={'新增'}
        appCode={query.appCode}
        funCode={query.funCode}
        viewCode={query.viewCode}
        dRef={drawerRef}
        type={'add'}
        // onAfterSave={props.onAfterSave}
      /> */}
      <UrlDialog
        visible={urlDialogVisible}
        onVisibleChange={(visible: boolean) => {
          setUrlDialogVisible(visible);
        }}
        title={props?.title || ''}
        url={url}
      />
    </div>
  );
};

export default ButtonForm;