export type DoctorCertImage = { label: string; url: string };

export function normalizeDoctorRecord(doc: Record<string, any>) {
  if (!doc) return doc;
  if (!doc.titleInfo && doc.title_info) {
    doc.titleInfo = doc.title_info;
  }
  if (!doc.depart && doc.department) {
    doc.depart = doc.department;
  }
  return doc;
}

export function unwrapStoreInputDetail(res: unknown): Record<string, any> | null | undefined {
  if (res == null || typeof res !== 'object') {
    return res as Record<string, any> | null | undefined;
  }
  const obj = res as Record<string, any>;
  if (obj.doctor_inputs != null || obj.doctorInputs != null || obj.id != null) {
    return obj;
  }
  const inner = obj.data ?? obj.result;
  if (inner != null && typeof inner === 'object') {
    return inner as Record<string, any>;
  }
  return obj;
}

export function getLinkedDoctors(data: Record<string, any> | null | undefined) {
  const detail = unwrapStoreInputDetail(data) ?? data;
  const list = detail?.doctor_inputs ?? detail?.doctorInputs ?? [];
  const arr = Array.isArray(list) ? list : [];
  return arr.map((d) => normalizeDoctorRecord(d));
}

export function doctorDepartName(doc: Record<string, any> | null | undefined) {
  if (!doc) return '-';
  const d = normalizeDoctorRecord(doc);
  return d.depart?.name ?? d.depart_name ?? '-';
}

export function doctorTitleName(doc: Record<string, any> | null | undefined) {
  if (!doc) return '-';
  const d = normalizeDoctorRecord(doc);
  return d.titleInfo?.name ?? d.title_info?.name ?? '-';
}

export function getDoctorTypeText(type: number) {
  if (type === 1) return '中医医生';
  if (type === 2) return '西医医生';
  return '-';
}

export function getSignTypeText(signType: number) {
  if (signType === 1) return '电子签名';
  if (signType === 2) return '手写签名';
  return '-';
}

export function getAuditStatusText(status: number) {
  if (status === 0) return '待审核';
  if (status === 1) return '审核通过';
  if (status === 2) return '审核拒绝';
  return '-';
}

export function doctorCertImages(doc: Record<string, any> | null | undefined): DoctorCertImage[] {
  if (!doc) return [];
  const items: DoctorCertImage[] = [
    { label: '头像', url: doc.avatar },
    { label: '资格证书', url: doc.qualification },
    { label: '执业证书', url: doc.practicing },
    { label: '职称证书', url: doc.title },
    { label: '身份证正面', url: doc.card_up },
    { label: '身份证反面', url: doc.card_down },
    { label: '签名', url: doc.sign_image },
  ];
  return items.filter((item) => !!item.url);
}

export function isDoctorPending(doc: Record<string, any>) {
  return Number(doc?.status) === 0;
}
