ApplyForInvoicingModal.tsx 16 KB
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 30 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 68 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 124 125 126 127 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 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
import { RESPONSE_CODE } from '@/constants/enum';
import {
  postServiceOrderApplyInvoicing,
  postServiceOrderQueryServiceOrder,
} from '@/services';
import { FloatAdd, enumToSelect, getAliYunOSSFileNameFromUrl } from '@/utils';
import {
  ModalForm,
  ProFormMoney,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProFormUploadDragger,
} from '@ant-design/pro-components';
import { Form, message } from 'antd';
import { useEffect, useState } from 'react';
import { PAYEE_OPTIONS } from '../constant';

// 定义选项类型
interface SelectOption {
  label: string;
  value: string;
}

export default ({
  setCheckVisible,
  isEdit,
  subOrders,
  mainOrders,
  onClose,
}: {
  setCheckVisible: (val: boolean) => void;
  isEdit?: boolean;
  subOrders: any[];
  mainOrders: any[];
  onClose: () => void;
}) => {
  const [isUrgent, setIsUrgent] = useState('');
  const [receivingCompanyOptions, setReceivingCompanyOptions] = useState<
    SelectOption[]
  >([]);
  const [additionalMainOrders, setAdditionalMainOrders] = useState<any[]>([]);

  let ids = subOrders?.map((item) => {
    return item.id;
  });

  // 定义返回类型接口
  interface MainOrderData {
    value: string | number;
    totalPayment: number;
    invoiceIssuedAmount: number;
    availableAmount: number;
  }

  // 解析输入框内容,识别格式如 "23123,2507310003"
  const parseInputContent = (content: string): string[] => {
    if (!content) return [];
    return content
      .split(',')
      .map((id) => id.trim())
      .filter((id) => id);
  };

  // 查询未选择的订单数据
  const queryMissingOrders = async (missingIds: string[]) => {
    try {
      const { data } = await postServiceOrderQueryServiceOrder({
        // @ts-ignore
        data: {
          current: 1,
          pageSize: 10,
          id: missingIds,
          condition: 0,
          sorted: false,
          isDeleteQueryOrder: false,
        },
      });

      if (data?.data) {
        setAdditionalMainOrders(data.data);
      }
    } catch (error) {
      console.error('查询订单失败:', error);
      message.error('查询订单数据失败');
    }
  };

  // 获取唯一的主订单ID及其相关金额信息
  const getUniqueMainOrderIds = (): MainOrderData[] => {
    console.log(subOrders, mainOrders);
    const mainOrderIds = subOrders?.map((item: any) => item.mainOrderId);
    const uniqueIds = [...new Set(mainOrderIds)].filter(Boolean);

    const result = uniqueIds.map((id) => {
      // 获取该主订单的数据
      const mainOrder = mainOrders
        ? mainOrders.find((item: any) => item.id === id)
        : null;

      // 获取该主订单下所有子订单
      const orderSubOrders = subOrders.filter(
        (item: any) => item.mainOrderId === id,
      );

      // 计算该主订单的总金额
      let totalPayment = mainOrder ? mainOrder.totalPayment : 0;
      if (!totalPayment) {
        orderSubOrders.forEach((item: any) => {
          totalPayment = FloatAdd(totalPayment, item.totalPayment || 0);
        });
      }

      // 计算已开票金额(如果有的话)
      let invoiceIssuedAmount = mainOrder
        ? mainOrder.invoiceIssuedAmount || 0
        : 0;
      if (!invoiceIssuedAmount) {
        orderSubOrders.forEach((item: any) => {
          invoiceIssuedAmount = FloatAdd(
            invoiceIssuedAmount,
            item.invoiceIssuedAmount || 0,
          );
        });
      }

      // 计算可开票金额
      const availableAmount = Math.max(0, totalPayment - invoiceIssuedAmount);

      return {
        value: String(id),
        totalPayment,
        invoiceIssuedAmount,
        availableAmount,
      };
    });

    // 添加额外查询到的订单数据
    const additionalOrders = additionalMainOrders.map((order) => ({
      value: String(order.id),
      totalPayment: order.totalPayment || 0,
      invoiceIssuedAmount: order.invoiceIssuedAmount || 0,
      availableAmount: Math.max(
        0,
        (order.totalPayment || 0) - (order.invoiceIssuedAmount || 0),
      ),
    }));

    return [...result, ...additionalOrders];
  };

  let mainIdSet = new Set();
  subOrders?.forEach((item: { mainOrderId: unknown }) => {
    mainIdSet.add(item.mainOrderId);
  });

  let mainIds = Array.from(mainIdSet).join(',');

  let newListAnnex = [];

  //回显,子订单可以编辑备注跟附件
  if (isEdit) {
    newListAnnex = subOrders.afterAnnexList?.map((path) => {
      let i = 0;
      return {
        uid: i++,
        name: getAliYunOSSFileNameFromUrl(path),
        status: 'uploaded',
        url: path,
        response: { data: [path] },
      };
    });
    subOrders.filePaths = newListAnnex;
  }

  const [form] = Form.useForm<{
    applyInvoicingNotes: string;
    filePaths: any;
    subIds: any[];
    afterInvoicingUpdate: boolean;
    receivingCompany: string;
    isUrgent: boolean;
    deadline: string;
    invoiceType: string; // 新增发票类型字段
  }>();

  // 处理备注内容变化
  const handleNotesChange = async (value: string) => {
    const inputIds = parseInputContent(value);
    const selectedMainOrderIds = Array.from(mainIdSet).map((id) => String(id));

    console.log('输入的订单ID:', inputIds);
    console.log('已选择的主订单ID:', selectedMainOrderIds);

    // 找出输入框中存在但未选择的订单ID
    const missingIds = inputIds.filter(
      (id) => !selectedMainOrderIds.includes(id),
    );

    console.log('缺失的订单ID:', missingIds);

    if (missingIds.length > 0) {
      await queryMissingOrders(missingIds);
    } else {
      // 如果没有缺失的订单,清空额外的订单数据
      setAdditionalMainOrders([]);
    }
  };

  useEffect(() => {
    //显示拼接的主订单id
    form.setFieldValue('applyInvoicingNotes', mainIds);

    // 转换收款单位选项并保存
    const options = enumToSelect(PAYEE_OPTIONS);
    setReceivingCompanyOptions(options);
  }, []);

  useEffect(() => {
    // 当额外的主订单数据变化时,设置可开票金额初始值
    const mainOrders = getUniqueMainOrderIds();
    mainOrders.forEach((order) => {
      // 只为新添加的订单设置初始值,避免覆盖用户已输入的值
      const currentValue = form.getFieldValue(
        `invoiceAvailableAmount_${order.value}`,
      );
      if (currentValue === undefined || currentValue === null) {
        form.setFieldValue(
          `invoiceAvailableAmount_${order.value}`,
          order.availableAmount,
        );
      }
    });
  }, [additionalMainOrders]);

  return (
    <ModalForm<{
      applyInvoicingNotes: string;
      filePaths: any;
      subIds: any[];
      afterInvoicingUpdate: boolean;
    }>
      width={500}
      open
      title={isEdit ? '修改信息' : '申请开票'}
      initialValues={subOrders}
      form={form}
      autoFocusFirstInput
      modalProps={{
        okText: '确认',
        cancelText: '取消',
        destroyOnClose: true,
        onCancel: () => {
          setCheckVisible(false);
        },
      }}
      submitter={{
        render: (props, defaultDoms) => {
          return defaultDoms;
        },
      }}
      submitTimeout={2000}
      onFinish={async (values) => {
        // 收集所有相关的子订单ID,包括额外查询到的主订单下的子订单
        const allSubIds = [...ids]; // 原始选择的子订单ID

        console.log('原始子订单ID:', ids);
        console.log('额外查询的主订单:', additionalMainOrders);

        // 添加额外查询到的主订单下的子订单ID
        additionalMainOrders.forEach((mainOrder: any) => {
          if (mainOrder.subOrderInformationLists) {
            mainOrder.subOrderInformationLists.forEach((subOrder: any) => {
              if (subOrder.id && !allSubIds.includes(subOrder.id)) {
                console.log('添加子订单ID:', subOrder.id);
                allSubIds.push(subOrder.id);
              }
            });
          }
        });

        console.log('最终子订单ID列表:', allSubIds);
        values.subIds = allSubIds;
        //附件处理
        values.filePaths = values.filePaths?.map((item) => {
          return { url: item.response.data[0] };
        });

        if (isEdit) {
          values.afterInvoicingUpdate = true;
        } else {
          values.afterInvoicingUpdate = false;
        }

        // 收集主订单可开票金额
        const invoiceOrderAmounts = getUniqueMainOrderIds().map((item) => ({
          orderId: Number(item.value), // 确保为 number 类型
          availableAmount: values[`invoiceAvailableAmount_${item.value}`],
        }));
        // 校验所有主订单可开票金额之和等于price字段
        const price = values.price;
        let sumAvailable = 0;
        invoiceOrderAmounts.forEach((item) => {
          sumAvailable = FloatAdd(sumAvailable, item.availableAmount || 0);
        });
        if (Math.abs(sumAvailable - price) > 0.01) {
          message.error(
            `所有主订单可开票金额之和(${sumAvailable})必须等于开票金额(${price})`,
          );
          return;
        }

        // 获取receivingCompany对应的名称
        const selectedOption = receivingCompanyOptions.find(
          (option) => option.value === values.receivingCompany,
        );
        const receivingCompanyName = selectedOption ? selectedOption.label : '';

        // 构建包含所有订单的mainOrderIds字符串
        const allMainOrderIds = getUniqueMainOrderIds()
          .map((item) => item.value)
          .join(',');

        // 添加到请求数据中
        const reqData = {
          ...values,
          receivingCompanyName, // 添加收款单位名称
          mainOrderIds: allMainOrderIds, // 使用包含所有订单的ID字符串
          invoiceOrderAmounts,
        };
        const res = await postServiceOrderApplyInvoicing({ data: reqData });

        if (res.result === RESPONSE_CODE.SUCCESS) {
          message.success(res.message);
          onClose();
        }
      }}
      onOpenChange={setCheckVisible}
    >
      {/* 主订单金额表格,任何情况都显示 */}
      <div style={{ marginBottom: 24 }}>
        <div
          style={{
            display: 'flex',
            fontWeight: 'bold',
            marginBottom: 8,
            padding: '8px 0',
            borderBottom: '1px solid #f0f0f0',
          }}
        >
          <div style={{ flex: 25 }}>订单号</div>
          <div style={{ flex: 18, textAlign: 'right' }}>订单金额</div>
          <div style={{ flex: 18, textAlign: 'right' }}>已开票金额</div>
          <div style={{ flex: 39, textAlign: 'right' }}>可开票金额</div>
        </div>
        {getUniqueMainOrderIds().map((item, index) => {
          const maxAvailable = Math.max(
            0,
            item.totalPayment - item.invoiceIssuedAmount,
          );

          // 检查是否是额外查询到的订单
          const isAdditionalOrder = additionalMainOrders.some(
            (order) => String(order.id) === String(item.value),
          );

          return (
            <div
              key={index}
              style={{
                display: 'flex',
                marginBottom: 8,
                padding: '8px 0',
                borderBottom: '1px solid #f0f0f0',
                backgroundColor: isAdditionalOrder ? '#f6ffed' : 'transparent', // 浅绿色背景表示新查询的订单
                border: isAdditionalOrder ? '1px solid #b7eb8f' : 'none',
                borderRadius: isAdditionalOrder ? '4px' : '0',
              }}
            >
              <div style={{ flex: 25 }}>
                {item.value}
                {isAdditionalOrder}
              </div>
              <div style={{ flex: 18, textAlign: 'right' }}>
                ¥ {item.totalPayment.toFixed(2)}
              </div>
              <div style={{ flex: 18, textAlign: 'right' }}>
                ¥ {item.invoiceIssuedAmount.toFixed(2)}
              </div>
              <div style={{ flex: 39, textAlign: 'right' }}>
                <ProFormMoney
                  name={`invoiceAvailableAmount_${item.value}`}
                  locale="zh-CN"
                  fieldProps={{
                    precision: 2,
                    style: { width: '70%' },
                  }}
                  initialValue={item.availableAmount}
                  rules={[
                    { required: true, message: '请填写可开票金额!' },
                    {
                      validator: (_, value) => {
                        if (value > maxAvailable) {
                          return Promise.reject(
                            `可开票金额不能超过${maxAvailable.toFixed(2)}`,
                          );
                        } else if (value === 0) {
                          return Promise.reject(`可开票金额不能为0`);
                        }
                        return Promise.resolve();
                      },
                    },
                  ]}
                />
              </div>
            </div>
          );
        })}
      </div>

      <div className="mb-1">
        如果需要合并订单,请将需要合并的订单id写在备注中,id之间用英文逗号隔开。
      </div>
      <ProFormTextArea
        width="lg"
        name="applyInvoicingNotes"
        key="applyInvoicingNotes"
        placeholder="请输入备注"
        fieldProps={{
          onChange: (e) => {
            handleNotesChange(e.target.value);
          },
        }}
      />
      <ProFormText
        width="lg"
        name="purchaser"
        label="抬头名称"
        key="purchaser"
        placeholder="请输入抬头名称"
        rules={[{ required: true, message: '抬头名称必填' }]}
      />
      <ProFormSelect
        placeholder="选择收款单位"
        name="receivingCompany"
        width="lg"
        key="receivingCompany"
        label={
          <div>
            <span>开票收款单位</span>
            <span className="pl-2 text-xs text-gray-400">
              财务开票将依据这个字段,选择对应的公司开票(若对[收款单位]没有要求,请任意选择一个)
            </span>
          </div>
        }
        options={receivingCompanyOptions}
        rules={[{ required: true, message: '开票收款单位必填' }]}
      />

      {/* 新增发票类型选择 */}
      <ProFormSelect
        placeholder="选择发票类型"
        name="invoiceType"
        width="lg"
        key="invoiceType"
        label="发票类型"
        options={[
          { label: '普票', value: 'ORDINARY_TICKET' },
          { label: '专票', value: 'SPECIAL_TICKET' },
        ]}
        rules={[{ required: true, message: '发票类型必填' }]}
      />

      <ProFormSelect
        placeholder="选择是否加急"
        name="isUrgent"
        width="lg"
        key="isUrgent"
        label="是否加急"
        options={[
          { label: '是', value: 'true' },
          { label: '否', value: 'false' },
        ]}
        rules={[{ required: true, message: '是否加急必填' }]}
        onChange={(val: any) => {
          setIsUrgent(val);
        }}
      />

      {/* <ProFormDatePicker
        key="deadline"
        label="期望开票时间"
        name="deadline"
        rules={[{ required: isUrgent === 'true', message: '期望开票时间必填' }]}
        hidden={isUrgent !== 'true'}
      /> */}

      <ProFormTextArea
        key="invoicingUrgentCause"
        label="加急开票原因"
        name="invoicingUrgentCause"
        rules={[{ required: isUrgent === 'true', message: '加急开票原因' }]}
        hidden={isUrgent !== 'true'}
      />

      <ProFormUploadDragger
        key="2"
        label={
          <div>
            <span>开票明细确认表</span>
            <span className="pl-2 text-xs text-gray-400">
              如果开票信息有变更,如开票内容跟下单内容不一致、下单抬头和付款抬头不一致,请上传开票明细确认表。
            </span>
          </div>
        }
        name="filePaths"
        action="/api/service/order/fileProcess"
        fieldProps={{
          headers: { Authorization: localStorage.getItem('token') },
        }}
      />
    </ModalForm>
  );
};