import { defineStore } from 'pinia'
import { ref } from 'vue'
import dayjs from 'dayjs'

const initState = {
  token: '', // 登录token
  userid: '', // 用户id
  openid: '', // 微信openid
}

export const useAppStore = defineStore(
  'app',
  () => {
    const appInfo = ref<IAppInfo>({ ...initState })
    const alertCompleteInfo = ref({
      hasAlert: false,
      time: '',
    })

    const setAppInfo = (val: IAppInfo) => {
      appInfo.value = val
    }

    const clearAppInfo = () => {
      appInfo.value = { ...initState }
    }

    // 一般没有reset需求，不需要的可以删除
    const reset = () => {
      appInfo.value = { ...initState }
    }

    const isLogined = computed(() => !!appInfo.value.token)

    const needAlertCompleteInDays = computed(() => {
      // 如果已经提示过，并且距离上一次提示的时间在3天以内，则不需要提示
      if (alertCompleteInfo.value && dayjs().diff(alertCompleteInfo.value.time, 'day') < 3) {
        return false
      }
      return true
    })

    const setAlertCompleteInfo = (val: { hasAlert: boolean; time: string }) => {
      alertCompleteInfo.value = val
    }

    return {
      appInfo,
      setAppInfo,
      clearAppInfo,
      isLogined,
      reset,
      alertCompleteInfo,
      setAlertCompleteInfo,
      needAlertCompleteInDays,
    }
  },
  {
    persist: true,
  },
)
