import { GET, POST } from "@/utils/http";
import { useUuidStore } from "@/stores/modules/uuid";
import pinia from "@/stores/index";

// 定义埋点参数的类型
interface LogParams {
  type?: number;
  channel?: string;
  uuid?: string;
  page?: string;
  page_url?: string;
  describe?: any;
  time?: number;
  [key: string]: any;
}

// 定义UUID响应的类型
interface UuidResponse {
  code: number;
  data: {
    uuid: string;
  };
  message: string;
}

// 获取UUID store实例
const getUuidStore = () => {
  return useUuidStore(pinia);
};

// 公共参数
const getPubParams = () => {
  const uuidStore = getUuidStore();
  return {
    channel: 'aigc-camera',
    uuid: uuidStore.getUuid || ''
  };
};

/**
 * 获取UUID
 */
export async function getUUid(): Promise<UuidResponse> {
  return GET('/api/uuid', {}, {
    loading: false,
    showErrorMessage: false
  });
}

/**
 * 设置UUID（用于与store集成）
 * @param uuid UUID字符串
 */
export function setUuid(uuid: string): void {
  const uuidStore = getUuidStore();
  uuidStore.setUuid(uuid);
}

/**
 * 获取当前UUID
 * @returns 当前UUID或null
 */
export function getCurrentUuid(): string | null {
  const uuidStore = getUuidStore();
  return uuidStore.getUuid;
}

/**
 * 埋点接口
 * @param params 埋点参数
 */
export async function setLog(params: LogParams): Promise<void> {
  const uuidStore = getUuidStore();
  
  // 埋点函数
  const setLogFun = async (logParams: LogParams) => {
    const pubParams = getPubParams();
    const requestData = {
      type: 1,
      ...pubParams,
      uuid: uuidStore.getUuid || '',
      ...logParams
    };
    
    try {
      await POST('/api/record/point', requestData, {
        loading: false,
        showErrorMessage: false
      });
    } catch (error) {
      console.error('埋点请求失败:', error);
    }
  };

  // 检查UUID是否存在
  if (uuidStore.hasUuid) {
    await setLogFun(params);
  } else {
    // UUID不存在，先获取UUID
    try {
      const res = await getUUid();
      if (res.code === 0 && res.data?.uuid) {
        uuidStore.setUuid(res.data.uuid);
        await setLogFun(params);
      } else {
        console.error('获取UUID失败:', res.message);
      }
    } catch (error) {
      console.error('获取UUID异常:', error);
    }
  }
}
