index.tsx 5.81 KB
import React, { useEffect, useState, useRef } from 'react';
import { useLocation, useParams } from 'umi';
import { PoweroffOutlined, SaveOutlined } from '@ant-design/icons';
import _ from 'lodash';
import { Button } from 'antd';
import HeadButton from '../form/components/head-button';
import CustomButton from '@/src/pages/list-view/components/custom-button';
import RuntimeForm from '@/src/pages/form/components/runtime-form';
import { getDetailId } from './services';

import './index.less';

const Index: React.FC = () => {
  const { appCode, funCode } = useParams<{
    appCode: string;
    funCode: string;
  }>();
  // @ts-ignore
  const { query } = useLocation();
  const [dataId, setDataId] = useState('');
  const [headConfig, setHeadConfig] = useState<any>({});
  const [type, setType] = useState('view');
  const [saveLoading, setSaveLoading] = useState(false);
  const detailRef = useRef<any>(null);
  const [btnData, setBtnData] = useState([]);
  const [selectData, setSelectData] = useState({});
  const [formKey, setFormKey] = useState('1');

  useEffect(() => {
    if (appCode && funCode) {
      getDetailId(appCode, funCode).then((res) => {
        setDataId(res);
      });
    }
  }, [appCode, funCode]);

  const handleBtnClick = _.debounce(
    (btn) => {
      const { code } = btn;
      switch (code) {
        // case 'ADD':
        //   break;
        // case 'VIEW':
        //   break;
        // case 'DELETE':
        //   break;
        // case 'EXPORT':
        //   break;
        // case 'IMPORT':
        //   break;
        case 'EDIT': // 详情视图页 只会出现编辑与自定义按钮
          setType('edit');
          break;
        default:
          //const btnSchemas = ;
          setBtnData(_.cloneDeep(btn));
          setSelectData({
            ids: [dataId],
            record: { id: dataId },
            keys: [],
          });
      }
    },
    1000,
    {
      leading: true,
      trailing: false,
    },
  );

  const refresh = (data: any) => {
    try {
      const { initData } = detailRef.current || {};
      if (_.isFunction(initData)) {
        initData(!!data);
      }
    } catch (e) {}
  };

  const onAfterSave = () => {
    setSaveLoading(false);
    setType('view');
  };

  // const transferViewType = () => {
  //   const code = funCode
  //   // 转详情
  //   changeToList(appCode, code).then(() => {
  //     history.replace(`/app-view/${appCode}/${code}/list?_code=${query._code}&appId=${query.appId}&viewCode=${query.viewCode || ''}`)
  //   }).catch(e => {
  //     if (e.msg) {
  //       message.error(e.msg)
  //     }
  //   })
  // }

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

  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, code }: { flag: string; code: string }) =>
            data[flag] && code !== 'DELETE',
        );
        setHeadConfig({
          buttons: resButtons,
          ...other,
        });
      }
    }
  };

  return (
    <div className={`qx-app-detail_show qx-app-detail_show--view`}>
      <div
        style={{
          textAlign: 'right',
          ...(type === 'edit' ||
          (type === 'view' && !_.isEmpty(headConfig.buttons))
            ? { padding: '5px 10px', borderBottom: '1px solid #eee' }
            : null),
        }}
      >
        {type === 'view' ? (
          <HeadButton
            buttons={headConfig.buttons}
            handleBtnClick={handleBtnClick}
          />
        ) : // (
        //   (headConfig.buttons || []).map((item: any) => (
        //     <QxButton key={item.code} type={item.type} color={item.color} icon={item.icon} onClick={() => {
        //       handleBtnClick(item)
        //     }}>{item.name}</QxButton>
        //   ))
        // )
        null}
        {type === 'edit' ? (
          <>
            <Button
              loading={saveLoading}
              type={'primary'}
              icon={<SaveOutlined />}
              style={{ marginRight: '10px' }}
              onClick={() => {
                setSaveLoading(true);
                detailRef.current.doSave(() => setSaveLoading(false));
              }}
            >
              保存
            </Button>
            <Button
              type="default"
              icon={<PoweroffOutlined />}
              onClick={() => setType('view')}
            >
              关闭
            </Button>
          </>
        ) : null}
        {/* <Button
          type="default"
          icon={<PoweroffOutlined/>}
          onClick={() => transferViewType()}
        >关闭
        </Button> */}
      </div>
      {/*// TODO 写两个组件处理不太好,后续需优化*/}
      {dataId && type === 'view' ? (
        <RuntimeForm
          key={formKey}
          cRef={detailRef}
          appCode={appCode}
          funCode={funCode}
          dataId={dataId}
          viewCode={'all'}
          type={type}
          params={{ appCode, funCode }}
          handleBySchemaAndData={handleBySchemaAndData}
          onAfterSave={onAfterSave}
          handleReload={handleReload}
          mode="detail"
        />
      ) : null}
      {dataId && type === 'edit' ? (
        <RuntimeForm
          cRef={detailRef}
          appCode={appCode}
          funCode={funCode}
          dataId={dataId}
          viewCode={'all'}
          type={type}
          params={{ appCode, funCode }}
          onAfterSave={onAfterSave}
          mode="detail"
        />
      ) : null}
      <CustomButton
        refresh={refresh}
        _btnData={btnData}
        _selectData={selectData}
        appCode={appCode}
        funCode={funCode}
        viewCode={'all'}
      />
    </div>
  );
};

export default Index;