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 isLoginState = 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
    }

    /**
     * 判断用户是否登陆：没有登录->提示登录，已经登录，返回true
     */
    const alertLogin = () => {
      if (!isLoginState.value) {
        uni.showToast({ title: '请先登录', icon: 'none' })
      }
    }

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