import { defineStore } from 'pinia';
import { getUserInfo, getCartList } from '@/api/user'
// defineStore 方法有两个参数，第一个参数是模块化名字（也就相当于身份证一样，不能重复）

// 第二个参数是选项，对象里面有三个属性，相比于vuex 少了一个 mutations.
export const useUserStore = defineStore('user', {
  state(){  // 存放的就是模块的变量
    return {
      token: localStorage.getItem('token') || 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMzYzMTI2MjkyNiIsImxvZ2luVHlwZSI6InVzZXIiLCJ1c2VyTmFtZSI6IjEzNjMxMjYyOTI2IiwiaWF0IjoxNzU4ODU2MzkzLCJqdGkiOiI3MmY0NWYwMC1iOTFkLTQ1ZGItYWIzZS1iOGNlNGVhNDNkMTMifQ.PG85Q044plwHvak1aRGgKXYYsH1hXhueKK1X-2Q65Lo',
      openId: localStorage.getItem('openId'),
      isLogin: false,
      carList: [],
      info: {

      },
    }
  },
  getters:{ // 相当于vue里面的计算属性，可以缓存数据
    getToken(state){
      return state.token || localStorage.getItem('token')
    },
    getOpenId(state){
      return state.openId || localStorage.getItem('openId')
    },
    getUserInfo(state){
      return state.info || localStorage.getItem('info')
    },
    getCarList(state){
      return state.carList.length || 0
    },
  },
  actions:{ // 可以通过actions 方法，改变 state 里面的值。
    setUserOpenId(value:string){
      this.openId = value
      localStorage.setItem('openId', value,)
    },
    async getInfo(){
      let infoRes = await getUserInfo()
      console.log('infoRes', infoRes)
      this.info = infoRes
      this.isLogin = true

    },
    async getCartData(){
      let infoRes = await getCartList({})
      this.carList = infoRes
      return infoRes
    }
  }
})
