// 公共数据,什么都可往里面传，可用于临时传参
import Taro from '@tarojs/taro'
import {
  CLEAR_SHOPCOUNT,
  SET_SHOPCOUNT,
  STORAGE_SHOPCOUNT,
} from '../constants/common'

export interface DataParam {
  shopCount: number // 购物车数量
}

interface Action {
  type?: string
  data?: DataParam
}

const INIT = {
  shopCount: Taro.getStorageSync(STORAGE_SHOPCOUNT) ? JSON.parse(Taro.getStorageSync(STORAGE_SHOPCOUNT)).shopCount : 0,
}

export default (state = INIT, action: Action) => {
  const { type, data } = action
  switch (type) {
    case SET_SHOPCOUNT:
      Taro.setStorageSync(STORAGE_SHOPCOUNT, JSON.stringify(data?.shopCount))
      return { ...state, ...data }
    case CLEAR_SHOPCOUNT:
      Taro.removeStorageSync(STORAGE_SHOPCOUNT)
      return { ...state, shopCount: 0 }
    default:
      return state
  }
}
