import { City, ExtraUserInfo } from '@/types/app-type'
import { defineStore } from 'pinia'
import { ref } from 'vue'

const initState = {
  nickname: '',
  avatar: '',
  city: {
    allscore: 0,
    code: '0',
    isopen: 0,
    lizations: [],
    policy: 0,
    provincename: '',
    years: 0,
  },
  estimatedAchievement: {
    year: 0, // 学期
    score: '', // 成绩
    requireSubject: { code: 0, name: '', simplename: '' },
    optionalSubject: [],
    cityCode: '',
  },
  userFilterParams: {
    phase: 0,
  },
}

export const useUserStore = defineStore(
  'user',
  () => {
    const userInfo = ref<ExtraUserInfo>({ ...initState })

    // 设置用户信息
    const setUserInfo = (val: ExtraUserInfo) => {
      userInfo.value = val
    }

    // 设置用户所在城市
    const setUserCity = (val: City) => {
      userInfo.value.city = val
    }

    // 设置预估成绩
    const setEstimatedAchievement = (val: any) => {
      userInfo.value.estimatedAchievement = val
    }

    // 清除预估成绩
    const clearUserEstimatedAchievement = () => {
      userInfo.value.estimatedAchievement = { ...initState.estimatedAchievement }
    }

    // 清除用户信息
    const clearUserInfo = () => {
      userInfo.value = { ...initState }
    }
    // 一般没有reset需求，不需要的可以删除
    const reset = () => {
      userInfo.value = { ...initState }
    }
    const isLogined = computed(() => !!userInfo.value.token)

    return {
      userInfo,
      setUserInfo,
      clearUserInfo,
      isLogined,
      reset,
      setUserCity,
      setEstimatedAchievement,
      clearUserEstimatedAchievement,
    }
  },
  {
    persist: true,
  },
)
