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";
import { getIntegralName } from "@/api/member";
import store from "@/store";

const {push} = useRouter()

export const useMainStore = defineStore('main', {
    state: () => ({
        user: null,
        areaList: [],
        selectAddress: null,
        moreLoading: true,
        cartId: null,
        integralName: '积分'
    }),
    getters: {},
    actions: {
        setAccessToken(user) {
            cookie.set('accessToken', user)
            return getUserInfo()
        },
        setSelectAddress(id) {
            this.selectAddress = this.address.filter(item => item.id == id)[0]
        },
        async getUserInfo() {
            let res = await getUserInfo()
            this.user = res
            return res
        },

        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"})
        },
        async doGetIntegralName() {
            this.integralName = await getIntegralName()
        }
    },
})

export const useMainStoreWithOut = () => useMainStore(store)
