import axios, { AxiosInstance } from "axios";

// API配置
const API_CONFIG = {
  // 内网URL
  INTERNAL_URL:
    "http://10.1.5.118:8077/platform-api/api/his-web/self-service-machine/",
  // 外网URL
  EXTERNAL_URL:
    "http://apihis.circleharmonyhospital.cn:8982/platform-api/api/his-web/self-service-machine/",
};

// 响应数据类型
export interface ApiResponse<T = any> {
  Status: number;
  Message: string | null;
  Data: T;
  CopyRight: string;
}

// 患者基本信息
export interface PatientInfo {
  name: string;
  gender: number;
  gender_name: string;
  age: string;
  IdCard: string;
  phone: string;
  marital: number;
  marital_name: string;
  is_valid_exam: number;
  is_update_patient_info: number; // 是否需要更新客户信息(1-需要 0-不需要)
}

// VIP认证结果
export interface VipResult {
  is_vip: number; // 0-否 1-是
}

// 可选项目列表 - 套餐信息
export interface PackageInfo {
  physical_exam_id: number;
  is_optional_package: number;
  is_optional_package_name: string;
  package_code: number;
  package_name: string;
  registration_time: string;
}

// 可选项目
export interface OptionalItem {
  combination_name: string;
  combination_code: number;
  physical_exam_id: number;
  package_code: number;
}

// 可选项目列表响应
export interface OptionalItemListResponse {
  packageInfo: PackageInfo;
  listOptionalItem: OptionalItem[];
}

// 已预约套餐信息
export interface PackagItemInfo {
  patient_name: string;
  is_upgrade_package: number; // 0-否 1-是
  appointment_datetime: string;
  package_code: string;
  package_name: string;
  registration_time: string;
  physical_exam_id: number;
}

// 套餐详情
export interface PackDetail {
  department_id: number;
  department_name: string;
  project_id: string;
  project_name: string;
}

// 已预约套餐详情响应
export interface PackagItemDetailResponse {
  packagItemInfo: PackagItemInfo;
  listPackDetail: PackDetail[];
}

// PDF响应
export interface PdfItem {
  pdf_name?: string | null;
  pdf_url?: string | null;
  combination_code?: number | null;
}

export interface PdfResponse {
  list_pdf_url: Array<string | PdfItem>;
  message: string | null;
}

export interface SignPdfResponse {
  pdf_url: string;
  message: string | null;
}

export interface DaojiandanPdfResponse {
  exam_id: number;
  pdf_url: string;
  message: string | null;
}

// 解析后的PDF响应（接口8返回的pdf_url可能是JSON字符串）
export interface ParsedPdfResponse {
  pdfUrl: string;
  message: string;
}

// 签到确认响应
export interface SignInResponse {
  is_success: number; // 0-成功 1-失败
}

// 创建axios实例
function createAxiosInstance(baseURL: string): AxiosInstance {
  const instance = axios.create({
    baseURL,
    timeout: 30000, // 30秒超时
    headers: {
      "Content-Type": "application/json; charset=UTF-8",
    },
  });

  // 请求拦截器
  instance.interceptors.request.use(
    (config) => {
      return config;
    },
    (error) => {
      return Promise.reject(error);
    }
  );

  // 响应拦截器
  instance.interceptors.response.use(
    (response) => {
      return response;
    },
    (error) => {
      return Promise.reject(error);
    }
  );

  return instance;
}

// 默认使用外网URL
// let currentBaseURL = API_CONFIG.EXTERNAL_URL;
let currentBaseURL = API_CONFIG.INTERNAL_URL;
let axiosInstance = createAxiosInstance(currentBaseURL);

/**
 * 1. 通过身份证号查询基本信息
 */
export async function getPatientInfo(
  id_no: string
): Promise<ApiResponse<PatientInfo>> {
  const response = await axiosInstance.post<ApiResponse<PatientInfo>>(
    "patient-info",
    {
      id_no,
    }
  );
  return response.data;
}

/**
 * 2. 通过身份证号更新客户信息
 */
export async function updatePatientInfo(
  id_no: string,
  marital_status: number,
  address: string,
  id_no_pic: File | Blob,
  id_valid_date: string
): Promise<ApiResponse<null>> {
  const formData = new FormData();
  formData.append("id_no", id_no);
  formData.append("id_no_pic", id_no_pic || "");
  formData.append("marital_status", marital_status.toString());
  formData.append("address", address || "");
  const response = await axiosInstance.post<ApiResponse<null>>(
    "patient-edit",
    formData,
    {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    }
  );
  return response.data;
}

/**
 * 3. 获取VIP客户认证结果
 */
export async function getVipStatus(
  id_no: string
): Promise<ApiResponse<VipResult>> {
  const response = await axiosInstance.post<ApiResponse<VipResult>>(
    "is-taiping-vip",
    {
      id_no,
    }
  );
  return response.data;
}

/**
 * 3. 通过身份证号获取体检选项项目列表
 */
export async function getOptionalItemList(
  id_no: string
): Promise<ApiResponse<OptionalItemListResponse>> {
  const response = await axiosInstance.post<
    ApiResponse<OptionalItemListResponse>
  >("optional-item-list", {
    id_no,
  });
  return response.data;
}

/**
 * 4. 查询已预约的体检套餐详情
 * 注意：此接口与接口3使用相同的路径，但返回数据不同
 * 如果后端需要区分，可能需要额外的参数或不同的路径
 */
export async function getPackagItemDetail(
  id_no: string
): Promise<ApiResponse<PackagItemDetailResponse>> {
  const response = await axiosInstance.post<
    ApiResponse<PackagItemDetailResponse>
  >("package-item-list", {
    id_no,
  });
  return response.data;
}

/**
 * 5. 获取体检知情同意书PDFurlList
 */
export async function getTongyishuPdf(
  exam_id: number
): Promise<ApiResponse<PdfResponse>> {
  const response = await axiosInstance.post<ApiResponse<PdfResponse>>(
    "tongyishu-get",
    {
      exam_id,
    }
  );
  return response.data;
}

/**
 * 5.5. 拿取体检知情同意书PDF
 */
export async function getTongyishuPdfFile(
  pdf_url: string
): Promise<ApiResponse<PdfResponse>> {
  const response = await axiosInstance.get<ApiResponse<PdfResponse>>(pdf_url);
  return response.data;
}
/**
 * 6. 体检知情同意书签名，返回生成的知情同意书PDF
 * @param exam_id 体检ID
 * @param sign_file 签名图片文件（File对象或Blob）
 */
export async function submitTongyishuSign(
  exam_id: number,
  combination_code: number,
  sign_file: File | Blob
): Promise<ApiResponse<PdfResponse>> {
  const formData = new FormData();
  formData.append("exam_id", exam_id.toString());
  formData.append("combination_code", combination_code.toString());
  formData.append("sign_file", sign_file);

  const response = await axiosInstance.post<ApiResponse<PdfResponse>>(
    "tongyishu-sign-submit",
    formData,
    {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    }
  );
  return response.data;
}

/**
 * 7. 获取体检导检单PDF
 */
export async function getDaojiandanPdf(
  exam_id: number
): Promise<ApiResponse<DaojiandanPdfResponse>> {
  const response = await axiosInstance.post<ApiResponse<DaojiandanPdfResponse>>(
    "daojiandan-get",
    {
      exam_id,
    }
  );
  return response.data;
}

/**
 * 8. 提交体检导检单签名，返回生成的导检单PDF
 * @param exam_id 体检ID
 * @param sign_file 签名图片文件（File对象或Blob）
 * @returns 注意：返回的Data.pdf_url可能是JSON字符串，需要解析
 */
export async function submitDaojiandanSign(
  exam_id: number,
  sign_file: File | Blob
): Promise<ApiResponse<SignPdfResponse>> {
  const formData = new FormData();
  formData.append("exam_id", exam_id.toString());
  formData.append("sign_file", sign_file);

  const response = await axiosInstance.post<ApiResponse<SignPdfResponse>>(
    "daojiandan-sign-submit",
    formData,
    {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    }
  );
  return response.data;
}

/**
 * 解析接口8返回的pdf_url JSON字符串
 * @param pdfUrlJsonString JSON字符串
 * @returns 解析后的PDF响应对象
 */
export function parsePdfUrlResponse(
  pdfUrlJsonString: string
): ParsedPdfResponse {
  try {
    return JSON.parse(pdfUrlJsonString);
  } catch (error) {
    // 如果不是JSON字符串，直接返回
    return {
      pdfUrl: pdfUrlJsonString,
      message: "",
    };
  }
}

/**
 * 9. 体检客户签到确认
 * @param physical_exam_id 体检ID
 * @param package_code 套餐代码
 */
export async function signIn(
  physical_exam_id: number
): Promise<ApiResponse<SignInResponse>> {
  const response = await axiosInstance.post<ApiResponse<SignInResponse>>(
    "sign-in",
    {
      physical_exam_id,
    }
  );
  return response.data;
}

// 导出axios实例，以便需要时进行自定义配置
export { axiosInstance };
