ReportEditForm.js 7.73 KB
Newer Older
陈龙's avatar
陈龙 committed
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
/*
 ** 报表的编辑、新增表单
 ** create by ChenLong on 2022/8/10
 ** 功能路径:src\pages\product\ReportsManage\ReportEditForm.js
 ** 菜单参数列表:*变量名*(变量说明,数据类型,是否必填,取值范围)
 **/
import React, { useEffect, useState, useContext } from 'react';
import {
  Form,
  Input,
  DatePicker,
  InputNumber,
  Row,
  Col,
  Button,
  message,
  Select,
  ConfigProvider,
} from 'antd';
import moment from 'moment';
import { submitReportData } from '../api/service/report';
import FileUpload from './Components/fileUpload/fileUpload';
import { reportService } from '../api';
import { isSelect, returnOptions, returnRows, returnCols } from './utils/utils';
import style from './ReportEditForm.less';

const { Option } = Select;
const { TextArea } = Input;
// 类型
30
const USER_ID = window?.globalConfig?.userInfo?.OID || 0;
陈龙's avatar
陈龙 committed
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
const TEXT_ARRAY = ['文本', '标签'];
const TEXTAREA_ARRAY = ['多行文本'];
const DATE_PICKER_ARRAY = ['日期'];
const DATE_TIME_PICKER_ARRAY = ['日期时刻'];
const DATE_TYPE = ['日期', '日期时刻']; // 用来匹配是否需要转为日期对象;
const NUMBER_ARRAY = ['数值', '数值标签'];
const FILE_ARRAY = ['附件'];
// 形态对应组件

// 对应关系

/**
 * @description: 函数描述
 * @date: 2022/8/10
 * @author: ChenLong
 * @params: reportDetails 各个字段的配置列表
 *           data 与reportDetails对应的值
 */
const ReportEditForm = ({ reportDetails, reportData, onCancel, reportName, modalType }) => {
  // if (!reportData || Object.keys(reportData).length === 0) return <>未传递表单数据</>;
  const [fileAlias, setFileAlias] = useState([]); // 附件需要单独处理提交的数据
  const [form] = Form.useForm();
  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
  const prefixCls = getPrefixCls();
  /*  const formItemLayout = {
      labelCol: {
        span: 8,
      },
      wrapperCol: {
        span: 16,
      },
    };*/
  // 数值类的后端会处理再返回,故无序处理精度问题
  const handleDate = (reportDetails, data) => {
    let _data = { ...data };
    reportDetails.forEach((item) => {
      if (DATE_TYPE.includes(item.type)) {
68
        _data[item.fieldAlias] = data[item.fieldAlias] ? moment(data[item.fieldAlias]) : null;
陈龙's avatar
陈龙 committed
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
      }
    });
    return _data;
  };
  const componentMap = (config) => {
    if (DATE_TIME_PICKER_ARRAY.includes(config.type)) {
      return <DatePicker showTime readonly={config.isReadOnly} />;
    } else if (DATE_PICKER_ARRAY.includes(config.type)) {
      return <DatePicker disabled={config.isReadOnly} />;
    } else if (NUMBER_ARRAY.includes(config.type)) {
      return <InputNumber disabled={config.isReadOnly} />;
    } else if (FILE_ARRAY.includes(config.type)) {
      return <FileUpload schema={{ renderTo: 'File' }} disabled={config.isReadOnly} />;
    } else if (TEXTAREA_ARRAY.includes(config.type)) {
      let _rows = returnRows(config.configItems);
      return <TextArea rows={_rows} disabled={config.isReadOnly} />;
    } else {
      if (isSelect(config.configItems)) {
        let options = returnOptions(config.configItems);
        if (options) {
          return (
            <Select disabled={config.isReadOnly}>
              {options.map((item) => (
                <Option value={item}>{item}</Option>
              ))}
            </Select>
          );
        }
      }
      return <Input disabled={config.isReadOnly} />;
    }
  };
  const submitReportForm = () => {
    form.validateFields().then((values) => {
      let _data = values;
      let final = [];
      Object.keys(_data).forEach((key) => {
        let value = reportData[key];
        let _value = _data[key];
        if (moment.isMoment(_data[key])) {
          _value = moment(_data[key]).format('YYYY-MM-DD HH:mm:ss');
        }
        if (value !== _value) {
          if (fileAlias.includes(key)) {
            _value = _value
              ? JSON.parse(_value)
                  .reduce((final, curr) => {
                    final.push(curr.sourcePath);
                    return final;
                  }, [])
                  .join(',')
              : '';
          }
          let _finalData = {
            fieldAlias: key,
124
            fieldValue: _value === null ? _value : String(_value),
陈龙's avatar
陈龙 committed
125 126
          };
          if (modalType === '编辑') {
127
            _finalData.key = reportData.key;
陈龙's avatar
陈龙 committed
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
          }
          final.push(_finalData);
        }
      });
      if (modalType === '新增') {
        reportService
          .addReportData({
            reportName: reportName,
            userId: USER_ID,
            reportDatas: final,
          })
          .then((res) => {
            if (res.code === 0) {
              message.success('保存成功!');
              onCancel();
            } else if (res.code === -1) {
              message.error(res.msg);
            } else if (res.code === -2) {
              message.error('系统故障,请找管理员查看故障!');
            }
          });
      }
      if (modalType === '编辑') {
        submitReportData(
          {},
          {
            editDatas: final,
            reportName: reportName,
            userId: USER_ID,
          },
        ).then((res) => {
          if (res.code === 0) {
            message.success('保存成功!');
            onCancel();
          } else if (res.code === -1) {
            message.error(res.msg);
          } else if (res.code === -2) {
            message.error('系统故障,请找管理员查看故障!');
          }
        });
      }
    });
  };
  useEffect(() => {
    if (reportDetails && reportDetails.length) {
      let _fileAlias = [...fileAlias];
      reportDetails.forEach((item) => {
        if (item.type === '附件') _fileAlias.push(item.fieldAlias);
      });
      setFileAlias(_fileAlias);
    }
  }, [reportDetails]);
  useEffect(() => {
    if (reportData && Object.keys(reportData).length)
      form.setFieldsValue(handleDate(reportDetails, reportData));
  }, [reportData]);
  return (
    <div className={style.reportEditForm} style={{ position: 'relative' }}>
      <div>
        <Form form={form}>
          <Row style={{ overflowY: 'scroll', maxHeight: 'calc(100vh - 300px)' }}>
            {reportDetails &&
              reportDetails
                .filter((config) => {
                  if (modalType === '新增' && config.isReadOnly) return false;
                  return config;
                })
                .map((config) => {
                  // return <Col span={returnCols(config.configItems) * 8} key={config.fieldAlias}>
                  return (
                    <div
                      style={{ width: `${returnCols(config.configItems) * 33.3}%` }}
                      key={config.fieldAlias}
                    >
                      <Form.Item
                        label={config.fieldAlias}
                        name={config.fieldAlias}
                        rules={[
                          {
                            required: config.isRequired,
                            message: `${config.fieldAlias}必填`,
                          },
                        ]}
                      >
                        {componentMap(config)}
                      </Form.Item>
                    </div>
                  );
                })}
          </Row>
          <Row>
            <Col span={24} style={{ textAlign: 'right' }}>
              {/*<Form.Item style={{textAlign:'right'}}>*/}
              <Button
                style={{ position: 'sticky', bottom: 0 }}
                type={'primary'}
                onClick={submitReportForm}
              >
                提交
              </Button>
              {/*</Form.Item>*/}
            </Col>
          </Row>
        </Form>
      </div>
    </div>
  );
};
export default ReportEditForm;