import { defineStore } from 'pinia'

import cookie from '@/utils/cookie'
import { getUserInfo } from '@/api/user'
import { getAddressDel, getAddressDefault, getAddressAddAndEdit, getAddressList, getAddressCityList } from '@/api/address'
import { navigateTo } from '@/utils/router'

export const useMainStore = defineStore('main', {
  state: () => ({
    user: null,
    address: [],
    areaList: [],
    selectAddress: null,
  }),
  getters: {
    defaultAddress(state) {
      return state.address?.filter(item => item.isDefault)?.[0]
    },
  },
  actions: {
    setAccessToken(user) {
      cookie.set('accessToken', user)
      return getUserInfo()
    },
    setSelectAddress(id) {
      console.log('--> % setSelectAddress % id:\n', id)
      this.selectAddress = this.address.filter(item => item.id == id)[0]
    },
    async getUserInfo(user) {
      let res = await getUserInfo()
      this.user = res
      return res
    },
    async getAddressList(user) {
      let res = await getAddressList()
      this.selectAddress = res.filter(item => item.isDefault)[0]
      this.address = res
      // console.log('--> % getUserInfo % res:\n', res)
    },
    async getAddressCityList() {
      let res = await getAddressCityList()
      this.areaList = res
      // console.log("--> % getAddressCityList % this:\n", this)
      // console.log('--> % getAddressCityList % res:\n', res)
    },
    init() {
      let accessToken = cookie.get('accessToken')
      if (accessToken) {
        return getUserInfo()
      }
      return null
    },
    logout() {
      this.user = null
      this.address = []
      this.areaList = []
      this.selectAddress = null
      navigateTo('/pages/login/login')
    },
  },
})
