import { defineStore } from "pinia";
import { ref } from "vue";
import userApi from "@/api/user";
import { requestCommon } from "@/utils/request";
export default defineStore("useUserState", () => {



	const userData = ref(requestCommon.getUserData() || {});
	const myDoctor = ref(uni.getStorageSync("MYDOCTOR") || {})


	/**
	 * 用户登录
	 * @param data 
	 * @returns 
	 */
	const userLogin =  (data:object) => {
		return new Promise((resolve,reject)=>{
			userApi.login(data).then(({data})=>{
			
				
				requestCommon.setToken(data.token)
				saveUserInfo(data)
				resolve(true)
			}).catch((error)=>{
				reject(false)
			})
			
		})
		
	};
	const saveUserInfo = (data:object) => {
		return new Promise((resolve,reject)=>{
			// userApi.userInfo().then(({data})=>{
				requestCommon.setUserData(data)
				userData.value = requestCommon.getUserData()
				resolve(true)
			// }).catch((error)=>{
				// reject(false)
			// })
			
		})
	
	
	}
	const getUserData = async () => {
		userData.value = requestCommon.getUserData()
		return Promise.resolve(userData.value)
	};
	const userLogout =  () => {
		requestCommon.removeAll()
		// return
		return userApi.logout();
		
	};
	return { userData, myDoctor,userLogin, getUserData, userLogout,saveUserInfo };
});
