// BaseStore.js - 基础Store类
import IndexedDBHelper from '@/common/IndexedDBHelper.js'
import UniStorageHelper from '../common/UniStorageHelper'
import config from '@/config'


class BaseStore {
    db = null
    isDBReady = false
    dbName = 'BrowsingHistory'
    constructor() {
        this.checkAndInitDB()
    }
    checkAndInitDB() {
        // 获取本地数据库版本
        if (config.OnlyUseCachedDB) {
            return this.initDB()
        }
        const localVersion = uni.getStorageSync('indexedDBVersion') || 1
        console.log('DBVersion: ', localVersion, config.DBversion)
        if (localVersion === config.DBversion) {
            this.initDB()
        } else {
            console.log('清空本地数据库')
            this.clearDB().then(() => {
                uni.setStorageSync('indexedDBVersion', config.DBversion);
                this.initDB();
            });
        }
    }
    initDB() {
        // // #ifdef H5
        this.db = new IndexedDBHelper(this.dbName, config.DBversion);
        // // #endif
        // // #ifndef H5
        this.db = new UniStorageHelper(this.dbName, config.DBversion);
        // // #endif
        this.db.openDB([{
            name: 'record',
            keyPath: "id",
            autoIncrement: true,
        }, {
            name: 'messageGroup',
            keyPath: "id",
            autoIncrement: true,
        }, {
            name: 'messages',
            keyPath: "id",
            autoIncrement: true,
            indexes: [{
                name: 'parentGroupId',
                key: 'parentGroupId',
                unique: false
            }]
        }]).then(async () => {
            const { default: useChatGroupDBStore } = await import('@/packageA/stores/userChatGroupStore.js')
            useChatGroupDBStore().init()
            this.isDBReady = true
        });
    }
    async clearDB() {
        return new Promise((resolve, rejetc) => {
            new IndexedDBHelper().deleteDB(this.dbName).then(() => {
                resolve()
            })
        })
    }

}

const baseDB = new BaseStore()

export default baseDB