antd react hooks From表单格式模板

import {
  Row,
  Col,
  Form,
  Input,
  Button,
  Upload,
  Spin,
  DatePicker,
  message,
  Image,
  Modal
} from 'antd';
import {
  PlusOutlined, ExclamationCircleOutlined
} from '@ant-design/icons';

import React, { useState, useEffect, useRef } from 'react';
import moment from 'moment'
import PanelTitle from '@/components/PanelTitle'
import BraftEditor from 'braft-editor';
import { v4 as uuidv4 } from 'uuid';
import 'braft-editor/dist/index.css';
import UploadComponent from "./component";
import styles from './index.less';
import { GiftDetail, CreateGift, UpdateGift } from '@/services/pointsCenter';
const commonUploadUrl = requestUrl + '/api/common/CommonUpload';
import { requestUrl, getUploadFileType, MessageError, MessageSuccess } from '../../../utils/utils';
const dateFormat = 'YYYY/MM/DD';

const { RangePicker } = DatePicker;

const editGift = (props) => {
  const { history, location } = props;

  const { confirm } = Modal;
  const [form] = Form.useForm();
  const { query } = location;
  const type = query.type || 'add';
  const content = useRef('');
  const [loading, setloading] = useState(false);
  const [thumbnailImage, setThumbnailImageUrl] = useState('')//缩略图

  useEffect(() => {
    if (!query.id) {
      return;
    }

    // TODO:回显礼品详情
    GiftDetail({ Id: query.id }).then(res => {
      if (res) {
        setThumbnailImageUrl(`${ATTACHMENT_URL}${res.ThumbnailUrl}`)//手动绑定缩略图
        let imagesData = []
        res.Images.map((item) => {//处理多张图片
          let obj = {}
          obj.id = item.Id
          obj.uid = item.Id
          obj.url = `${ATTACHMENT_URL}${item.DocumentPath}`
          imagesData.push(obj)
          return imagesData
        })

        console.log(res);
        form.setFieldsValue({
          Gift: res.GiftName,
          RedemptionTime: [moment(res.StartTime), moment(res.EndTime)],
          RequiredPoints: res.RequiredPoints,
          RemainingUnit: res.RemainingUnit,
          Order: res.Order,
          Description: BraftEditor.createEditorState(res.Description),
          Thumbnail: res.Thumbnail,//缩略图手动绑定的!但这里要赋值,要不然 修改的时候 提交 会提示这里无值;修改回显传id给后台
          uploadPhoto: imagesData
        });
      }
    })
  }, [query.id]);

  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
  }

  const uploadButton = (
    <div className={styles.upImg2} >
      <PlusOutlined />
      <div>Upload</div>
    </div>
  );

  const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.readAsDataURL(img)
    reader.addEventListener('load', () => callback(reader.result));
  }

  const EditorChange = (editorState) => {
    //编辑器change 事件
    content.current = editorState && editorState.toHTML();
  };

  const rulesObj = {
    Gift: [
      {
        required: true,
        message: `Please input Gift!`
      },
      {
        validator(rule, text) {
          if (text) {
            if (text.length <= 200) {
              return Promise.resolve();
            } else {
              return Promise.reject('The length of characters exceed the limit!');
            }
          } else {
            return Promise.resolve();
          }
        }
      }
    ],
    Order: [
      {
        required: false,
        validator(rule, text) {
          if (text) {
            const reg = /^[+]{0,1}(\d+)$/;
            if (reg.test(text)) {
              return Promise.resolve();
            } else {
              return Promise.reject('Please input positive integer!');
            }
          } else {
            return Promise.resolve();
          }
        },
      }
    ],
    Thumbnail: [
      {
        required: true,
        message: `Please upload Thmbnail!`,
      }
    ],
    Image: [
      {
        required: true,
        message: `Please upload Image!`,
      }
    ],
    Description: [{
      required: true,
      message: `Please input Description!`,
    }
    ],
    RedemptionTime: [
      {
        required: true,
        message: `Please select Redemption Time!`,
      }
    ],
    RequiredPoints: [
      {
        required: true,
        message: `Please input Required Points!`,
      }
    ],
    RemainingUnit: [
      {
        required: true,
        message: `Please input RemainingUnit!`
      },
      {
        validator(rule, text) {
          if (text) {
            const reg = /^([1-9]\d*)?$/;
            if (reg.test(text)) {
              return Promise.resolve();
            } else {
              return Promise.reject('Please input positive integer!');
            }
          } else {
            return Promise.resolve();
          }
        }
      }
    ],
    RequiredPoints: [
      {
        required: true,
        message: `Please input Required Points!`,
      },
      {
        validator(rule, text) {
          if (text) {
            const reg = /^([1-9]\d*)?$/;
            if (reg.test(text)) {
              return Promise.resolve();
            } else {
              return Promise.reject('Please input positive integer!');
            }
          } else {
            return Promise.resolve();
          }
        }
      }
    ],

  }

  // 礼品缩略图
  const ThumbnailUploading = {
    showUploadList: false,
    action: commonUploadUrl,
    headers: {
      SessionKey: `${localStorage.getItem('sk')}`,
    },
    name: "thumbnail",//发到后台的文件name
    // listType="picture-card"
    className: "avatar-uploader",
    // className="thumbnailImage",
    accept: ".jpeg,.png,.jpg",
    data: (file) => {
      return {
        UploadType: 1026,
        Id: uuidv4(),
        FileType: getUploadFileType(file),
      };
    },
    beforeUpload: (file) => {
      // setPageLoading(true);
      const limitFileNameLen = 100;
      return new Promise((resolve, reject) => {
        if (file.name && file.name.length > limitFileNameLen) {
          message.error('Please upload a file with a file name less than 100 characters');
          return reject();
        }
        const limitM = 2;
        const isLimit = file.size / 1024 / 1024 <= limitM;
        if (!isLimit) {
          message.error('The size exceeds the limit');
          return reject();
        }
        return resolve();
      });
    },
    /**
     * 附件上传
     * @param info
     */
    onChange: (info) => {
      if (info.file.status === 'uploading') {
        setloading(true);
        return;
      }
      setloading(false);

      if (info.file.status === 'done') {
        getBase64(info.file.originFileObj, (resImageUrl) => {
          const { response } = info.file;
          if (response.DocumentId) {
            form.setFieldsValue({
              // TODO:传给后端的图片参数
              Thumbnail: response.DocumentId,//调用传图片的接口CommonUpload 后,后端response 返回的id 又传回给后台(通过保存的接口)
            });
            setThumbnailImageUrl(`${ATTACHMENT_URL}${response.UploadPath}`);
          } else {
            message.error('Upload failed');
          }
        });
      }
    },
  };

  // 礼品image
  const imageUploading = {
    showUploadList: false,
    action: commonUploadUrl,
    headers: {
      SessionKey: `${localStorage.getItem('sk')}`,
    },
    data: (file) => {
      return {
        UploadType: 1027,//后端定义的type
        Id: uuidv4(),
        FileType: getUploadFileType(file),
      };
    },
    beforeUpload: (file) => {// 礼品image
      console.log('你进来了');

      // setPageLoading(true);
      const limitFileNameLen = 100;
      return new Promise((resolve, reject) => {
        if (file.name && file.name.length > limitFileNameLen) {
          message.error('Please upload a file with a file name less than 100 characters');
          return reject();
        }
        const limitM = 2;
        const isLimit = file.size / 1024 / 1024 <= limitM;
        if (!isLimit) {
          message.error('The size exceeds the limit');
          return reject();
        }
        return resolve(isLimit);
      });
    },
    /**
     * 附件上传
     * @param info
     */
    onChange: (info) => {// 礼品image

      if (info.file.status === 'uploading') {
        setloading(true);
        return;
      }
      setloading(false);
      if (info.file.status === 'done') {// 礼品image
        getBase64(info.file.originFileObj, (resImageUrl) => {
          const { response } = info.file;
          if (response.DocumentId) {
            form.setFieldsValue({
              Image: response.DocumentId,//传给后台的info对象的id
            });
          } else {
            message.error('Upload failed');
          }
        });
      }
    },
    onPreview: (info) => {
      // console.log(info)
    }
  };

  //TODO:保存提交
  const submitForm = () => {
    form
      .validateFields()
      .then((values) => {
        let DataArray = []
        if (values.uploadPhoto) {//处理上传多张图片的值,数组对象转成数组字符串
          let newArray = values.uploadPhoto
          newArray.map((item, index) => {
            DataArray.push(item.id)
            return DataArray
          })
        }
        const postData = {
          GiftName: values.Gift,
          // StartTime: values.RedemptionTime?values.RedemptionTime[0].format('YYYY-MM-DD'):'',
          StartTime: values.RedemptionTime[0].format('YYYY-MM-DD'),
          EndTime: values.RedemptionTime[1].format('YYYY-MM-DD'),
          Thumbnail: values.Thumbnail,
          RequiredPoints: values.RequiredPoints,
          RemainingUnit: values.RemainingUnit,
          Order: values.Order,
          Description: content.current,
          Images: DataArray
        }

        if (query.id) {
          //编辑Edit
          postData.Id = query.id;//新增一个id键值对字段进postData中 传入后端Edit接口
          UpdateGift(postData).then((res) => {
            if (!res) {
              return;
            }
            if (res.ReturnCode === 1001) {
              history.push({
                pathname: '/admin/pointscenter/giftlist',
                search: ``,
              });
              message.success('Edit Successfully')
              // MessageSuccess(res)
            } else {
              MessageError(res);
              // console.log('修改提交报错');
            }
          });
        } else {//Add
          CreateGift(postData).then(res => {
            if (!res) {
              return;
            }
            if (res.ReturnCode === 1001) {
              history.push({
                pathname: '/admin/pointscenter/giftlist',
                search: ``,
              });
              // MessageSuccess(res)
              message.success('Add Successfully')
            } else {
              MessageError(res);
            }
          })
        }
      })
      .catch((err) => { });
  };

  return (
    <>
      <Spin spinning={loading}>

        <div className={styles.MaxBox}>
          <PanelTitle title={`Gift List / ${type == 'edit' ? 'Edit' : 'Add'} Gift`} />
          <div className={styles.boxTitle}>Content</div>
          <Form
            form={form}
            {...layout}
          >
            <Row>
              <Col span={12}>
                <Form.Item
                  labelCol={{ span: 8, offset: 0 }}
                  wrapperCol={{ span: 12, offset: 0 }}
                  label="Gift"
                  name="Gift"
                  rules={rulesObj.Gift}
                >
                  <Input></Input>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  labelCol={{ span: 8, offset: 0 }}
                  wrapperCol={{ span: 12, offset: 0 }}
                  label="Order"
                  name="Order"
                  rules={rulesObj.Order}
                >
                  <Input></Input>
                </Form.Item>
              </Col>
              <Col span={24}>
                <Form.Item
                  className={styles.uploadImgItem}
                  label="Thumbnail"
                  name="Thumbnail"
                  rules={rulesObj.Thumbnail}
                >
                  <Upload
                    className={styles.upImg2}

                    {...ThumbnailUploading}
                  >
                    {thumbnailImage ? <img src={thumbnailImage} className={styles.upImg} alt="Network error" /> : uploadButton}
                  </Upload>
                  <span className={styles.coverTips}>
                    建议尺寸300*300,支持jpg/jpeg、png格式图片,小于2M
                  </span>
                  {/* TODO:缩略图上传 */}
                </Form.Item>
              </Col>
              {/* TODO:礼品图上传 */}
              <Col span={24}>
                <Form.Item
                  className={styles.uploadImgItem}
                  label="Image"
                  name="uploadPhoto"//用了预览的组件,手动绑定图片路径,NONO!
                  rules={rulesObj.Image}
                >
                  <UploadComponent />
                </Form.Item>
              </Col>
              <Col span={24}>
                <Form.Item
                  label="Description"
                  name="Description"
                  rules={rulesObj.Description}
                  labelCol={{ span: 4, offset: 0 }}
                  wrapperCol={{ span: 18, offset: 0 }}
                >
                  <BraftEditor
                    // contentClassName={styles.content}
                    className={styles.myEditor}
                    onChange={EditorChange}
                  />
                </Form.Item>
              </Col>
            </Row>
            <div className={styles.boxTitle}>Setting</div>
            <Row>
              <Col span={12}>
                <Form.Item
                  labelCol={{ span: 8, offset: 0 }}
                  wrapperCol={{ span: 12, offset: 0 }}
                  label="Redemption Time"
                  name="RedemptionTime"
                  rules={rulesObj.RedemptionTime}
                >
                  <RangePicker
                    placeholder={['From', 'To']}
                    format={dateFormat}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  labelCol={{ span: 8, offset: 0 }}
                  wrapperCol={{ span: 12, offset: 0 }}
                  label="Required Points"
                  name="RequiredPoints"
                  rules={rulesObj.RequiredPoints}
                >
                  <Input></Input>
                </Form.Item>
              </Col>

              <Col span={24}>
                <Form.Item
                  labelCol={{ span: 4, offset: 0 }}
                  wrapperCol={{ span: 6, offset: 0 }}
                  label="Remaining Unit"
                  name="RemainingUnit"
                  rules={rulesObj.RemainingUnit}
                >
                  <Input></Input>
                </Form.Item>
              </Col>
            </Row>
          </Form>
          <div
            className={styles.BtnBox}
          >
            <Button
              className={styles.backBtn}
              type="primary"
              onClick={() => {
                confirm({
                  title: 'Content',
                  centered: true,
                  icon: <ExclamationCircleOutlined />,
                  content: 'Are you sure to back?',
                  okText: 'Yes',
                  cancelText: 'No',
                  onOk() {
                    history.go(-1);

                  },
                  onCancel() { },
                });
              }}
            >
              Back
            </Button>
            <Button
              className={styles.saveBtn}
              onClick={() => {
                submitForm();
              }}
              style={{ marginLeft: '10px' }}
              type="primary"
            >
              Save
            </Button>
          </div>
        </div>
      </Spin>
    </>
  );
};

export default editGift
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值