class ImageStore {
    constructor(dbName = 'imageDatabase', storeName = 'images') {
        this.dbName = dbName;
        this.storeName = storeName;
        this.db = null;
    }

    // 初始化IndexedDB数据库
    async initDB() {
        return new Promise((resolve, reject) => {
            const request = window.indexedDB.open(this.dbName, 1);

            request.onupgradeneeded = (event) => {
                const db = event.target.result;
                if (!db.objectStoreNames.contains(this.storeName)) {
                    db.createObjectStore(this.storeName, { keyPath: 'url' });
                }
            };

            request.onsuccess = (event) => {
                this.db = event.target.result;
                resolve(this.db);
            };

            request.onerror = (event) => {
                console.error("Error opening IndexedDB:", event);
                reject(event);
            };
        });
    }

    // 存储Base64图片
    async storeImage(url, base64Data) {
        return new Promise(async (resolve, reject) => {
            if (!this.db) {
                await this.initDB();
            }

            const transaction = this.db.transaction([this.storeName], 'readwrite');
            const store = transaction.objectStore(this.storeName);

            const request = store.put({ url, base64Data });

            request.onsuccess = () => {
                resolve(true);
            };

            request.onerror = (event) => {
                console.error("Error storing image:", event);
                reject(event);
            };
        });
    }

    // 根据URL获取Base64图片
    async getImage(url) {
        return new Promise(async (resolve, reject) => {
            if (!this.db) {
                await this.initDB();
            }

            const transaction = this.db.transaction([this.storeName], 'readonly');
            const store = transaction.objectStore(this.storeName);

            const request = store.get(url);

            request.onsuccess = (event) => {
                const result = event.target.result;
                if (result) {
                    resolve(result.base64Data);
                } else {
                    resolve(null);  // 如果没有找到图片，返回null
                }
            };

            request.onerror = (event) => {
                console.error("Error retrieving image:", event);
                reject(event);
            };
        });
    }
}
