read.tsx 10.6 KB
import {
  postOrderErpOrderStagesPayWaySaveOrUpdate,
  postOrderErpOrderStagesSaveOrUpdate,
  postOrderErpOrderStagesSearch,
  postOrderErpOrderStagesUpload,
} from '@/services';
import {
  ModalForm,
  ProCard,
  ProForm,
  ProFormDatePicker,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { Form, message } from 'antd';
import { RcFile } from 'antd/es/upload';
import { useEffect, useState } from 'react';
import PayWayDetail from './readPayWay';
import ProductDetail from './readProduct';

const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

export default ({ currentContract }) => {
  const [form] = Form.useForm<{ name: string; company: string }>();
  const [contextBody, setContextBody] = useState({});
  const [, setEditProductBody] = useState([]);
  const [total, setTotal] = useState(0);
  const [payWayBody, setPayWayBody] = useState([]);
  const [otherBody, setOtherBody] = useState([]);

  type OrderStagesWithListItem = {
    //文件编号
    id: number;
    //合同编号
    contract: string;
    //供应商名称
    vendor: string;
    //签合同日期
    dateRange: Date;
    //终端名称
    terminal: string;
    orderStagesDeviceVoList: orderStagesDevice[];
    //合同总金额
    totalPrice: number;
    //付款方式
    payWay: string;
    //附件
    annex: string;
    //备注
    remark: string;
  };

  type orderStagesDevice = {
    //设备id
    dId: number;
    //设备名称
    deviceName: string;
    //设备型号
    deviceModel: string;
    //数量
    count: number;
    //单价
    unitPrice: number;
    //总价
    price: number;
  };

  async function refresh() {
    const res = await postOrderErpOrderStagesSearch({
      data: { contract: currentContract },
    });
    const context = res.data[0];
    // console.log(context);

    if (context.contract !== null) {
      setContextBody(context);
      setTotal(context.totalPrice);
      form.setFieldValue('totalPrice', context.totalPrice);
    }
  }

  function setSave(value) {
    // console.log(value);
    setOtherBody(value);
  }

  useEffect(() => {
    setContextBody({ ...contextBody, totalPrice: total });
    form.setFieldValue('totalPrice', total);
  }, [total]);

  const handleInputChange = (value: string, no: number, priceNow?: number) => {
    let totalPay = 0;
    const payValue: string[] = value.split('/');
    let body:
      | ((prevState: never[]) => never[])
      | { proportion: string; payPrice: number }[] = [];
    if (no === 1) {
      if (payValue.length !== 4) {
        message.warning('比例个数总和不为4个!');
      } else {
        payValue.forEach((item) => {
          totalPay += Number(item);
        });
      }
      if (totalPay !== 100) {
        message.warning('比例总和不为100!');
      } else {
        message.success('输入有效!');
        const price = total;
        payValue.forEach((item) => {
          body.push({
            proportion: item + '%',
            payPrice: (Number(item) * price) / 100,
          });
        });
        setPayWayBody(body);
      }
    } else {
      payValue.forEach((item) => {
        totalPay += Number(item);
      });
      payValue.forEach((item) => {
        body.push({
          proportion: item + '%',
          payPrice: (Number(item) * priceNow) / 100,
        });
      });
      setPayWayBody(body);
    }
  };

  async function getBody() {
    const res = await postOrderErpOrderStagesSearch({
      data: { contract: currentContract },
    });
    const context = res.data[0];
    // console.log(context);

    if (context.contract !== null) {
      setContextBody(context);
      setTotal(context.totalPrice);
      form.setFieldValue('totalPrice', context.totalPrice);
    }
    handleInputChange(context.payWay, 0, context.totalPrice);
  }

  useEffect(() => {
    getBody();
  }, []);

  function getEditProductBody(value) {
    // console.log(value);

    setEditProductBody(value);
    let price = 0;
    value.map((obj) => (price += obj.count * obj.unitPrice));
    setTotal(price);
    setContextBody({ ...contextBody, orderStagesDeviceVoList: value });
    handleInputChange(contextBody.payWay, 0, price);
  }

  return (
    <ModalForm<OrderStagesWithListItem>
      title="查看"
      trigger={<a onClick={refresh}>查看</a>}
      form={form}
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
        // onCancel: () => console.log('run'),
      }}
      submitter={{
        resetButtonProps: {},
        submitButtonProps: {
          style: {
            display: 'none',
          },
        },
      }}
      submitTimeout={2000}
      onFinish={async (values) => {
        // console.log(values);
        // console.log(otherBody);
        let remakeValue = [];
        // 创建一个用于存储所有异步操作的Promise数组
        const promises = [];

        otherBody.forEach((item) => {
          let remakeItem = {
            ossId: item.ossId,
            number: item.id,
            dataRange: item.payDate,
            fileName: item.fileName,
          };
          if (
            typeof item.fileUrl === 'object' &&
            item.fileUrl instanceof File
          ) {
            const formData = new FormData();
            formData.append('file', item.fileUrl as RcFile);
            const uploadPromise = async () => {
              const res = await postOrderErpOrderStagesUpload({
                data: formData,
                headers: {
                  'Content-Type':
                    'multipart/form-data; boundary=----WebKitFormBoundarynl6gT1BKdPWIejNq',
                },
              });
              if (res.data) {
                remakeItem.fileUrl = res.data;
              }
            };
            promises.push(uploadPromise());
          }
          remakeValue.push(remakeItem);
        });

        // 使用Promise.all等待所有异步操作完成后再执行保存操作
        Promise.all(promises).then(async () => {
          await postOrderErpOrderStagesPayWaySaveOrUpdate({
            data: remakeValue,
          });
        });
        const formData = new FormData();
        // let toSendEdit={...values,orderStagesDeviceVoList:contextBody.orderStagesDeviceVoList};
        let toSendEdit = {
          id: values.id || contextBody.id,
          contract: values.contract || contextBody.contract,
          vendor: values.vendor || contextBody.vendor,
          dateRange: values.dateRange || contextBody.dateRange,
          terminal: values.terminal || contextBody.terminal,
          orderStagesDeviceDoList:
            values.orderStagesDeviceVoList ||
            contextBody.orderStagesDeviceVoList,
          totalPrice: values.totalPrice || contextBody.totalPrice,
          payWay: values.payWay || contextBody.payWay,
          annex: contextBody.annex,
          remark: values.remark || contextBody.remark,
        };
        if (values.annex) {
          formData.append('file', values.annex[0].originFileObj as RcFile);
          const res = await postOrderErpOrderStagesUpload({
            data: formData,
            headers: {
              'Content-Type':
                'multipart/form-data; boundary=----WebKitFormBoundarynl6gT1BKdPWIejNq',
            },
          });
          if (res.data) {
            // console.log(values)
            // console.log(contextBody);
            toSendEdit.annex = res.data;
          }
        }
        const isSaveOrUpdate = await postOrderErpOrderStagesSaveOrUpdate({
          data: { ...toSendEdit },
        });
        if (isSaveOrUpdate) {
          // console.log(isSaveOrUpdate);
          getBody();
        }
        await waitTime(2000);
        message.success('提交成功');
        return true;
      }}
    >
      <ProCard title="基本信息" headerBordered bordered>
        <ProForm.Group>
          <ProFormText
            width="md"
            name="vendor"
            label="供应商名称"
            placeholder="请输入"
            initialValue={contextBody.vendor}
            readonly
          />

          <ProFormText
            width="md"
            name="terminal"
            label="终端名称"
            placeholder="请输入"
            initialValue={contextBody.terminal}
            readonly
          />

          <ProFormDatePicker
            name="dateRange"
            width="md"
            label="签合同日期"
            placeholder="请选择日期"
            fieldProps={{
              format: (value) => value.format('YYYY-MM-DD'),
            }}
            initialValue={contextBody.dateRange}
            readonly
          />

          <ProFormText
            width="md"
            name="payWay"
            label="付款比例"
            placeholder="请输入"
            initialValue={contextBody.payWay}
            readonly
            onBlur={(e) => {
              handleInputChange(e.target.value, 1);
            }}
          />

          <ProFormText
            width="md"
            name="contract"
            label="合同编号"
            placeholder="请输入"
            initialValue={contextBody.contract}
            readonly
          />

          {/* <ProFormText
                        width="md"
                        name="annex"
                        label="合同附件"
                        placeholder="请输入"
                        initialValue={contextBody.fileUrl}
                        readonly
                    /> */}

          <ProFormText
            width="md"
            name="totalPrice"
            label="合同金额"
            placeholder="请输入"
            disabled
            readonly
            // rules={[{ required: true, message: '此项为必填项' }]}
            // value={contextBody.totalPrice}
            initialValue={contextBody.totalPrice}
          />
        </ProForm.Group>
      </ProCard>
      <ProCard
        title="产品明细"
        style={{ marginTop: 10 }}
        headerBordered
        bordered
      >
        <ProductDetail
          productBody={contextBody.orderStagesDeviceVoList}
          EditProductBody={getEditProductBody}
        ></ProductDetail>
      </ProCard>

      <ProCard
        title="付款信息"
        style={{ marginTop: 10 }}
        headerBordered
        bordered
      >
        <PayWayDetail
          payBody={payWayBody}
          thisId={contextBody.id}
          currtSave={setSave}
        ></PayWayDetail>
      </ProCard>

      <ProCard style={{ marginTop: 10 }} headerBordered bordered>
        <ProFormTextArea
          label="备注"
          name="remark"
          initialValue={contextBody.remark}
          readonly
        />
      </ProCard>
    </ModalForm>
  );
};