import { computed, ref } from "vue";
import { defineStore } from "pinia";
import { getWelcomeMessage, type WelcomeMessageData } from "@/api/welcome";
import { isDeviceOnline } from "@/constants/deviceOnline";
import { SseService } from "@/utils/sse";

function formatRequestDate(date = new Date()) {
  const pad = (n: number) => String(n).padStart(2, "0");
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
}

/** 可通过 updateState 批量更新的字段 */
export interface AppStateUpdates {
  terminal?: string;
  accessToken?: string;
  familyId?: string;
  deviceType?: string;
  deviceCategory?: string;
  deviceName?: string;
  deviceId?: string;
  deviceGuid?: string;
  userId?: string;
  machineOpenStatus?: boolean | null;
  machinePowerStateReady?: boolean;
}

export const useAppStore = defineStore("app", () => {
  /** 应用展示名，可在启动时由接口或配置覆盖 */
  const appName = ref("Roki H5");
  const terminal = ref("android");
  const userId = ref("3243300064");

  const deviceName = ref("HD3-L10-18");
  const familyId = ref("");
  const deviceId = ref("HDL1088a68d65eb5f");
  const deviceGuid = ref("HDL1088a68d65eb5f");
  const deviceType = ref("HDL10");
  const deviceCategory = ref("RRSQ");

  /** 开发联调用 token，生产环境由 App 注入覆盖 */
  const accessToken = ref(
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3OTExMDgwNjQsInVzZXJJZCI6NDIzNTY3MjY5OSwianRpIjoiZDJiOWY0Y2UtMzMzMS00Y2U2LWJjZGUtZjQyZGU3YTllYzE3IiwiY2xpZW50X2lkIjoicm9raV9jbGllbnQifQ.GMcX0otpARzToxBu8GT6bN1qA3qp1AejtrTPlprfWMU",
  );

  /** `/rest/ops/ai/welcome` 的 data：prefix / speech */
  const welcomeCopy = ref<WelcomeMessageData>({});

  /** 设备是否开机（null 表示尚未从 shadow/SSE 同步） */
  const machineOpenStatus = ref<boolean | null>(null);
  /** 开关机状态是否已从 shadow/SSE 同步过 */
  const machinePowerStateReady = ref(false);
  /**
   * 设备在线状态码：info/state → data[0].status
   * 0 离线 / 1 在线；未拉取前为 null
   */
  const deviceOnlineStatusCode = ref<number | null>(null);
  /** 是否在线（未拉取前默认 true，避免首屏误显示离线） */
  const machineOnlineStatus = computed(() => {
    const status = deviceOnlineStatusCode.value;
    if (status === null || status === undefined) return true;
    return isDeviceOnline(status);
  });
  /** SSE 客户端 */
  const sseClient = ref<SseService | null>(null);

  function setAppName(name: string) {
    appName.value = name;
  }

  function setAccessToken(token: string) {
    accessToken.value = token;
  }

  function setDeviceOnlineStatus(status: number) {
    deviceOnlineStatusCode.value = status;
  }

  function initSSEClient(url: string) {
    if (sseClient.value) {
      console.log("[SSE] 已存在连接，不重复创建");
      return sseClient.value;
    }
    sseClient.value = new SseService(url);
    return sseClient.value;
  }

  function resetWelcomeCopy() {
    welcomeCopy.value = {};
  }

  async function loadWelcomeMessage(params: Record<string, unknown> = {}) {
    try {
      const res = await getWelcomeMessage({
        date: formatRequestDate(),
        ...params,
      });
      welcomeCopy.value = res?.data ?? {};
    } catch (e) {
      welcomeCopy.value = {};
      if (import.meta.env.DEV) {
        console.warn("[App] loadWelcomeMessage failed", e);
      }
    }
  }

  function updateState(updates: AppStateUpdates) {
    const stateRefs = {
      terminal,
      accessToken,
      familyId,
      deviceType,
      deviceCategory,
      deviceName,
      deviceId,
      deviceGuid,
      userId,
      machineOpenStatus,
      machinePowerStateReady,
    } as const;

    Object.entries(updates).forEach(([key, value]) => {
      if (key in stateRefs) {
        stateRefs[key as keyof typeof stateRefs].value = value as never;
      } else if (import.meta.env.DEV) {
        console.warn(`[App] updateState: unknown key "${key}"`);
      }
    });
  }

  return {
    appName,
    terminal,
    deviceName,
    familyId,
    deviceId,
    deviceGuid,
    deviceType,
    deviceCategory,
    userId,
    accessToken,
    welcomeCopy,
    machineOpenStatus,
    machinePowerStateReady,
    deviceOnlineStatusCode,
    machineOnlineStatus,
    sseClient,
    setAppName,
    setAccessToken,
    setDeviceOnlineStatus,
    initSSEClient,
    resetWelcomeCopy,
    loadWelcomeMessage,
    updateState,
  };
});
