BusinessForm.test.tsx 30.7 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 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
import { useState } from 'react';
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';

import {
  BusinessForm,
  validateBusinessForm,
  type BusinessFormField,
  type BusinessFormValue,
  type BusinessFormValues,
} from '@gl/business-components';

function getSelectTrigger(name: string) {
  const field = screen
    .getAllByText(name)
    .map((element) => element.closest('[data-testid^="business-form-field-"]'))
    .find(Boolean);
  if (!field) {
    throw new Error(`Select field ${name} was not found`);
  }
  const input = field.querySelector('input[type="text"]');
  if (!input) {
    throw new Error(`Select input ${name} was not found`);
  }
  return input as HTMLInputElement;
}

function getSelectOption(name: string) {
  const option = screen.getAllByText(name).map((element) => element.closest('li')).find(Boolean);
  if (!option) {
    throw new Error(`Select option ${name} was not found`);
  }
  return option as HTMLElement;
}

function getUploadInput(name: string) {
  const field = screen.getByTestId(`business-form-field-${name}`);
  const input = field.querySelector('input[type="file"]');
  if (!input) {
    throw new Error(`Upload input ${name} was not found`);
  }
  return input as HTMLInputElement;
}

function getNumberInput(name: string) {
  const field = screen.getByTestId(`business-form-field-${name}`);
  const input = field.querySelector('input');
  if (!input) {
    throw new Error(`Number input ${name} was not found`);
  }
  return input as HTMLInputElement;
}

function getControlHolder(name: string) {
  const holder = screen.getByTestId(`business-form-control-holder-${name}`);
  if (!holder) {
    throw new Error(`Control holder ${name} was not found`);
  }
  return holder as HTMLElement;
}

function Harness({
  fields,
  initialValues,
  errors,
  onChange = vi.fn(),
}: {
  fields: Parameters<typeof BusinessForm>[0]['fields'];
  initialValues: Parameters<typeof BusinessForm>[0]['values'];
  errors?: Parameters<typeof BusinessForm>[0]['errors'];
  onChange?: Parameters<typeof BusinessForm>[0]['onChange'];
}) {
  const [values, setValues] = useState(initialValues);

  return (
    <BusinessForm
      fields={fields}
      errors={errors}
      values={values}
      onChange={(nextValues, changedKey) => {
        setValues(nextValues);
        onChange?.(nextValues, changedKey);
      }}
    />
  );
}

describe('BusinessForm', () => {
  it('renders all built-in field types with the current values', () => {
    const upload = vi.fn();

    render(
      <BusinessForm
        fields={[
          { key: 'title', label: '名称', type: 'input', required: true, maxLength: 10 },
          { key: 'amount', label: '数量', type: 'numberInput', min: 1, max: 10, precision: 2 },
          {
            key: 'status',
            label: '状态',
            type: 'select',
            options: [
              { label: '启用', value: 'enabled' },
              { label: '停用', value: 'disabled' },
            ],
          },
          { key: 'enabled', label: '开关', type: 'switch' },
          { key: 'remark', label: '备注', type: 'textarea', maxLength: 20 },
          {
            key: 'file',
            label: '附件',
            type: 'upload',
            kinds: ['image', 'video', 'file', 'gif'],
            accept: '.png,.mp4,.pdf',
            maxSize: 1024 * 1024,
            upload,
          },
          { key: 'summary', label: '说明', type: 'displayText' },
          {
            key: 'custom',
            label: '自定义',
            type: 'custom',
            render: () => <button type="button">自定义操作</button>,
          },
        ]}
        values={{
          title: '合同',
          amount: 2,
          status: 'enabled',
          enabled: true,
          remark: '已填写',
          file: { name: 'demo.png', url: '/demo.png', kind: 'image' },
          summary: '说明内容',
          custom: 'custom-value',
        }}
        onChange={vi.fn()}
        fieldWidth={360}
      />,
    );

    expect(screen.getByLabelText('名称')).toHaveValue('合同');
    expect(getNumberInput('amount')).toHaveValue(2);
    expect(getSelectTrigger('状态')).toHaveValue('启用');
    expect(screen.getByRole('switch', { name: '开关' })).toBeChecked();
    expect(screen.getByLabelText('备注')).toHaveValue('已填写');
    expect(screen.getByText('说明内容')).toBeInTheDocument();
    expect(screen.getByRole('button', { name: '自定义操作' })).toBeInTheDocument();
    expect(screen.getByTestId('business-form-field-title')).toHaveAttribute('data-width', '360');
    expect(screen.getByTestId('business-form-field-remark')).toHaveAttribute('data-width', '360');
    expect(screen.getByTestId('business-form-field-status')).toHaveAttribute('data-width', '360');
  });

  it('keeps controlled fields inside TDesign FormItem without overriding their values', () => {
    const onChange = vi.fn();

    render(
      <Harness
        fields={[
          { key: 'title', label: '名称', type: 'input', required: true, helpText: '请输入项目名称' },
          {
            key: 'status',
            label: '状态',
            type: 'select',
            options: [{ label: '启用', value: 'enabled' }],
          },
          {
            key: 'custom',
            label: '自定义',
            type: 'custom',
            render: ({ value, setValue }) => (
              <button type="button" onClick={() => setValue('custom-next')}>
                {String(value)}
              </button>
            ),
          },
        ]}
        initialValues={{ title: '合同', status: 'enabled', custom: 'custom-start' }}
        errors={{ title: '名称错误' }}
        onChange={onChange}
      />,
    );

    const titleField = screen.getByTestId('business-form-field-title');
    expect(titleField.querySelector('.t-form__item')).toBeInTheDocument();
    expect(within(titleField).getByText('请输入项目名称')).toBeInTheDocument();
    expect(within(titleField).getByText('名称错误')).toBeInTheDocument();

    fireEvent.change(screen.getByLabelText('名称'), { target: { value: '合同A' } });
    fireEvent.click(screen.getByRole('button', { name: 'custom-start' }));

    expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ title: '合同A' }), 'title');
    expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ custom: 'custom-next' }), 'custom');
  });

  it('uses red validation text and light gray helper text', () => {
    render(
      <BusinessForm
        fields={[{ key: 'title', label: '名称', type: 'input', required: true, helpText: '普通提示' }]}
        values={{ title: '' }}
        errors={{ title: '名称必填' }}
        onChange={vi.fn()}
      />,
    );

    const titleField = screen.getByTestId('business-form-field-title');
    const helperText = within(titleField).getByText('普通提示');
    const errorText = within(titleField).getByText('名称必填');

    expect(helperText.className).toContain('helpText');
    expect(errorText.className).toContain('error');
    expect(helperText).toHaveStyle({ color: '#a6a6a6' });
    expect(errorText).toHaveStyle({ color: '#d94841' });
  });

  it('updates controlled values and emits form-level and field-level patch changes', () => {
    const onChange = vi.fn();
    const titleChange = vi.fn();

    render(
      <BusinessForm
        fields={[
          {
            key: 'title',
            label: '名称',
            type: 'input',
            onChange: titleChange,
          },
          {
            key: 'amount',
            label: '数量',
            type: 'numberInput',
          },
        ]}
        values={{
          title: '合同',
          amount: 1,
        }}
        onChange={onChange}
      />,
    );

    fireEvent.change(screen.getByLabelText('名称'), { target: { value: '合同A' } });
    fireEvent.change(getNumberInput('amount'), { target: { value: '2' } });

    expect(titleChange).toHaveBeenCalledWith('合同A', expect.objectContaining({ key: 'title' }));
    expect(onChange).toHaveBeenCalledWith(
      expect.objectContaining({
        title: '合同A',
        amount: 2,
      }),
      expect.objectContaining({
        key: 'title',
        value: '合同A',
      }),
    );
  });

  it('recomputes visible, disabled, and readonly fields from the latest values', () => {
    function Harness() {
      const [values, setValues] = useState<BusinessFormValues>({
        mode: 'hide',
        detail: '详情',
        locked: '锁定值',
        readonlyNote: '只读值',
      });

      return (
        <BusinessForm
          fields={[
            {
              key: 'mode',
              label: '模式',
              type: 'input',
            },
            {
              key: 'detail',
              label: '详情',
              type: 'input',
              visible: (currentValues) => currentValues.mode === 'show',
            },
            {
              key: 'locked',
              label: '锁定项',
              type: 'input',
              disabled: (currentValues) => currentValues.mode === 'lock',
            },
            {
              key: 'readonlyNote',
              label: '只读项',
              type: 'input',
              readonly: (currentValues) => currentValues.mode === 'read',
            },
          ]}
          values={values}
          onChange={(nextValues) => setValues(nextValues)}
        />
      );
    }

    render(<Harness />);

    expect(screen.queryByLabelText('详情')).not.toBeInTheDocument();
    expect(screen.getByLabelText('锁定项')).not.toBeDisabled();
    expect(screen.getByLabelText('只读项')).not.toHaveAttribute('readonly');

    fireEvent.change(screen.getByLabelText('模式'), { target: { value: 'show' } });
    expect(screen.getByLabelText('详情')).toBeInTheDocument();

    fireEvent.change(screen.getByLabelText('模式'), { target: { value: 'lock' } });
    expect(screen.getByLabelText('锁定项')).toBeDisabled();

    fireEvent.change(screen.getByLabelText('模式'), { target: { value: 'read' } });
    expect(screen.queryByLabelText('只读项')).not.toBeInTheDocument();
    expect(screen.getByText('只读值')).toBeInTheDocument();
  });

  it('validates required, max length, number range, precision, readonly, hidden and custom validator fields', async () => {
    const fields: BusinessFormField[] = [
      { key: 'title', label: '名称', type: 'input', required: true, maxLength: 3 },
      { key: 'count', label: '数量', type: 'numberInput', min: 2, max: 5 },
      { key: 'price', label: '单价', type: 'numberInput', precision: 1 },
      { key: 'readonlyField', label: '只读', type: 'input', readonly: true, required: true },
      { key: 'hiddenField', label: '隐藏', type: 'input', visible: false, required: true },
      { key: 'summary', label: '说明', type: 'displayText', required: true },
      {
        key: 'custom',
        label: '校验',
        type: 'input',
        validator: async (value: BusinessFormValue) => (value === 'ok' ? undefined : '自定义校验失败'),
      },
    ];

    await expect(
      Promise.resolve(
        validateBusinessForm(fields, {
          title: '超长名称',
          count: 1,
          price: 1.23,
          readonlyField: '',
          hiddenField: '',
          summary: '',
          custom: 'bad',
        }),
      ),
    ).resolves.toEqual({
      title: '最多 3 个字符',
      count: '不能低于 2',
      price: '最多保留 1 位小数',
      custom: '自定义校验失败',
    });
  });

  it('caps input and textarea values at maxLength and uses native length display', () => {
    const handleChange = vi.fn();

    render(
      <BusinessForm
        fields={[
          { key: 'title', label: '名称', type: 'input', maxLength: 4, allowInputOverMax: true },
          { key: 'remark', label: '备注', type: 'textarea', maxLength: 5, allowInputOverMax: true },
        ]}
        values={{ title: '', remark: '' }}
        onChange={handleChange}
      />,
    );

    fireEvent.change(screen.getByLabelText('名称'), { target: { value: '超出长度啊' } });
    fireEvent.change(screen.getByLabelText('备注'), { target: { value: '超出长度内容啊' } });

    expect(screen.getByLabelText('名称')).toHaveValue('超出长度');
    expect(screen.getByLabelText('备注')).toHaveValue('超出长度内');
    expect(handleChange).toHaveBeenLastCalledWith(
      { title: '超出长度', remark: '超出长度内' },
      expect.objectContaining({
        key: 'remark',
        value: '超出长度内',
      }),
    );
  });

  it('keeps input, numberInput, select and textarea at the same default width and syncs fieldWidth to all of them', () => {
    const { rerender } = render(
      <BusinessForm
        fields={[
          { key: 'title', label: '名称', type: 'input' },
          { key: 'amount', label: '数量', type: 'numberInput' },
          {
            key: 'status',
            label: '状态',
            type: 'select',
            options: [{ label: '启用', value: 'enabled' }],
          },
          { key: 'remark', label: '备注', type: 'textarea' },
        ]}
        values={{ title: '', amount: 0, status: 'enabled', remark: '' }}
        onChange={vi.fn()}
      />,
    );

    const defaultWidths = ['title', 'amount', 'status', 'remark'].map((key) =>
      screen.getByTestId(`business-form-field-${key}`).getAttribute('data-width'),
    );

    expect(defaultWidths.every((width) => width !== null)).toBe(true);
    expect(new Set(defaultWidths).size).toBe(1);

    rerender(
      <BusinessForm
        fields={[
          { key: 'title', label: '名称', type: 'input' },
          { key: 'amount', label: '数量', type: 'numberInput' },
          {
            key: 'status',
            label: '状态',
            type: 'select',
            options: [{ label: '启用', value: 'enabled' }],
          },
          { key: 'remark', label: '备注', type: 'textarea' },
        ]}
        values={{ title: '', amount: 0, status: 'enabled', remark: '' }}
        onChange={vi.fn()}
        fieldWidth={420}
      />,
    );

    expect(screen.getByTestId('business-form-field-title')).toHaveAttribute('data-width', '420');
    expect(screen.getByTestId('business-form-field-amount')).toHaveAttribute('data-width', '420');
    expect(screen.getByTestId('business-form-field-status')).toHaveAttribute('data-width', '420');
    expect(screen.getByTestId('business-form-field-remark')).toHaveAttribute('data-width', '420');
    expect(getControlHolder('title')).toHaveStyle({ width: '100%', maxWidth: '420px' });
    expect(getControlHolder('amount')).toHaveStyle({ width: '100%', maxWidth: '420px' });
    expect(getControlHolder('status')).toHaveStyle({ width: '100%', maxWidth: '420px' });
    expect(getControlHolder('remark')).toHaveStyle({ width: '100%', maxWidth: '420px' });

    rerender(
      <BusinessForm
        fields={[
          { key: 'title', label: '名称', type: 'input' },
          { key: 'amount', label: '数量', type: 'numberInput' },
          {
            key: 'status',
            label: '状态',
            type: 'select',
            options: [{ label: '启用', value: 'enabled' }],
          },
          { key: 'remark', label: '备注', type: 'textarea' },
        ]}
        values={{ title: '', amount: 0, status: 'enabled', remark: '' }}
        onChange={vi.fn()}
        fieldWidth="w-full max-w-[450px]"
      />,
    );

    expect(getControlHolder('title')).toHaveClass('w-full', 'max-w-[450px]');
    expect(getControlHolder('amount')).toHaveClass('w-full', 'max-w-[450px]');
    expect(getControlHolder('status')).toHaveClass('w-full', 'max-w-[450px]');
    expect(getControlHolder('remark')).toHaveClass('w-full', 'max-w-[450px]');
  });

  it('keeps 40px spacing between form rows', () => {
    const { container } = render(
      <BusinessForm
        fields={[
          { key: 'title', label: '名称', type: 'input' },
          { key: 'amount', label: '数量', type: 'numberInput' },
        ]}
        values={{ title: '', amount: 0 }}
        onChange={vi.fn()}
      />,
    );

    expect(container.querySelector('form')).toHaveStyle({ gap: '40px' });
  });

  it('respects select option disabled, field disabled and readonly native props', () => {
    const onChange = vi.fn();

    render(
      <Harness
        initialValues={{
          status: 'enabled',
          lockedStatus: 'enabled',
          readonlyStatus: 'disabled',
        }}
        fields={[
          {
            key: 'status',
            label: '状态',
            type: 'select',
            options: [
              { label: '启用', value: 'enabled' },
              { label: '停用', value: 'disabled', disabled: true },
            ],
          },
          {
            key: 'lockedStatus',
            label: '禁用状态',
            type: 'select',
            disabled: true,
            options: [
              { label: '启用', value: 'enabled' },
              { label: '停用', value: 'disabled' },
            ],
          },
          {
            key: 'readonlyStatus',
            label: '只读状态',
            type: 'select',
            readonly: true,
            options: [
              { label: '启用', value: 'enabled' },
              { label: '停用', value: 'disabled' },
            ],
          },
        ]}
        onChange={onChange}
      />,
    );

    fireEvent.click(getSelectTrigger('状态'));
    fireEvent.click(getSelectOption('停用'));

    expect(onChange).not.toHaveBeenCalled();
    expect(getSelectTrigger('状态')).toHaveValue('启用');
    expect(getSelectTrigger('禁用状态')).toBeDisabled();
    expect(screen.queryByLabelText('只读状态')).not.toBeInTheDocument();
    expect(within(screen.getByTestId('business-form-field-readonlyStatus')).getByText('停用')).toBeInTheDocument();
  });

  it('supports boolean switch defaults, mapped values and readonly display', () => {
    const onChange = vi.fn();

    render(
      <Harness
        initialValues={{
          enabled: false,
          mapped: 'off',
          readonlySwitch: true,
        }}
        fields={[
          { key: 'enabled', label: '开关', type: 'switch' },
          { key: 'mapped', label: '映射开关', type: 'switch', checkedValue: 'on', uncheckedValue: 'off' },
          { key: 'readonlySwitch', label: '只读开关', type: 'switch', readonly: true },
        ]}
        onChange={onChange}
      />,
    );

    expect(screen.getByRole('switch', { name: '开关' })).not.toBeChecked();
    fireEvent.click(screen.getByRole('switch', { name: '开关' }));
    expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ enabled: true }), 'enabled');

    fireEvent.click(screen.getByRole('switch', { name: '映射开关' }));
    expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ mapped: 'on' }), 'mapped');

    expect(screen.getByText('已开启')).toBeInTheDocument();
    expect(screen.queryByRole('switch', { name: '只读开关' })).not.toBeInTheDocument();
  });

  it('uses TDesign text, image and link primitives for readonly and static upload display', () => {
    render(
      <BusinessForm
        fields={[
          { key: 'summary', label: '说明', type: 'displayText' },
          { key: 'readonlyNote', label: '只读说明', type: 'input', readonly: true },
          { key: 'readonlySwitch', label: '只读开关', type: 'switch', readonly: true },
          {
            key: 'readonlyMedia',
            label: '只读素材',
            type: 'upload',
            uploadType: 'media',
            readonly: true,
            upload: vi.fn(),
          },
          {
            key: 'readonlyFile',
            label: '只读文件',
            type: 'upload',
            uploadType: 'file',
            readonly: true,
            upload: vi.fn(),
          },
        ]}
        values={{
          summary: '展示内容',
          readonlyNote: '只读内容',
          readonlySwitch: true,
          readonlyMedia: { name: 'cover.png', url: '/cover.png', kind: 'image' },
          readonlyFile: { name: 'manual.pdf', url: '/manual.pdf', kind: 'file' },
        }}
        onChange={vi.fn()}
      />,
    );

    const summaryField = screen.getByTestId('business-form-field-summary');
    const readonlyNoteField = screen.getByTestId('business-form-field-readonlyNote');
    const readonlySwitchField = screen.getByTestId('business-form-field-readonlySwitch');
    const readonlyMediaField = screen.getByTestId('business-form-field-readonlyMedia');
    const readonlyFileField = screen.getByTestId('business-form-field-readonlyFile');

    expect(within(summaryField).getByText('展示内容').tagName).toBe('SPAN');
    expect(within(readonlyNoteField).getByText('只读内容').tagName).toBe('SPAN');
    expect(within(readonlySwitchField).getByText('已开启').tagName).toBe('SPAN');
    expect(readonlyMediaField.querySelector('.t-image')).toBeInTheDocument();
    expect(within(readonlyMediaField).getByText('cover.png').tagName).toBe('SPAN');
    expect(readonlyFileField.querySelector('.t-link')).toHaveAttribute('href', '/manual.pdf');
    expect(readonlyFileField.querySelector('.t-link')).toHaveAttribute('target', '_blank');
    expect(readonlyFileField.querySelector('.t-link')).toHaveAttribute('rel', 'noreferrer');
  });

  it('rejects invalid media uploads, uploads media and file values separately, and renders media cards', async () => {
    const upload = vi.fn(async (file: File) => ({ url: `/uploaded/${file.name}` }));
    const failedUpload = vi.fn(async () => {
      throw new Error('后端拒绝');
    });
    const onChange = vi.fn();

    render(
      <BusinessForm
        fields={[
          {
            key: 'invalidMediaUpload',
            label: '媒体校验',
            type: 'upload',
            uploadType: 'media',
            kinds: ['image'],
            accept: '.png',
            maxSize: 1024,
            placeholder: '点击上传',
            helperText: '支持图片、视频、GIF,推荐 1:1,最大 20MB',
            upload,
          },
          {
            key: 'fileUpload',
            label: '文件上传',
            type: 'upload',
            uploadType: 'file',
            kinds: ['file'],
            accept: '.pdf,.zip',
            maxSize: 1024 * 1024,
            upload,
          },
          {
            key: 'failedUpload',
            label: '上传失败',
            type: 'upload',
            uploadType: 'media',
            kinds: ['image'],
            accept: '.png',
            maxSize: 1024 * 1024,
            upload: failedUpload,
          },
        ]}
        values={{
          invalidMediaUpload: undefined,
          fileUpload: { name: 'manual.pdf', url: '/manual.pdf', kind: 'file' },
          failedUpload: { name: 'old.png', url: '/old.png', kind: 'image' },
        }}
        onChange={onChange}
      />,
    );

    const failedField = screen.getByTestId('business-form-field-failedUpload');
    const invalidMediaField = screen.getByTestId('business-form-field-invalidMediaUpload');

    expect(within(invalidMediaField).getByText('点击上传')).toBeInTheDocument();
    expect(invalidMediaField.querySelector('.t-upload__card')).toBeInTheDocument();
    expect(within(invalidMediaField).getByText('支持图片、视频、GIF,推荐 1:1,最大 20MB')).toBeInTheDocument();

    fireEvent.change(getUploadInput('invalidMediaUpload'), {
      target: { files: [new File(['demo'], 'demo.txt', { type: 'text/plain' })] },
    });
    fireEvent.change(getUploadInput('fileUpload'), {
      target: { files: [new File(['ok'], 'manual.zip', { type: 'application/zip' })] },
    });
    fireEvent.change(getUploadInput('failedUpload'), {
      target: { files: [new File(['ok'], 'bad.png', { type: 'image/png' })] },
    });

    await waitFor(() => {
      expect(upload).toHaveBeenCalledTimes(1);
      expect(failedUpload).toHaveBeenCalledTimes(1);
    });

    expect(upload).toHaveBeenNthCalledWith(1, expect.any(File), expect.any(Object));

    await waitFor(() => expect(screen.getByText(/不支持|格式/)).toBeInTheDocument());
    expect(screen.getByText(/后端拒绝|请重试/)).toBeInTheDocument();
    expect(screen.getByText('old.png')).toBeInTheDocument();

    expect(await screen.findByText('manual.zip')).toBeInTheDocument();

    expect(failedField.querySelector('.t-upload__card-mask')).toBeInTheDocument();
    expect(failedField.querySelector('.t-icon-browse')).toBeInTheDocument();
    const deleteIcon = failedField.querySelector('.t-icon-delete');
    expect(deleteIcon).toBeInTheDocument();
    fireEvent.click(deleteIcon as Element);
    await waitFor(() => expect(screen.queryByText('old.png')).not.toBeInTheDocument());
    expect(within(failedField).getByText('点击上传')).toBeInTheDocument();

    const mediaUploadCall = onChange.mock.calls.find(([, changedKey]) => changedKey === 'mediaUpload');
    expect(mediaUploadCall).toBeUndefined();
  });

  it('supports configurable multiple media uploads and keeps the value as an uploaded file array', async () => {
    const upload = vi.fn(async (file: File) => ({
      url: `/uploaded/${file.name}`,
      name: file.name,
      kind: 'video' as const,
    }));
    const onChange = vi.fn();

    const fields = [
      {
        key: 'mediaGallery',
        label: '素材集合',
        type: 'upload',
        uploadType: 'media',
        kinds: ['image', 'gif', 'video'],
        accept: '.png,.gif,.mp4',
        maxCount: 3,
        multiple: true,
        upload,
      },
    ] as BusinessFormField[];

    render(
      <Harness
        fields={fields}
        initialValues={{
          mediaGallery: [
            { name: 'cover.png', url: '/cover.png', kind: 'image' },
            { name: 'motion.gif', url: '/motion.gif', kind: 'gif' },
          ] as BusinessFormValues['mediaGallery'],
        }}
        onChange={onChange}
      />,
    );

    const mediaField = screen.getByTestId('business-form-field-mediaGallery');
    const uploadInput = getUploadInput('mediaGallery');

    expect(uploadInput).toHaveAttribute('multiple');
    expect(within(mediaField).getByText('cover.png')).toBeInTheDocument();
    expect(within(mediaField).getByText('motion.gif')).toBeInTheDocument();

    fireEvent.change(uploadInput, {
      target: { files: [new File(['demo'], 'clip.mp4', { type: 'video/mp4' })] },
    });

    await waitFor(() => expect(upload).toHaveBeenCalledTimes(1));
    await waitFor(() => expect(within(mediaField).getByText('clip.mp4')).toBeInTheDocument());

    const appendCall = onChange.mock.calls.find((call) => {
      const nextValue = call[0].mediaGallery;
      return Array.isArray(nextValue) && nextValue.length === 3;
    });
    expect(appendCall).toBeDefined();
    expect(appendCall?.[0]).toEqual(
      expect.objectContaining({
        mediaGallery: [
          expect.objectContaining({ name: 'cover.png' }),
          expect.objectContaining({ name: 'motion.gif' }),
          expect.objectContaining({ name: 'clip.mp4', kind: 'video' }),
        ],
      }),
    );

    const deleteIcons = mediaField.querySelectorAll('.t-icon-delete');
    expect(deleteIcons.length).toBeGreaterThan(0);
    fireEvent.click(deleteIcons[0]);

    await waitFor(() => expect(within(mediaField).queryByText('cover.png')).not.toBeInTheDocument());
    const removeCall = onChange.mock.calls.find((call) => {
      const nextValue = call[0].mediaGallery;
      return Array.isArray(nextValue) && nextValue.length === 2 && nextValue.every((item) => item?.name !== 'cover.png');
    });
    expect(removeCall).toBeDefined();
  });

  it('passes custom field context, supports setValue and setValues, and keeps custom validation tied to current values', async () => {
    const renderCustom = vi.fn((context: any) => (
      <div>
        <div data-testid="custom-summary">
          {`value:${String(context.value)}|mode:${String(context.values.mode)}|disabled:${String(context.disabled)}|readonly:${String(context.readonly)}|error:${String(context.error ?? '')}`}
        </div>
        <button type="button" onClick={() => context.setValue('patched')}>
          更新当前字段
        </button>
        <button
          type="button"
          onClick={() =>
            context.setValues({
              ...context.values,
              mode: 'lock',
              note: '联动',
              custom: 'batch',
            })
          }
        >
          批量更新
        </button>
      </div>
    ));
    const validator = vi.fn(async (value: string) => (value === 'ok' ? undefined : '自定义字段错误'));
    const onChange = vi.fn();

    const fields: BusinessFormField[] = [
      { key: 'mode', label: '模式', type: 'input' },
      { key: 'note', label: '备注', type: 'input' },
      {
        key: 'custom',
        label: '自定义',
        type: 'custom',
        required: true,
        validator,
        disabled: (currentValues) => currentValues.mode === 'lock',
        readonly: (currentValues) => currentValues.mode === 'read',
        render: renderCustom,
      },
    ] as Parameters<typeof BusinessForm>[0]['fields'];

    render(
      <Harness
        fields={fields}
        initialValues={{
          mode: 'edit',
          note: '',
          custom: 'start',
        }}
        errors={{ custom: '已有错误' }}
        onChange={onChange}
      />,
    );

    expect(renderCustom).toHaveBeenCalledWith(
      expect.objectContaining({
        value: 'start',
        values: expect.objectContaining({
          mode: 'edit',
          note: '',
          custom: 'start',
        }),
        disabled: false,
        readonly: false,
        error: '已有错误',
        setValue: expect.any(Function),
        setValues: expect.any(Function),
      }),
    );
    expect(screen.getByTestId('custom-summary')).toHaveTextContent('value:start');
    expect(screen.getByTestId('custom-summary')).toHaveTextContent('disabled:false');
    expect(screen.getByTestId('custom-summary')).toHaveTextContent('readonly:false');
    expect(screen.getByTestId('custom-summary')).toHaveTextContent('error:已有错误');

    fireEvent.change(screen.getByLabelText('模式'), { target: { value: 'lock' } });
    expect(screen.getByTestId('custom-summary')).toHaveTextContent('disabled:true');

    fireEvent.change(screen.getByLabelText('模式'), { target: { value: 'read' } });
    expect(screen.getByTestId('custom-summary')).toHaveTextContent('readonly:true');

    fireEvent.click(screen.getByRole('button', { name: '更新当前字段' }));
    expect(onChange).toHaveBeenCalledWith(
      expect.objectContaining({
        custom: 'patched',
      }),
      'custom',
    );

    fireEvent.click(screen.getByRole('button', { name: '批量更新' }));
    expect(onChange).toHaveBeenCalledWith(
      expect.objectContaining({
        mode: 'lock',
        note: '联动',
        custom: 'batch',
      }),
      'custom',
    );

    await expect(
      validateBusinessForm(fields, {
        mode: 'edit',
        note: '',
        custom: 'bad',
      }),
    ).resolves.toEqual({
      custom: '自定义字段错误',
    });
  });
});