AddressModal.tsx 5.36 KB
import { useCallback, useEffect, useRef, useState } from 'react';
import { UAlert, UButton, UModal, useUMessage } from '@uj/ui';
import { buildMapFrameHtml, type MapFrameEvent, type MapFrameValue } from './mapFrame';

/**
 * 源 temp/account/html/merchant/map.html 的选点流程移植。
 *
 * 地图本体跑在 srcdoc iframe(独立 realm)里,原因见 mapFrame.ts 头部:
 * wujie 会劫持子应用动态 <script src> 走 fetch,百度 3.0 的 verify/风控脚本
 * 无 CORS 头必失败;源 map.html 本身就是独立页面,iframe 才是对等运行环境。
 * 这里只负责拿配置中心 apiUrl 与收发选点结果,与源页父窗口的
 * helper.store('merchantMapObj') 对等(源 map.html:132)。
 */

/** 配置中心 map-api-js 地址,逐字取自源 js/glsk-mapapi-sdk.js(env=3 → production)。 */
const GLMAP_CONFIG_URL =
  'https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=map-api-js&env=production';

interface MapFrameWindow extends Window {
  __ujMapCallback?: (event: MapFrameEvent) => void;
  __ujMapFlush?: () => void;
}

let apiUrlPromise: Promise<string> | undefined;

function loadApiUrl(): Promise<string> {
  if (!apiUrlPromise) {
    apiUrlPromise = (async () => {
      const response = await fetch(GLMAP_CONFIG_URL);
      const config = (await response.json()) as { apiUrl?: string };
      if (!config.apiUrl) throw new Error('配置中心 map-api-js 未下发 apiUrl');
      return config.apiUrl;
    })().catch((error: unknown) => {
      apiUrlPromise = undefined;
      throw error;
    });
  }
  return apiUrlPromise;
}

export interface AddressValue {
  merchantAddress?: string;
  lat?: string;
  lng?: string;
  provinceName?: string;
  cityName?: string;
}

interface AddressModalProps {
  open: boolean;
  initial?: AddressValue;
  onOk: (value: AddressValue) => void;
  onCancel: () => void;
}

export function AddressModal({ open, initial, onOk, onCancel }: AddressModalProps) {
  const message = useUMessage();
  const messageRef = useRef(message);
  messageRef.current = message;
  const frameRef = useRef<HTMLIFrameElement | null>(null);
  const [frameHtml, setFrameHtml] = useState('');
  const [error, setError] = useState('');
  const valueRef = useRef<MapFrameValue | null>(null);

  const handleFrameEvent = useCallback((event: MapFrameEvent) => {
    switch (event.type) {
      case 'change':
        valueRef.current = event.payload;
        break;
      case 'warn':
        messageRef.current.warning(event.payload.message);
        break;
      case 'error':
        setError(event.payload.message);
        break;
      case 'ready':
        break;
    }
  }, []);

  // srcdoc iframe 的 parent 是主 window(wujie 非降级把 DOM 放在 shadowRoot),
  // postMessage 到不了子应用执行 iframe window。改为 onLoad 时直接注入函数引用。
  const handleFrameLoad = useCallback(() => {
    const win = frameRef.current?.contentWindow as MapFrameWindow | null;
    if (!win) return;
    win.__ujMapCallback = handleFrameEvent;
    win.__ujMapFlush?.();
  }, [handleFrameEvent]);

  useEffect(() => {
    if (!open) return;
    let cancelled = false;
    setError('');
    setFrameHtml('');
    valueRef.current =
      initial?.lat && initial?.lng
        ? {
            lat: Number(initial.lat),
            lng: Number(initial.lng),
            merchantAddress: initial?.merchantAddress ?? '',
            provinceName: initial?.provinceName ?? '',
            cityName: initial?.cityName ?? '',
          }
        : null;

    loadApiUrl()
      .then((apiUrl) => {
        if (cancelled) return;
        setFrameHtml(
          buildMapFrameHtml(apiUrl, {
            lat: initial?.lat,
            lng: initial?.lng,
            merchantAddress: initial?.merchantAddress,
          }),
        );
      })
      .catch((loadError: unknown) => {
        if (!cancelled)
          setError(loadError instanceof Error ? loadError.message : String(loadError));
      });

    return () => {
      cancelled = true;
    };
  }, [
    open,
    initial?.lat,
    initial?.lng,
    initial?.merchantAddress,
    initial?.provinceName,
    initial?.cityName,
  ]);

  function confirm() {
    const value = valueRef.current;
    if (!value?.lat || !value?.lng || !value.merchantAddress.trim()) {
      message.warning('请选择地址');
      return;
    }
    onOk({
      lat: value.lat.toFixed(6),
      lng: value.lng.toFixed(6),
      merchantAddress: value.merchantAddress.trim(),
      provinceName: value.provinceName,
      cityName: value.cityName,
    });
  }

  return (
    <UModal
      className="uj-map-modal"
      title="选择地址"
      open={open}
      width="min(1080px, 92vw)"
      onCancel={onCancel}
      footer={
        <div className="uj-map-modal__footer">
          <UButton onClick={onCancel}>取消</UButton>
          <UButton type="primary" onClick={confirm}>
            确定
          </UButton>
        </div>
      }
    >
      {error ? <UAlert type="error" showIcon title="地图不可用" description={error} /> : null}
      {frameHtml ? (
        // srcdoc 变化(换初始坐标)时强制重建 iframe,避免沿用上一次的地图实例。
        <iframe
          ref={frameRef}
          key={frameHtml}
          title="地图选点"
          srcDoc={frameHtml}
          className="uj-create-address__frame"
          onLoad={handleFrameLoad}
        />
      ) : null}
    </UModal>
  );
}