export const GLOBAL_FIELD_ALIASES = {
  // 内部信息 / HIS 相关字段可能后续改名：这里做最小兜底，保证“有值就能显示”
  hisCardNo: ['hisOutpatientNo', 'hisClinicNo', 'hisCardNumber'],
  idCard: ['idNo', 'idNumber'],
  sex: ['gender'],
  cardType: ['idType'],
};

function isEmpty(v) {
  if (v === null || v === undefined) return true;
  if (Array.isArray(v)) return v.length === 0;
  if (typeof v === 'string') return v.trim() === '';
  return false;
}

function buildAliasCandidates(items) {
  const itemList = Array.isArray(items) ? items : [];
  const map = {};

  // 支持模板项自带别名：aliasTitles / aliases
  itemList.forEach((it) => {
    const title = it?.title;
    if (!title) return;
    const aliases = Array.isArray(it?.aliasTitles)
      ? it.aliasTitles
      : Array.isArray(it?.aliases)
        ? it.aliases
        : [];
    if (!aliases.length) return;
    map[String(title)] = aliases.map((i) => String(i)).filter(Boolean);
  });

  return map;
}

function uniq(arr) {
  const out = [];
  const seen = new Set();
  arr.forEach((i) => {
    const v = String(i || '');
    if (!v || seen.has(v)) return;
    seen.add(v);
    out.push(v);
  });
  return out;
}

export function createAliasedForm(form, items) {
  const local = buildAliasCandidates(items);
  return new Proxy(form || {}, {
    get(target, prop) {
      if (typeof prop !== 'string') return target[prop];

      const direct = target[prop];
      if (!isEmpty(direct)) return direct;

      const candidates = uniq([...(local[prop] || []), ...(GLOBAL_FIELD_ALIASES[prop] || [])]);
      for (const k of candidates) {
        const v = target[k];
        if (!isEmpty(v)) return v;
      }
      return direct;
    },
  });
}

