import { defineStore } from 'pinia'
import { ref } from 'vue'
import ls from 'store2'
import crypt from '../composables/crypt'
import { userToken } from '../composables/config'

export interface UserInfo {
  id?: string
  name: string
  email: string
  phone: string
}
export interface AccountInfo {
  loginName: string
  password: string
  rememberPassword: boolean
}
const STORAGE_KEY = 'user'
const CARD_KEY = 'cardList'
const ACCOUNT_INFO_KEY = 'accountInfo'
const useUserStore = defineStore('userStore', () => {
  const userInfo = ref<UserInfo | null>(null)
  const accountInfo = ref<AccountInfo | null>(null)
  const isLoggedIn = ref(false)
  const userCard = ref([])
  const initUserInfo = () => {
    const encryptedInfo = ls.get(STORAGE_KEY)
    if (encryptedInfo) {
      const decryptedInfo = crypt.decrypt(encryptedInfo)
      if (decryptedInfo) {
        userInfo.value = JSON.parse(decryptedInfo)
        isLoggedIn.value = true
      }
    }
  }
  const initAccountInfo = () => {
    const encryptedInfo = ls.get(ACCOUNT_INFO_KEY)
    if (encryptedInfo) {
      const decryptedInfo = crypt.decrypt(encryptedInfo)
      if (decryptedInfo) {
        accountInfo.value = JSON.parse(decryptedInfo)
      }
    }
  }
  const initUserCard = () => {
    const encryptedCard = ls.get(CARD_KEY)
    if (encryptedCard) {
      const decryptedCard = crypt.decrypt(encryptedCard)
      if (decryptedCard) {
        userCard.value = JSON.parse(decryptedCard)
      }
    }
  }
  const saveUserInfo = (info: UserInfo) => {
    userInfo.value = info
    isLoggedIn.value = true
    const encryptedInfo = crypt.encrypt(JSON.stringify(info))
    ls.set(STORAGE_KEY, encryptedInfo)
  }
  const saveAccountInfo = (info: AccountInfo) => {
    accountInfo.value = info
    const encryptedInfo = crypt.encrypt(JSON.stringify(info))
    ls.set(ACCOUNT_INFO_KEY, encryptedInfo)
  }
  const saveUserCard = (info: any) => {
    userCard.value = info
    const decryptedCard = crypt.encrypt(JSON.stringify(info))
    ls.set(CARD_KEY, decryptedCard)
  }
  const clearUserInfo = () => {
    userInfo.value = null
    isLoggedIn.value = false
    userToken.value = ''
    userCard.value = []
    ls.remove(STORAGE_KEY)
  }
  initUserCard()
  initUserInfo()
  initAccountInfo()
  return {
    userInfo,
    accountInfo,
    isLoggedIn,
    userCard,
    saveUserInfo,
    saveAccountInfo,
    saveUserCard,
    clearUserInfo,
  }
})

export default useUserStore
