AddRewardsModal.tsx 9 KB
import React, { useEffect, useState } from "react";
import { Modal, Form, Select, InputNumber, message, Button, Spin } from "antd";
import { saveRewardsListApi } from "../RewardsList/api";
import { useStore } from "../index";
import { getRewardsDealer, getRewardsSelectApi } from "../api";
import _ from "lodash";
import useInitail from "@/hooks/useInitail";
import { RewardsType } from "@/pages/stock/AllowanceConfirm/entity";
import EditableTable from "./EditTable";
import { savePromotionNegativeApi } from "@/pages/stock/AllowanceConfirm/EditComfirm/Manufacturer/api";

const Option = Select.Option;
interface Props {
  visible: boolean;
  onCancel: Function;
  rewardsType?: number;
  fetchList: () => any;
  currentItem: any;
  dimension: number; //5 奖励 ,4 :负激励
}
const currentApi = {
  4: savePromotionNegativeApi,
  5: saveRewardsListApi,
};

export default function CreateModal(props: Props) {
  const [form] = Form.useForm();
  const { visible, onCancel, fetchList, rewardsType, currentItem, dimension } =
    props;
  const { data, rebateId, readOnly } = useStore();

  // 扣款金额
  const [amount, setAmount] = useState<number>(0);
  const [delay, setDelay] = useState(true);
  const [shopDelay, setShopDelay] = useState(true);
  const [dealerList, setDealerList] = useState<FvmAllowance.DealerItem[]>([]);
  const [shopList, setShopList] = useState<any[]>([]);
  /**
   * 存储已经选择门店列表
   */
  const [selesctedDealerList, setSelectedDealerList] = useState<any[]>([]);

  /** 获取折让类型列表 */
  const {
    data: rewardsList,
    setParams,
    loading,
  } = useInitail(getRewardsSelectApi, [], rewardsType, delay);
  const [saveLoading, setSaveLoading] = useState(false);

  useEffect(() => {
    if (visible) {
      setAmount(currentItem.actualRebateAmount || 0);
      // 选中商家
      if (currentItem.costSharing && currentItem.costSharing.length) {
        const shops = currentItem.costSharing.map((i) => ({
          label: i.dealerName,
          value: i.dealerId,
        }));
        const tmpList = currentItem.costSharing.map((i) => ({
          ...i,
          key: i.dealerId,
        }));
        currentItem.dealerId = shops;

        setSelectedDealerList([...tmpList]);
      }
      form.setFieldsValue({
        ...currentItem,
        amount: currentItem.actualRebateAmount,
        rewardsSelectType: {
          label: currentItem.fundsName,
          value: currentItem.rewardsId,
        },
      });
    }
    if (dimension === 4) {
      setDelay(true);
    }
    if (rewardsType && visible && dimension === 5) {
      setParams(rewardsType, true);
      setDelay(false);
    }
    // if (data.brandId && data.brandId && visible) {
    //   getShopList({ brandId: data.brandId, subjectId: data.subjectId });
    // }
  }, [visible, data]);

  useEffect(() => {
    if (dealerList.length) return;
    visible && data.subjectId && getDealerList();
  }, [data.subjectId, visible]);

  function getDealerList() {
    getRewardsDealer(data.subjectId)
      .then((res) => {
        setDealerList(res.data || []);
      })
      .catch((e) => {
        message.error(e.message);
      });
  }

  /** 查询商家--门店 */
  // function getShopList(param: any) {
  //   getRebateShop(param)
  //     .then((res) => {
  //       setShopList(res.data || []);
  //     })
  //     .catch((e) => {
  //       message.error(e.message);
  //     });
  // }

  function handSubmit(fieldsValue: any) {
    if (fieldsValue.costSharing && fieldsValue.costSharing.length) {
      const costSharing = fieldsValue.costSharing;
      const sum = costSharing.reduce((previousValue, currentValue) => {
        return previousValue + currentValue.amount;
      }, 0);

      if (sum !== fieldsValue.amount) {
        message.error("分摊金额之和不等于扣款金额");
        return;
      }
    }
    const param: any = {
      ...fieldsValue,
      rebateId,
      rewardsType,
      actualRebateAmount: fieldsValue.amount,
    };
    if (dimension === 5) {
      param.rewardsId = fieldsValue.rewardsSelectType.value;
      param.rewardsName = fieldsValue.rewardsSelectType.label;
    }
    // 厂家促销==》负激励
    if (dimension === 4) {
      param.promotionId = currentItem.promotionId;
    }
    setSaveLoading(true);
  
    currentApi[dimension](param)
      .then(() => {
        message.success("操作成功");
        setSaveLoading(false);
        fetchList && fetchList();
        onCancel && onCancel();
      })
      .catch((e) => {
        message.error(e.message);
        setSaveLoading(false);
      });
  }

  // 选择商家
  const _onSelect = (values: any[]) => {
    if (values.length) {
      const res = values.map((i) => ({
        dealerName: i.label,
        dealerId: i.value,
        key: i.value,
        amount: 0,
        ratio: 0,
        rewardBelong: 1,
      }));
      setSelectedDealerList([...res]);

      return;
    }
    setSelectedDealerList([]);
  };
  return (
    <Modal
      title={
        dimension === 5 && rewardsType
          ? `${currentItem.id ? "设置" : "新增"} ${RewardsType[rewardsType]}`
          : `${currentItem.id ? "设置" : "新增"}负激励`
      }
      visible={visible}
      maskClosable={false}
      confirmLoading={saveLoading}
      afterClose={() => {
        form.resetFields();
        setSelectedDealerList([]);
      }}
      onCancel={() => onCancel()}
      onOk={form.submit}
      width={800}
      footer={
        readOnly
          ? null
          : [
            <Button key="back" onClick={() => onCancel()}>
              取消
            </Button>,
            <Button key="submit" type="primary" onClick={form.submit}>
              确定
            </Button>,
            ]
      }
    >
      <Spin spinning={dimension === 4 ? false : loading}>
        <Form
          form={form}
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 15 }}
          onFinish={handSubmit}
        >
          {dimension === 5 && (
            <Form.Item
              name="rewardsSelectType"
              label="折让类型"
              rules={[{ required: true, message: "请选择折让类型" }]}
            >
              <Select placeholder="请选择" labelInValue>
                {rewardsList.map((item) => (
                  <Option value={item.id} key={item.id}>
                    {item.name}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          )}

          <Form.Item
            label={
              dimension === 5
                ? ` ${RewardsType[rewardsType]}金额`
                : `负激励金额`
            }
            required
          >
            <Form.Item
              noStyle
              name="amount"
              rules={[
                { required: true, message: "请输入" },
                { pattern: /^[1-9]*[1-9][0-9]*$/, message: "金额必须大于0" },
              ]}
            >
              <InputNumber
                placeholder="请输入"
                style={{ width: "90%" }}
                onChange={(value: number) => setAmount(value)}
              />
            </Form.Item>
            <span style={{ paddingLeft: 10 }}>元</span>
          </Form.Item>
          <Form.Item
            name="dealerId"
            label="商家"
            rules={[{ required: true, message: "请选择商家" }]}
          >
            <Select
              placeholder="选择商家"
              labelInValue
              mode="multiple"
              onChange={(values) => {
                const amount = form.getFieldValue("amount");
                if (typeof amount !== "number") {
                  message.error("请先输入金额");
                  form.setFieldsValue({ dealerId: [] });
                  return;
                }
                _onSelect(values);
              }}
            >
              {dealerList.map((item) => (
                <Option value={item.dealerId} key={item.dealerId}>
                  {item.dealerName}
                </Option>
              ))}
            </Select>
          </Form.Item>
          {/* <Form.Item
            name="shopId"
            label="门店"
            rules={[{ required: true, message: "请选择门店" }]}
          >
            <Select
              placeholder="请选择"
              labelInValue
              mode="multiple"
              onChange={(values) => {
              const amount = form.getFieldValue("amount");
              if (typeof amount !== "number") {
                message.error("请先输入金额");
                return;
              }
              _onSelect(values);
            }}
            >
              {shopList.map((item) => (
                <Option value={item.shopId} key={item.shopId}>
                  {item.shopName}
                </Option>
            ))}
            </Select>
          </Form.Item> */}
          <Form.Item name="costSharing" label="分摊">
            <EditableTable
              tableDataSource={selesctedDealerList}
              amount={amount}
            />
          </Form.Item>
        </Form>
      </Spin>
    </Modal>
  );
}