import { defineStore } from "pinia";
import piniaPersistConfig from "@/config/piniaPersist";
import { generateUUID } from "@/utils";

type ClipboardItem<T = any> = {
  key?: string;
  id: string;
  data: T;
  timestamp?: number;
};

export const useClipboardStore = defineStore("clipboard", {
  state: () => ({
    // 支持多类型数据存储
    items: [] as ClipboardItem[],
    // 当前激活的剪贴板类型
    activeType: "",
    // 最大历史记录数
    maxHistory: 10
  }),
  actions: {
    // 泛型方法支持任意数据类型
    copy<T>(
      data: T,
      options: {
        key?: string;
        id?: string;
      } = {}
    ) {
      const { key = "default", id = generateUUID() } = options;

      // 自动清理旧记录
      if (this.items.length >= this.maxHistory) {
        this.items.shift();
      }

      this.items.push({
        id,
        data,
        timestamp: Date.now(),
        key: key
      });
      this.activeType = key;
    },

    // 按类型获取数据
    getByType<T>(key: string): ClipboardItem<T>[] {
      return this.items.filter(item => item.key === key);
    },

    // 获取最新数据
    getLatest<T>(key?: string): T | null {
      const items = key ? this.getByType(key) : [...this.items];
      return items.length ? items[items.length - 1].data : null;
    },

    // 清空指定类型数据
    clear(key?: string) {
      if (key) {
        this.items = this.items.filter(item => item.key !== key);
      } else {
        this.items = [];
      }
    }
  },
  persist: piniaPersistConfig("global_clipboard", false)
});
