BasicForm.tsx 29.4 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
import { useEffect, useMemo, useState } from 'react';
import type { FormInstance } from 'antd';
import dayjs from 'dayjs';
import {
  UButton,
  UCheckbox,
  UDatePicker,
  UForm,
  UFormItem,
  UInput,
  URadio,
  USelect,
  UTree,
  useUMessage,
} from '@uj/ui';
import type { FieldOption } from '@/components';
import { commonApi } from '@/api';
import { errorDetail } from '@/utils/error';
import { AddressModal, type AddressValue } from './AddressModal';
import type { BrandNode, CreateFormValues, MerchantFile } from './model';
import { PASSWORD_REGEX, PHONE_REGEX, RESIDENT_PHONE_REGEX, asArray } from './model';
import { SectionTitle } from './ui';
import { PROVINCES, citiesOf } from './regions';

interface ControlProps {
  value?: unknown;
  onChange?: (value: unknown) => void;
}

export type FormMode = 'create' | 'edit' | 'sub';

export interface SubParentInfo {
  parentName?: string;
  merchantModelName?: string;
}

interface BasicFormProps {
  form: FormInstance<CreateFormValues>;
  options: {
    channel: FieldOption[];
    accountLevel: FieldOption[];
    accountType: FieldOption[];
    businessType: FieldOption[];
  };
  channelId?: string | number;
  brandTree: BrandNode[];
  /** 源 L1090-1094:首次保存后账户类型不可再改。 */
  accountTypeLocked: boolean;
  /** create=两步创建;sub=创建子商户;edit=修改商户(edit.html 基本信息 tab)。 */
  mode?: FormMode;
  /** 子商户:源 addSubMerchant.html:478-495 的上级商户/上级商户模式只读行。 */
  parent?: SubParentInfo | null;
  /** edit:开通模式 radio 显隐(源 init() L1763-1771 由 status/model 决定)。 */
  modelVisible?: boolean;
  /** 账户有效期块显隐;quick=edit 三按钮(续7天/1年/2年),sub 五按钮(+5年/10年)。 */
  validityVisible?: boolean;
  validityQuick?: 'edit' | 'sub';
}

const REQUIRED = { required: true, message: '必填项不能为空' };
const formOptions = (options: FieldOption[]) => options.filter((item) => item.value !== '');

function ModelControl({ value, onChange }: ControlProps) {
  return (
    <URadio.Group
      className="uj-mode-group"
      value={value as string | number | undefined}
      onChange={(event) => onChange?.(event.target.value)}
    >
      <URadio value="2">
        单店企微版<span className="uj-hint">(一个门店一个企微账户授权)</span>
      </URadio>
      <URadio value="1">
        集团企微版<span className="uj-hint">(集团多个企微共用一个企微账户授权)</span>
      </URadio>
    </URadio.Group>
  );
}

/**
 * 联系电话 + 两个附属开关。
 * 开关值用本地 state 驱动,onChange 时双写表单——不依赖 useWatch 读取,
 * 避免首帧 store 未注入时永远读到 undefined 导致「点不动」。
 */
function PhoneControl({
  value,
  onChange,
  form,
}: ControlProps & { form: FormInstance<CreateFormValues> }) {
  const [phone, setPhone] = useState(() => String(value ?? ''));
  const [loginAsName, setLoginAsName] = useState(
    () => Number(form.getFieldValue('isloginName') ?? 0) === 1,
  );
  const [smsVerify, setSmsVerify] = useState(
    () => Number(form.getFieldValue('mesVerifyFlag') ?? 0) === 1,
  );

  useEffect(() => {
    setPhone(String(value ?? ''));
  }, [value]);

  return (
    <div className="uj-phone">
      <UInput
        value={phone}
        maxLength={11}
        placeholder="请输入联系电话"
        onChange={(event) => {
          setPhone(event.target.value);
          onChange?.(event.target.value);
        }}
      />
      <div className="uj-phone__flags">
        <UCheckbox
          checked={loginAsName}
          onChange={(event) => {
            const next = event.target.checked;
            setLoginAsName(next);
            form.setFieldValue('isloginName', next ? 1 : 0);
          }}
        >
          联系电话同时作为登录账户名
        </UCheckbox>
        <UCheckbox
          checked={smsVerify}
          onChange={(event) => {
            const next = event.target.checked;
            setSmsVerify(next);
            form.setFieldValue('mesVerifyFlag', next ? 1 : 0);
          }}
        >
          开启短信验证登录
        </UCheckbox>
      </div>
    </div>
  );
}

function toDayjs(value?: string) {
  if (!value) return null;
  const [hour = '0', minute = '0', second = '0'] = value.split(':');
  return dayjs().hour(Number(hour)).minute(Number(minute)).second(Number(second));
}

function parts(value?: string) {
  const [hour = '0', minute = '0', second = '0'] = (value ?? '').split(':');
  return [Number(hour), Number(minute), Number(second)];
}

/** 源 L741-770:开始/结束时间互设 min/max,格式 HH:mm:ss。 */
function TimeControl({ form }: { form: FormInstance<CreateFormValues> }) {
  const [start, setStart] = useState(() => String(form.getFieldValue('bussinessBegintime') ?? ''));
  const [end, setEnd] = useState(() => String(form.getFieldValue('bussinessEndtime') ?? ''));
  const limit = (bound?: string) => ({
    disabledHours: () => {
      const [hour] = parts(bound);
      return Array.from({ length: hour }, (_, index) => index);
    },
    disabledMinutes: (hour: number) => {
      const [boundHour, minute] = parts(bound);
      return hour === boundHour ? Array.from({ length: minute }, (_, index) => index) : [];
    },
    disabledSeconds: (hour: number, minute: number) => {
      const [boundHour, boundMinute, second] = parts(bound);
      return hour === boundHour && minute === boundMinute
        ? Array.from({ length: second }, (_, index) => index)
        : [];
    },
  });
  return (
    <div className="uj-time">
      <UDatePicker.TimePicker
        value={toDayjs(start)}
        format="HH:mm:ss"
        placeholder="开始时间"
        disabledTime={() => (end ? limit(end) : {})}
        onChange={(next) => {
          const text = next?.format('HH:mm:ss') ?? '';
          setStart(text);
          form.setFieldValue('bussinessBegintime', text);
        }}
      />
      <span className="uj-time__sep">—</span>
      <UDatePicker.TimePicker
        value={toDayjs(end)}
        format="HH:mm:ss"
        placeholder="结束时间"
        disabledTime={() => (start ? limit(start) : {})}
        onChange={(next) => {
          const text = next?.format('HH:mm:ss') ?? '';
          setEnd(text);
          form.setFieldValue('bussinessEndtime', text);
        }}
      />
    </div>
  );
}

/**
 * 编辑态登录密码(源 edit.html:361-376 + L1046-1049):
 * 默认 readonly 展示详情回填值,点「重置密码」清空并解锁编辑。
 */
function PasswordEditControl({
  value,
  onChange,
}: ControlProps) {
  const [reset, setReset] = useState(false);
  return (
    <div className="uj-time">
      <UInput
        style={{ flex: 1, minWidth: 0 }}
        type="password"
        maxLength={20}
        autoComplete="off"
        readOnly={!reset}
        value={String(value ?? '')}
        placeholder={reset ? '请输入密码(必须包含6-20个字母+数字)' : '如需修改请点右侧「重置密码」'}
        onChange={(event) => reset && onChange?.(event.target.value)}
      />
      <UButton className="uj-password__reset" onClick={() => setReset(true)}>
        重置密码
      </UButton>
    </div>
  );
}

function dateText(value?: dayjs.Dayjs | dayjs.Dayjs[] | string | null) {
  const single = Array.isArray(value) ? value[0] : value;
  const d = dayjs.isDayjs(single) ? single : single ? dayjs(single) : null;
  return d && d.isValid() ? d.format('YYYY-MM-DD') : '';
}

/**
 * 账户有效期(源 edit.html:377-391 / addSubMerchant.html:539-555):
 * 开始/结束日期 + 快捷续期按钮;开始时清空结束时间并抬高其下限。
 * 过期感知:起算取 max(今天, 原到期日+1),见 validPeriodForm.html 同口径。
 */
function ValidityControl({
  form,
  quick,
  expiredAt,
}: {
  form: FormInstance<CreateFormValues>;
  quick: 'edit' | 'sub';
  /** 原到期日(yyyy-MM-dd);已过期时续期从到期日起算,与源 validPeriodForm 一致。 */
  expiredAt?: string;
}) {
  const [start, setStart] = useState(() => dateText(form.getFieldValue('effectiveStarttime')));
  const [end, setEnd] = useState(() => dateText(form.getFieldValue('expireDate')));
  const write = (nextStart: string, nextEnd: string) => {
    setStart(nextStart);
    setEnd(nextEnd);
    form.setFieldsValue({ effectiveStarttime: nextStart, expireDate: nextEnd });
  };
  const quickButtons: Array<[string, number]> =
    quick === 'sub'
      ? [['续7天', 7], ['续1年', 365], ['续2年', 730], ['续5年', 1825], ['续10年', 3650]]
      : [['续7天', 7], ['续1年', 365], ['续2年', 730]];
  const applyQuick = (label: string) => {
    const today = dayjs().startOf('day');
    const origin =
      expiredAt && dayjs(expiredAt).isBefore(today, 'day') ? dayjs(expiredAt) : today;
    const years = label.includes('年') ? Number(label.replace(/[^\d]/g, '')) || 1 : 0;
    const nextEnd = years ? origin.add(years, 'year') : origin.add(7, 'day');
    write(origin.format('YYYY-MM-DD'), nextEnd.format('YYYY-MM-DD'));
  };
  const startDate = start ? dayjs(start) : null;
  return (
    <div className="uj-validity">
      <UDatePicker
        value={startDate}
        minDate={dayjs().startOf('day')}
        placeholder="开始时间"
        onChange={(next) => {
          const text = dateText(next ?? undefined);
          setStart(text);
          setEnd('');
          form.setFieldsValue({ effectiveStarttime: text, expireDate: undefined });
        }}
      />
      <span className="uj-time__sep">—</span>
      <UDatePicker
        value={end ? dayjs(end) : null}
        minDate={startDate ? startDate.add(1, 'day') : dayjs().add(1, 'day')}
        placeholder="结束时间"
        onChange={(next) => {
          const text = dateText(next ?? undefined);
          setEnd(text);
          form.setFieldValue('expireDate', text);
        }}
      />
      <span className="uj-validity__quick">
        {quickButtons.map(([label]) => (
          <UButton key={label} size="small" onClick={() => applyQuick(label)}>
            {label}
          </UButton>
        ))}
      </span>
    </div>
  );
}

function BrandControl({ value, onChange, tree }: ControlProps & { tree: BrandNode[] }) {
  const [keyword, setKeyword] = useState('');
  // 源 bindEvent() L1466-1502:输入后 helper.debounce(..., 500) 再过滤树。
  const [debouncedKeyword, setDebouncedKeyword] = useState('');
  useEffect(() => {
    const timer = window.setTimeout(() => setDebouncedKeyword(keyword.trim()), 500);
    return () => window.clearTimeout(timer);
  }, [keyword]);
  // 源 add.html:1266-1279:单个按钮在「全选 / 全不选」间切换。
  const [checkAll, setCheckAll] = useState(false);
  const checked = useMemo(() => asArray<string | number>(value).map(String), [value]);
  const visible = useMemo(() => {
    const text = debouncedKeyword;
    const keep = (nodes: BrandNode[]): BrandNode[] =>
      nodes.reduce<BrandNode[]>((result, node) => {
        const children = keep(node.children ?? []);
        if (!text || String(node.label ?? '').includes(text) || children.length) {
          // checkedKeys 内部按字符串比对 key;数字 id 必须显式转成字符串。
          result.push({
            ...node,
            key: node.id === undefined ? undefined : String(node.id),
            children,
          });
        }
        return result;
      }, []);
    return keep(tree);
  }, [debouncedKeyword, tree]);
  const allLeafKeys = useMemo(() => {
    const keys: Array<string | number> = [];
    const walk = (nodes: BrandNode[]) =>
      nodes.forEach((node) => {
        if (node.children?.length) walk(node.children);
        else if (node.id !== undefined && node.id !== null) keys.push(String(node.id));
      });
    walk(tree);
    return keys;
  }, [tree]);

  if (!tree.length) return <span className="uj-hint">暂无数据</span>;
  return (
    <div className="uj-brand">
      <div className="uj-brand__bar">
        <UInput
          value={keyword}
          placeholder="搜索品牌 / 子品牌"
          onChange={(event) => setKeyword(event.target.value)}
        />
        <UButton
          size="small"
          onClick={() => {
            const next = !checkAll;
            setCheckAll(next);
            onChange?.(next ? allLeafKeys : []);
          }}
        >
          {checkAll ? '全不选' : '全选'}
        </UButton>
      </div>
      <UTree
        checkable
        blockNode
        height={440}
        // 源 gtree.js:31-35 是 selectedMulti:false(可单选节点),不是「不可选中」。
        fieldNames={{ title: 'label', children: 'children' }}
        treeData={visible as never}
        checkedKeys={checked}
        onCheck={(keys) => onChange?.(asArray<string | number>(keys).map(String))}
      />
    </div>
  );
}

function ImageControl({ value, onChange }: ControlProps) {
  const message = useUMessage();
  const [uploading, setUploading] = useState<number | null>(null);
  const files = asArray<MerchantFile>(value);
  const inputs = useMemo(
    () => Array.from({ length: 3 }, () => ({ current: null as HTMLInputElement | null })),
    [],
  );

  const upload = async (file: File | undefined, index: number) => {
    if (!file) return;
    // 源 add.html:1290:fileInfo.name.split('.')[1] + '@' + base64。
    const ext = file.name.split('.')[1] ?? '';
    setUploading(index);
    try {
      const base64 = await new Promise<string>((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(String(reader.result ?? '').split(',')[1] ?? '');
        reader.onerror = () => reject(reader.error);
        reader.readAsDataURL(file);
      });
      const url = await commonApi.uploadFile(`${ext}@${base64}`);
      if (!url) throw new Error('上传文件失败');
      const next = [...files];
      next[index] = { fileUrl: url, fileName: '' };
      onChange?.(next);
    } catch (error) {
      message.error(errorDetail(error));
    } finally {
      setUploading(null);
    }
  };

  const remove = (index: number) => {
    // 直接压缩数组,保持连续槽位;后续上传仍按 0/1/2 三个框对齐。
    onChange?.(files.filter((_, position) => position !== index));
  };

  return (
    <div className="uj-images">
      <div className="uj-images__list">
        {[0, 1, 2].map((index) => {
          const file = files[index];
          return (
            <div key={index} className="uj-images__box">
              <button
                type="button"
                className={`uj-images__trigger${uploading === index ? ' is-uploading' : ''}`}
                onClick={() => inputs[index]?.current?.click()}
                title={uploading === index ? '正在上传…' : '点击上传门店照片'}
              >
                {file?.fileUrl ? (
                  <img src={file.fileUrl} alt={`门店照片 ${index + 1}`} />
                ) : (
                  <span className="uj-images__plus">+</span>
                )}
              </button>
              {file?.fileUrl ? (
                <button
                  type="button"
                  className="uj-images__remove"
                  title="删除照片"
                  aria-label={`删除门店照片 ${index + 1}`}
                  onClick={() => remove(index)}
                >
                  ×
                </button>
              ) : null}
              <input
                ref={(node) => {
                  if (inputs[index]) inputs[index].current = node;
                }}
                type="file"
                accept="image/png, image/jpeg, image/gif, image/jpg"
                style={{ display: 'none' }}
                onChange={(event) => {
                  void upload(event.target.files?.[0], index);
                  event.target.value = '';
                }}
              />
            </div>
          );
        })}
      </div>
      <span className="uj-hint">支持 JPG、PNG 格式,单张 1M 以内,最多 3 张</span>
    </div>
  );
}

/**
 * 省 / 市 / 详细地址 / 地图入口。
 * 源 add.html:1825-1870 省市是可编辑级联下拉,选省清空市与详细地址(L1842/1848-1849);
 * 被 disabled 的是详细地址输入框(L357 merchantAddress disabled),只能由地图回填。
 * 省市用本地 state 驱动,地图回填时一并同步,彻底避免 useWatch 读不到值。
 */
function AddressControl({
  value,
  onChange,
  form,
}: ControlProps & { form: FormInstance<CreateFormValues> }) {
  const [open, setOpen] = useState(false);
  const [province, setProvince] = useState(() => String(form.getFieldValue('provinceName') ?? ''));
  const [city, setCity] = useState(() => String(form.getFieldValue('cityName') ?? ''));
  const [address, setAddress] = useState(() => String(value ?? ''));
  const lat = String(form.getFieldValue('lat') ?? '');
  const lng = String(form.getFieldValue('lng') ?? '');
  const toOptions = (names: string[]): FieldOption[] =>
    names.map((name) => ({ label: name, value: name }));
  // 选中值置顶但去重:重复 value 会让 rc-virtual-list 高度测量互相打架,渲染死循环、整页卡死。
  const withCurrent = (current: string, names: string[]): string[] =>
    current && !names.includes(current) ? [current, ...names] : names;

  useEffect(() => {
    setAddress(String(value ?? ''));
  }, [value]);

  const chooseProvince = (next?: string) => {
    setProvince(next ?? '');
    setCity('');
    setAddress('');
    form.setFieldsValue({
      provinceName: next || undefined,
      cityName: undefined,
      lat: undefined,
      lng: undefined,
    });
    onChange?.('');
  };

  const chooseCity = (next?: string) => {
    setCity(next ?? '');
    setAddress('');
    form.setFieldValue('cityName', next || undefined);
    onChange?.('');
  };

  return (
    <div className="uj-address">
      <div className="uj-address__row">
        <USelect
          value={province || undefined}
          options={toOptions(withCurrent(province, PROVINCES))}
          placeholder="省"
          showSearch
          onChange={chooseProvince}
          className="uj-address__province"
        />
        <USelect
          value={city || undefined}
          options={toOptions(withCurrent(city, citiesOf(province)))}
          placeholder="市"
          showSearch
          disabled={!province}
          onChange={chooseCity}
          className="uj-address__city"
        />
        <UInput
          value={address}
          disabled
          placeholder="在地图上选点后自动回填详细地址"
          className="uj-address__input"
          suffix={
            lat && lng ? (
              <span className="uj-address__coords">
                经度 {lng} / 纬度 {lat}
              </span>
            ) : null
          }
        />
        <UButton onClick={() => setOpen(true)}>选择地址</UButton>
      </div>
      <AddressModal
        open={open}
        initial={{ merchantAddress: address, provinceName: province, cityName: city, lat, lng }}
        onCancel={() => setOpen(false)}
        onOk={(next: AddressValue) => {
          setProvince(next.provinceName ?? '');
          setCity(next.cityName ?? '');
          setAddress(next.merchantAddress ?? '');
          form.setFieldsValue({
            merchantAddress: next.merchantAddress,
            lat: next.lat,
            lng: next.lng,
            provinceName: next.provinceName,
            cityName: next.cityName,
          });
          onChange?.(next.merchantAddress ?? '');
          setOpen(false);
        }}
      />
    </div>
  );
}

export function BasicForm({
  form,
  options,
  channelId,
  brandTree,
  accountTypeLocked,
  mode = 'create',
  parent,
  modelVisible,
  validityVisible,
  validityQuick = 'sub',
  expiredAt,
}: BasicFormProps & { expiredAt?: string }) {
  const isEdit = mode === 'edit';
  return (
    <UForm form={form} layout="vertical">
      {/* 渠道控件在页面标题右侧;源 add.html:262 的 lay-verify="channelId" 仍要参与校验。
          edit/sub 无渠道控件,仅承载详情/父级回填值。 */}
      <UFormItem
        name="channelId"
        rules={mode === 'create' ? [REQUIRED] : undefined}
        style={{ display: 'none' }}
      >
        <UInput />
      </UFormItem>

      <section className="uj-section">
        <SectionTitle index="01" description="商户主体与门店经营信息">
          企业基本信息
        </SectionTitle>
        <div className="uj-form-grid">
          {mode === 'sub' && parent ? (
            <div className="uj-full uj-parent-row">
              <span>
                <em>上级商户</em>
                {parent.parentName || '-'}
              </span>
              <span>
                <em>上级商户模式</em>
                {parent.merchantModelName || '-'}
              </span>
            </div>
          ) : null}
          {!isEdit || modelVisible ? (
            <UFormItem
              label="选择开通模式"
              name="merchantModel"
              rules={[REQUIRED]}
              className="uj-full"
            >
              <ModelControl />
            </UFormItem>
          ) : null}
          <UFormItem
            label="商户名称"
            name="merchantName"
            className="uj-col-4"
            rules={[
              { required: true, message: '请输入商户名称' },
              { max: 50, message: '最多 50 个字符' },
            ]}
          >
            <UInput maxLength={50} placeholder="请输入商户名称" />
          </UFormItem>
          <UFormItem
            label="商户简称"
            name="merchantAbbreviation"
            className="uj-col-4"
            rules={[{ max: 15, message: '最多 15 个字符' }]}
          >
            <UInput maxLength={15} placeholder="请输入商户简称" />
          </UFormItem>
          <UFormItem
            label="联系人"
            name="merchantLegalPerson"
            className="uj-col-4"
            rules={[{ max: 15, message: '最多 15 个字符' }]}
          >
            <UInput maxLength={15} placeholder="请输入联系人姓名" />
          </UFormItem>
          <UFormItem
            label="联系电话"
            name="merchantLegalPersonPhone"
            className="uj-col-6"
            rules={[
              { required: true, message: '必填项不能为空' },
              { pattern: PHONE_REGEX, message: '请填写正确的手机号' },
            ]}
          >
            <PhoneControl form={form} />
          </UFormItem>
          {String(channelId) === '2' ? (
            <UFormItem
              label="商户SAP编码"
              name="sapCode"
              className="uj-col-6"
              rules={[{ max: 15, message: '最多 15 个字符' }]}
            >
              <UInput maxLength={15} placeholder="请输入商户SAP编码" />
            </UFormItem>
          ) : null}
          <UFormItem label="商户地址" name="merchantAddress" rules={[REQUIRED]} className="uj-full">
            <AddressControl form={form} />
          </UFormItem>
          <UFormItem
            label="驻店联系人"
            name="residentContact"
            className="uj-col-4"
            rules={[{ max: 15, message: '最多 15 个字符' }]}
          >
            <UInput maxLength={15} placeholder="请输入驻店联系人" />
          </UFormItem>
          <UFormItem
            label="驻店电话"
            name="residentPhone"
            className="uj-col-4"
            rules={[
              { pattern: RESIDENT_PHONE_REGEX, message: '请填入正确的驻店电话' },
              { max: 13, message: '最多 13 个字符' },
            ]}
          >
            <UInput maxLength={13} placeholder="请输入驻店电话" />
          </UFormItem>
          <UFormItem label="营业时间" className="uj-col-6">
            <TimeControl form={form} />
          </UFormItem>
          <UFormItem label="经营业务类型" name="businessType" className="uj-col-6">
            <UCheckbox.Group
              options={options.businessType.map((item) => ({
                label: item.label,
                value: item.value,
                disabled: Number(item.value) <= 6,
              }))}
            />
          </UFormItem>
          {/* 主营品牌右侧跨两行,与左侧「经营业务类型 + 门店照片」同高;树区相应加高。 */}
          <UFormItem label="主营品牌" name="merchantBrandChecked" className="uj-col-6 uj-brand-side">
            <BrandControl tree={brandTree} />
          </UFormItem>
          <UFormItem
            label="门店照片"
            name="merchantFiles"
            className="uj-col-6 uj-images-item"
          >
            <ImageControl />
          </UFormItem>
        </div>
      </section>

      <section className="uj-section">
        <SectionTitle index="02" description="商户平台登录与权限模板">
          账户基本信息
        </SectionTitle>
        <div className="uj-form-grid">
          <UFormItem
            label="登录账户名"
            name="merchantLoginAccount"
            className="uj-col-4"
            rules={[
              REQUIRED,
              { max: 15, message: '登录账户名请填入3-15位字符' },
              ...(isEdit
                ? []
                : [
                    {
                      validator: (_rule: unknown, value: string | undefined) => {
                        if (!value) return Promise.resolve();
                        if (value.length < 3)
                          return Promise.reject(new Error('登录账户名请填入3-15位字符'));
                        if (value.length === 11 && !Number.isNaN(Number(value)))
                          return Promise.reject(new Error('登录账户名不可为 11 位纯数字'));
                        return Promise.resolve();
                      },
                    },
                  ]),
            ]}
          >
            <UInput
              maxLength={15}
              placeholder="请输入登录账户名"
              autoComplete="off"
              disabled={isEdit}
            />
          </UFormItem>
          {isEdit ? (
            <UFormItem
              label="登录密码"
              name="merchantLoginPassword"
              className="uj-col-6"
              rules={[
                {
                  validator: (_rule: unknown, value: string | undefined) => {
                    if (!value) return Promise.resolve();
                    if (value.length < 6 || value.length > 20)
                      return Promise.reject(new Error('登录密码请填入6-20位字符'));
                    if (!PASSWORD_REGEX.test(value))
                      return Promise.reject(
                        new Error('您输入的密码格式不正确,必须同时包含字母、数字。'),
                      );
                    return Promise.resolve();
                  },
                },
              ]}
            >
              <PasswordEditControl />
            </UFormItem>
          ) : (
            <UFormItem
              label="登录密码"
              name="merchantLoginPassword"
              className="uj-col-4"
              rules={[
                REQUIRED,
                {
                  validator: (_rule: unknown, value: string | undefined) => {
                    if (!value) return Promise.resolve();
                    if (value.length < 6 || value.length > 20)
                      return Promise.reject(new Error('登录密码请填入6-20位字符'));
                    if (!PASSWORD_REGEX.test(value))
                      return Promise.reject(
                        new Error('您输入的密码格式不正确,必须同时包含字母、数字。'),
                      );
                    return Promise.resolve();
                  },
                },
              ]}
            >
              <UInput
                type="password"
                maxLength={20}
                placeholder="请输入密码(必须包含6-20个字母+数字)"
                autoComplete="off"
              />
            </UFormItem>
          )}
          {!isEdit ? (
            <UFormItem
              label="账户等级"
              name="merchantAccountLevel"
              className="uj-col-4"
              rules={mode === 'sub' ? [REQUIRED] : undefined}
              // 源 add.html:1392 创建态把 #accountLevelEl 置 disabled;子商户可选(源 addSubMerchant.html:536)。
            >
              <USelect
                options={formOptions(options.accountLevel)}
                disabled={mode === 'create'}
                placeholder="请选择"
                style={{ width: '100%' }}
              />
            </UFormItem>
          ) : null}
          <UFormItem
            label="账户类型"
            name="accounttypeId"
            className={isEdit ? 'uj-col-8' : 'uj-full'}
            rules={[REQUIRED]}
          >
            <UCheckbox.Group
              disabled={accountTypeLocked}
              options={options.accountType.map((item) => ({
                label: item.label,
                value: item.value,
              }))}
            />
          </UFormItem>
          {validityVisible ? (
            <UFormItem label="账户有效期" className="uj-full">
              <ValidityControl form={form} quick={validityQuick} expiredAt={expiredAt} />
            </UFormItem>
          ) : null}
          {/* 源 add.html:508-522 的账户有效期区间块初始 hide 且脚本无 show 操作;
              L565-570 的 effectiveTime 下拉在注释里。创建页不渲染这两处,避免臆造控件。 */}
        </div>
      </section>
    </UForm>
  );
}