// https://pinia.vuejs.org/
import { createPinia,PiniaPlugin,PiniaPluginContext } from 'pinia';

import {  toRaw } from 'vue'
import {Session} from '/@/utils/storage';

// 数据存储本地
const setStorage = (key: string, value: any) => {
    Session.set(key,value)
   // sessionStorage.setItem(key, JSON.stringify(value))
}
// 获取本地数据
const getStorage = (key: string) => {
    return Session.get(key)
}

const piniaPlugin = (context: PiniaPluginContext) => {
    const { store } = context;
    // $subscribe state值发生变化时会执行传入的回调
    store.$subscribe(() => {
        // 每次修改值的时候更新localStorage数据
        setStorage(`piniaKey-${store.$id}`, toRaw(store.$state))
    })
    // 每次构建项目的时候从本地存储取值
    const data = getStorage(`piniaKey-${store.$id}`)
   // 并将取的值赋给state
    return {
        ...data
    }
}


// 创建
const pinia = createPinia();
pinia.use(piniaPlugin);

// 导出
export default pinia;
