/**
 * 就诊人健康问诊 → 病历「史」字段
 * 映射与后端 MedicalRecordService::resolveHistoryDefaultsFromPatient 一致：
 * present→现病史，person→既往史，allergic→过敏史，family→家族史，其余同名
 */

type HealthInquiryLike = Record<string, any> | null | undefined;

const HISTORY_MAP: Array<{
  statusKey: string;
  historyKey: string;
  mrKey: string;
  /** menstrual | marital | always */
  visibility: 'always' | 'menstrual' | 'marital';
}> = [
  {
    statusKey: 'present_status',
    historyKey: 'present_history',
    mrKey: 'present_illness',
    visibility: 'always',
  },
  {
    statusKey: 'person_status',
    historyKey: 'person_history',
    mrKey: 'past_history',
    visibility: 'always',
  },
  {
    statusKey: 'allergic_status',
    historyKey: 'allergic_history',
    mrKey: 'allergy_history',
    visibility: 'always',
  },
  {
    statusKey: 'family_status',
    historyKey: 'family_history',
    mrKey: 'family_history',
    visibility: 'always',
  },
  {
    statusKey: 'epidemic_status',
    historyKey: 'epidemic_history',
    mrKey: 'epidemic_history',
    visibility: 'always',
  },
  {
    statusKey: 'personal_status',
    historyKey: 'personal_history',
    mrKey: 'personal_history',
    visibility: 'always',
  },
  {
    statusKey: 'menstrual_status',
    historyKey: 'menstrual_history',
    mrKey: 'menstrual_history',
    visibility: 'menstrual',
  },
  {
    statusKey: 'marital_status',
    historyKey: 'marital_history',
    mrKey: 'marital_history',
    visibility: 'marital',
  },
];

function isFieldVisible(
  visibility: 'always' | 'menstrual' | 'marital',
  sex: number,
  age: number,
): boolean {
  if (visibility === 'menstrual') return sex === 2;
  if (visibility === 'marital') {
    return (sex === 1 && age > 22) || (sex === 2 && age > 20);
  }
  return true;
}

/** status≠1 或内容空 →「无」；有内容用顿号拼接 */
function resolveHistoryText(status: unknown, raw: unknown): string {
  if (Number(status) !== 1) return '无';
  if (Array.isArray(raw)) {
    const parts = raw.map((v) => String(v ?? '').trim()).filter(Boolean);
    return parts.length ? parts.join('、') : '无';
  }
  const str = String(raw ?? '').trim();
  if (!str || str === '[]' || str === 'null') return '无';
  try {
    const decoded = JSON.parse(str);
    if (Array.isArray(decoded)) {
      const parts = decoded.map((v) => String(v ?? '').trim()).filter(Boolean);
      return parts.length ? parts.join('、') : '无';
    }
  } catch {
    /* 非 JSON，按分隔符拆 */
  }
  const parts = str.split(/[,，、]+/).map((s) => s.trim()).filter(Boolean);
  return parts.length ? parts.join('、') : '无';
}

/**
 * 将健康问诊转为可 patch 到病历的史字段对象
 */
export function mapHealthInquiryToMrHistory(
  health: HealthInquiryLike,
  opts?: { sex?: number; age?: number },
): Record<string, string> {
  const hi = health || {};
  const sex = Number(opts?.sex || 0);
  const age = Number(opts?.age || 0);
  const out: Record<string, string> = {};
  for (const row of HISTORY_MAP) {
    if (!isFieldVisible(row.visibility, sex, age)) continue;
    out[row.mrKey] = resolveHistoryText(hi[row.statusKey], hi[row.historyKey]);
  }
  return out;
}
