import {defineStore} from 'pinia';
import {reactive} from 'vue';
import { user_data } from '../data/data';
import { config } from '../config/config';
import { util } from '../framework/util';
import { http } from '../framework/http';
export const UserData = defineStore('user-data',()=>{
	let data:user_data = reactive(new user_data())
	function getData():user_data {
		if(!data.token) {
			let string = util.getStorage(config.storage_key.USER_DATA)
			if(string) {
				// data = JSON.parse(string)  响应式对象无法被改变
				Object.assign(data,JSON.parse(string))  // 使用此方法赋值给相应对象
			}
		}
		return data
	}
	async function updateUserData(d:user_data){
		data = Object.assign(data,d)
		util.setStorage(config.storage_key.USER_DATA, JSON.stringify(data))
	}
	function getUserToken(){
		if(data==null){
			return ""
		}
		return data.token
	}
	async function update_user_info(cb:Function){
		http.DynamicRequest(config.url_confg.Dynamic.user_info,{},(err,d)=>{
			if(d.code===config.url_confg.StatesCode.SUCCESS){
				updateUserData(d.content)
				cb()
			}
		})
	}
	return {data,getData,updateUserData,getUserToken,update_user_info}
})