import { defineStore } from 'pinia'

interface CacheItem {
	value : any
	expire : number // 过期时间戳
}

export const useCacheStore = defineStore('cache', {
	state: () => ({
		cache: {} as Record<string, CacheItem>
	}),
	actions: {
		set(key : string, value : any, ttl ?: number) {
			const expire = typeof ttl === 'undefined'
				? Number.MAX_SAFE_INTEGER
				: Date.now() + ttl * 1000;
			this.cache[key] = { value, expire }
			// 同步到本地存储
			uni.setStorageSync(key, JSON.stringify({ value, expire }))
		},
		get<T = any>(key : string) : T | null {
			// 优先内存中读取
			if (this.cache[key] && this.cache[key].expire > Date.now()) {
				return this.cache[key].value
			}
			// 本地存储读取
			const data = uni.getStorageSync(key)
			if (data) {
				try {
					const parsed : CacheItem = JSON.parse(data)
					if (parsed.expire > Date.now()) {
						this.cache[key] = parsed
						return parsed.value
					}
					this.remove(key)
				} catch (e) {
					console.error('缓存解析失败', e)
				}
			}
			return null
		},
		remove(key : string) {
			delete this.cache[key]
			uni.removeStorageSync(key)
		},
		clear() {
			this.cache = {}
			uni.clearStorageSync()
		}
	}
})