subform-edit.tsx 5.69 KB
import React, { useEffect, useState } from 'react';
import { getSubEditSchema, saveSubData } from '../services';
import { useForm } from '@qx/form-render';
import { message, Modal, Button } from 'antd';
import { isEqual } from 'lodash';
import { ExclamationCircleOutlined } from '@ant-design/icons';
// TODO:
import QxFormRender from '@/packages/qx-form-generator/src/form-render';

const { confirm } = Modal;

interface SubformEditProps {
  batchEditParam: {
    appCode: string;
    funCode: string;
    fieldKey: string;
    value: any[];
    relAppCode: string;
    relFunCode: string;
    $id: string;
  };
  saveCallBack: (id: string, value: any[]) => void;
}

const SubformEdit: React.FC<SubformEditProps> = (props) => {
  const form = useForm();
  const { batchEditParam, saveCallBack } = props;
  const [visible, setVisible] = useState(false);
  const [subSchema, setSubSchema] = useState<any>();
  const [loading, setLoading] = useState(false);

  const loopItems = (schema: any, fieldKey: string) => {
    const properties = schema?.properties || {};
    // const {appCode, funCode} = batchEditParam
    Object.keys(properties).forEach((key) => {
      const config = properties[key];
      config.readOnlyWidget = 'readOnlyWidget';
      const {
        widget,
        props: { column },
      } = config;
      if (column && column.show === false) {
        delete properties[key];
      }
      if (['qxRichText'].includes(widget)) {
        delete properties[key];
      }
      config.belongRelForm = true;
      config.relformKey = fieldKey;
      config.propertyKey = key;
      if (config?.widget === 'relSelector' && config?.props?.mode === 'TABLE') {
        config.props.mode = 'TAG';
      }
      if (widget === 'subform') {
        // 关联表内的子表,后台返回记录数量,改为number类型,不影响存储,因为关联记录只存储记录id
        config.type = 'number';
        config.readOnly = true;
        config.widget = 'subInTable';
        config.props.isSub = true;
        delete config.items;
      }
      if (['relField', 'qxBizNo'].includes(config.widget)) {
        config.readOnly = true;
      }
      if (
        widget === 'relSelector' ||
        widget === 'userSelector' ||
        widget === 'orgSelector'
      ) {
        if (!config.qxProps) {
          config.qxProps = {};
        }
        config.qxProps.currentAppCode = batchEditParam.relAppCode;
        config.qxProps.currentFunCode = batchEditParam.relFunCode;
        config.qxProps.appCode = batchEditParam.appCode;
        config.qxProps.funCode = batchEditParam.funCode;
        config.qxProps.currentViewCode = fieldKey;
        config.qxProps.isRel = true;
        config.qxProps.fieldName = key;
      }
      if (config.$base) {
        config.readOnly = true; // 系统字段不可编辑
      }
    });
  };

  useEffect(() => {
    const { appCode, funCode, fieldKey, value } = batchEditParam;
    if (!appCode) return;
    const _schema = {
      type: 'object',
      properties: {},
    };
    _schema.properties[fieldKey] = {
      title: '',
      type: 'array',
      widget: 'virtualList',
      width: '100%',
      propertyKey: fieldKey,
      default: value,
      items: {},
    };
    getSubEditSchema(appCode, funCode, fieldKey).then((res) => {
      loopItems(res, fieldKey);
      _schema.properties[fieldKey].items = res;
      setSubSchema(_schema);
      setVisible(true);
    });
  }, [batchEditParam]);

  const onFinish = (formData: any, errors: any) => {
    console.log(errors);
    setLoading(true);
    const { appCode, funCode, fieldKey } = batchEditParam;
    // if (errors.length === 0) {
    saveSubData(appCode, funCode, fieldKey, formData[fieldKey]).then((res) => {
      setLoading(false);
      message.success('保存成功');
      setVisible(false);
      saveCallBack(
        batchEditParam.$id,
        (formData[fieldKey] || []).map((item: any) => item.id),
      );
    });
    // }
  };

  const handleCancel = () => {
    const newValue = form.getValues()?.[batchEditParam.fieldKey];
    (newValue || []).forEach((item: any, index: number) => {
      const _item = batchEditParam.value?.[index];
      Object.keys(item).forEach((key) => {
        if (
          Array.isArray(item[key]) &&
          item[key].length === 0 &&
          _item[key] === undefined
        ) {
          delete item[key];
        }
      });
    });
    (newValue || []).forEach((item: { orginIdx?: number }) => {
      delete item.orginIdx;
    });
    const _isEqual = isEqual(newValue, batchEditParam.value);
    if (_isEqual) {
      setVisible(false);
    } else {
      confirm({
        // title: '取消后编辑数据将不被保存,确认取消?',
        content: '取消后编辑数据将不被保存,确认取消?',
        icon: <ExclamationCircleOutlined />,
        onOk() {
          setVisible(false);
        },
        onCancel() {},
      });
    }
  };

  return (
    <Modal
      title={'表格编辑模式'}
      // onOk={() => form.submit()}
      // onCancel={handleCancel}
      visible={visible}
      width={900}
      onCancel={() => setVisible(false)}
      bodyStyle={{ maxHeight: '550px', overflow: 'auto', padding: '0 10px' }}
      destroyOnClose={true}
      footer={
        <div>
          <Button
            style={{ marginRight: '10px' }}
            onClick={handleCancel}
            loading={loading}
          >
            取消
          </Button>
          <Button
            type="primary"
            onClick={() => {
              form.submit();
            }}
            loading={loading}
          >
            确定
          </Button>
        </div>
      }
    >
      <QxFormRender onFinish={onFinish} form={form} schema={subSchema} />
    </Modal>
  );
};

export default SubformEdit;