import { defineStore } from 'pinia'

import cookie from '@/utils/cookie'
import { getUserInfo } from '@/api/user'
import { getAddressCityList, getAddressList } from '@/api/address'
import { useRouter } from "@/hooks/useRouter";

const {push} = useRouter()

export const useMainStore = defineStore('main', {
    state: () => ({
        user: null,
        address: [],
        areaList: [],
        selectAddress: null,
        moreLoading: true,
        cartId: null
    }),
    getters: {
        defaultAddress(state) {
            return state.address?.filter(item => item.isDefault)?.[0]
        },
    },
    actions: {
        setAccessToken(user) {
            cookie.set('accessToken', user)
            return getUserInfo()
        },
        setSelectAddress(id) {
            this.selectAddress = this.address.filter(item => item.id == id)[0]
        },
        async getUserInfo(user) {
            let res = await getUserInfo()
            this.user = res
            return res
        },
        restAddress() {
            this.address = []
            this.moreLoading = true
        },
        clearSelectAddress(){
            this.selectAddress = null
        },
        async getAddressList(page) {
            let res = await getAddressList({page: page})
            if (res.length) {
                this.address = this.address.concat(res)
            } else {
                this.moreLoading = false
            }
            // console.log('--> % getUserInfo % res:\n', res)
        },
        async getAddressCityList() {
            this.areaList = await getAddressCityList()
        },
        init() {
            let accessToken = cookie.get('accessToken')
            if (accessToken) {
                return getUserInfo()
            }
            return null
        },
        logout() {
            this.user = null
            this.address = []
            this.areaList = []
            this.selectAddress = null
            cookie.remove('accessToken')
            push({url: '/pages/login/guid'}, {type: "redirectTo"})
        },
    },
})
