import { defineStore } from 'pinia'
import cookie from '@/utils/cookie'
import { navigateTo } from '@/utils/router'

export const useMainStore = defineStore('main', {
  state: () => ({
    store: {},
    cart: [],
    orderType: 'takein',
    address: {},
    addresses: {},
    member: {},
    openid: "",
    token: "",
    lang: 'zh-cn',
    cookieKey: 'YSESSID=yshop-e4dk4o2utr3c0n95tp42p745ai',
    location: {},
    mycoupon: {}
  }),
  getters: {
    isLogin(state) {
      return Object.keys(state.member).length > 0
    }
  },
  actions: {
    DEL_COUPON() {
      this.mycoupon = {}
    },
    SET_COUPON(coupon) {
      this.mycoupon = coupon
    },
    SET_ORDER_TYPE(type) {
      this.orderType = type
    },
    SET_MEMBER(member) {
      this.member = member
      cookie.set('userinfo', member)
    },
    SET_ADDRESS(address) {
      this.address = address
    },
    SET_ADDRESSES(addresses) {
      this.addresses = addresses
    },
    SET_STORE(store) {
      this.store = store
    },
    SET_CART(cart) {
      this.cart = cart
    },
    REMOVE_CART() {
      this.cart = []
    },
    setCookie(provider) {
      uni.setStorage({
        key: 'cookieKey',
        data: provider
      });
    },
    SET_LOCATION(location) {
      this.location = location;
    },
    SET_OPENID(openid) {
      this.openid = openid;
    },
    SET_TOKEN(token) {
      this.token = token;
      cookie.set('accessToken', token)
    },
    setAccessToken(user) {
      cookie.set('accessToken', user)
    },
    setSelectAddress(id) {
      console.log('--> % setSelectAddress % id:\n', id)
      this.selectAddress = this.address.filter(item => item.id == id)[0]
    },
    init() {
      let accessToken = cookie.get('accessToken')
      if (accessToken) {
        // 这里可以添加获取用户信息等逻辑
      }
      return null
    },
    logout() {
      this.member = {}
      this.address = {}
      this.addresses = {}
      navigateTo('/pages/login/login')
    },
  },
  persist: {
    enabled: true,
    strategies: [
      {
        storage: {
          setItem(key, value) {
            uni.setStorageSync(key, value)
          },
          getItem(key) {
            return uni.getStorageSync(key)
          },
        },
        paths: ['member', 'token'] // 需要持久化的字段
      }
    ]
  }
})