// 基础服务 - 对应 supermart-mini/service/base.js
import { Platform } from "react-native";
import { get, getToken, post } from "./http";

const apis = {
  PAGE_CONFIG: "/api/app/page/getByPageId",
  MESSAGE: "/api/app/message",
  TRACK: "/api/track",
  FEEDBACK: "/api/app/feedback/submit",
  PARAM_CONFIG: "/param/paramConfig",
};

export interface BannerItem {
  id: string;
  cover: string;
  path?: { url: string };
}

export interface TabItem {
  title: string;
  cover: string;
  path?: { url: string };
}

export interface PageConfig {
  components: Array<{
    elements: any[];
  }>;
}

// 获取页面配置
export const getPageConfig = async (
  pageId: string,
): Promise<PageConfig | null> => {
  const res = await get<PageConfig>(apis.PAGE_CONFIG, { pageId });
  return res.data;
};

// 获取消息列表
export const getMessages = async (
  current: number,
  size: number,
  type?: string,
) => {
  const params: any = { current, size };
  if (type) params.type = type;
  const res = await get(apis.MESSAGE, params);
  return res.success ? res.data : null;
};

// 获取消息列表（分页）
export const getMessageList = async (
  current: number,
  size: number,
  type?: string,
) => {
  const params: any = { current, size };
  if (type) params.type = type;
  const res = await get(apis.MESSAGE, params);
  return res.success ? res.data : { records: [], total: 0 };
};

// 获取参数配置
export const getParamConfig = async (code: string) => {
  const res = await get(apis.PARAM_CONFIG, { code });
  return res.data;
};

// 提交反馈
export const submitFeedback = async (data: any) => {
  const res = await post(apis.FEEDBACK, data);
  return res.data;
};

// 追踪
export const track = async () => {
  const res = await get(apis.TRACK);
  return res.data;
};

// 上传文件
export const uploadFile = async (
  fileUri: string,
  folder = "avatar",
  externalToken?: string,
): Promise<string | { error: string }> => {
  try {
    let processedUri = decodeURI(fileUri);
    if (Platform.OS === "ios") {
      if (!processedUri.startsWith("file://") && !processedUri.startsWith("http")) {
        processedUri = `file://${processedUri}`;
      }
    }

    const fileName = processedUri.split("/").pop() || `avatar_${Date.now()}.jpg`;
    const fileExt = fileName.split(".").pop()?.toLowerCase() || "jpg";
    const mimeType = fileExt === "png" ? "image/png" : "image/jpeg";

    console.log("[uploadFile] uri:", processedUri.substring(0, 80), "name:", fileName);

    const formData = new FormData();
    formData.append("file", {
      uri: processedUri,
      type: mimeType,
      name: fileName,
    } as any);
    formData.append("appId", "supermart-acetoys");
    formData.append("folder", folder);

    const token = externalToken || getToken();
    console.log("[uploadFile] token:", token ? token.substring(0, 10) + "..." : "空!");

    const response = await fetch("https://mm.acefig.com/api/oss/file/upload", {
      method: "POST",
      headers: {
        Authentication: token || "",
      },
      body: formData,
    });

    const responseText = await response.text();
    console.log("[uploadFile] status:", response.status, "body:", responseText?.substring(0, 200));

    if (!response.ok) {
      return { error: `HTTP ${response.status}: ${responseText?.substring(0, 100)}` };
    }
    if (!responseText) {
      return { error: "服务器响应为空" };
    }

    const result = JSON.parse(responseText);
    if ((result.code === 0 || result.code === "0") && result.data?.url) {
      return result.data.url;
    }
    return { error: `code:${result.code} msg:${result.msg || JSON.stringify(result).substring(0, 80)}` };
  } catch (error: any) {
    console.error("[uploadFile] 异常:", error);
    return { error: `异常: ${error?.message || String(error).substring(0, 100)}` };
  }
};

export default {
  getPageConfig,
  getMessages,
  getMessageList,
  getParamConfig,
  submitFeedback,
  track,
  uploadFile,
};
