import Vue from 'vue'
import Vuex from 'vuex'
import {
  setToken,
  setAccountInfo,
  setSearchHistory,
  setOrderInfo,
  setShoppingCartCheckedList,
  setWithdrawGoodsInfo,
  setAppVersion,

  getAppPlatform,
  getToken,
  getAccountInfo,
  getSearchHistory,
  getOrderInfo,
  getShoppingCartCheckedList,
  getWithdrawGoodsInfo,
  getAppVersion,

  clearToken,
  clearAccountInfo,
  clearSearchHistory,
  clearOrderInfo,
  clearShoppingCartCheckedList,
  clearWithdrawGoodsInfo,

  
} from '@/utils'
import mFetch from "@/api"

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    appPlatform: getAppPlatform(),
    appVersion: getAppVersion(),
    title: "",
    currentTab: 0,
    showNavBar: false,
    showTabBar: false,

    token: getToken(),
    accountInfo: getAccountInfo(),
    rewardRule: { evaluationRefund: 0 },

    searchHistory: getSearchHistory(),
    searchFlag: 0,

    orderInfo: getOrderInfo(),
    unCommentOrders: [],
    shoppingCart: [],
    shoppingCartCheckedList: getShoppingCartCheckedList(),

    withdrawGoodsInfo: getWithdrawGoodsInfo(),
    currentTime: +new Date(),
  },
  getters: {
    hasLogin: (state) => {
      return state.token && state.token.length > 0
    }
  },
  mutations: {
    // =====set=====
    setAppPlatform(state, val){
      state.appPlatform = val
    },
    
    setAppVersion(state, val) {
      state.appVersion = val
      setAppVersion(val)
    },

    setCurrentTab(state, val){
      state.currentTab = val
    },
    setTitle(state, val) {
      state.title = val
    },
    setShowNavBar(state, val) {
      state.showNavBar = val
    },
    setShowTabBar(state, val) {
      state.showTabBar = val
    },



    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    setAccountInfo(state, { area, phone, nickName, userId, uid, inviteCode, headUrl, sex = 2, birthday = null, isPayPassword=false }) {
      let accountInfo = { area, phone, nickName, userId, uid, inviteCode, headUrl, sex, birthday, isPayPassword }
      state.accountInfo = accountInfo
      setAccountInfo(accountInfo)
    },
    addSearchHistory(state, val) {
      if (state.searchHistory.length >= 10) {
        state.searchHistory.splice(9)
      }
      let index = state.searchHistory.findIndex(item => item == val)
      if (index >= 0) {
        state.searchHistory.splice(index, 1)
      }
      state.searchHistory.splice(0, 0, val)
      setSearchHistory(state.searchHistory)
    },
    setSearchFlag(state, val) {
      state.searchFlag = val
    },


    setOrderInfo(state, { selectAddrIndex, selectAddr, skuList, fromType, extData, type,salesType=1}) {
      let goodsMap = {}
      if (skuList && skuList.length !== 0) {
        skuList.forEach(item => {
          let { merchantId, merchantName, skuProps } = item
          let skuLabel =""
          if(salesType===4){
            skuLabel=""
          }else{
            skuLabel=skuProps.map((item) => item.propVal).join("+")
          }
           
          if (!goodsMap[merchantId]) {
            goodsMap[merchantId] = { merchantId, merchantName, skuList: [{ ...item, skuLabel }], vnote: "" }
          } else {
            goodsMap[merchantId].skuList.push({ ...item, skuLabel })
          }
        });
      }
      let orderInfo = { selectAddrIndex, selectAddr, goodsMap, fromType, extData, type,salesType }
      state.orderInfo = orderInfo
      setOrderInfo(orderInfo)
    },
    setOrderInfoAddr(state, { selectAddrIndex, selectAddr }) {
      let orderInfo = { ...state.orderInfo, selectAddrIndex, selectAddr }
      state.orderInfo = orderInfo
      setOrderInfo(orderInfo)
    },
    
		setUnCommentOrders(state, val) {
			state.unCommentOrders = val
		},
		updateUnCommentOrders(state, { index, val }) {
			if (state.unCommentOrders[index]) {
				state.unCommentOrders[index].buyerState = val
			}
		},
    
		setShoppingCart(state, val) {
			state.shoppingCart = val
		},
    setShoppingCartCheckedList(state, val){
      state.shoppingCartCheckedList = val
      setShoppingCartCheckedList(val)
    },

    setWithdrawGoodsInfo(state, val){
      state.withdrawGoodsInfo = val
      setWithdrawGoodsInfo(val)
    },

    setCurrentTime(state, val){
      state.currentTime = val
      return 1
    },


    // =====clear======
    clearAccountInfo(state) {
      state.token = null
      state.accountInfo = {}
      clearToken()
      clearAccountInfo()
    },
    clearSearchHistory(state) {
      state.searchHistory = []
      clearSearchHistory()
    },

    clearOrderInfo(state) {
      state.orderInfo = {}
      clearOrderInfo()
    },

    clearShoppingCart(state){
      state.shoppingCart = []
    },
    clearShoppingCartCheckedList(state){
      state.shoppingCartCheckedList = []
      clearShoppingCartCheckedList()
    },
    clearWithdrawGoodsInfo(state){
      state.withdrawGoodsInfo = {}
      clearWithdrawGoodsInfo()
    }
  },
  actions: {

    getShoppingCart({state, commit}) {
      mFetch({
				apiName: "getShoppingCartList",
				success: (res) => {
					let checkedList = state.shoppingCartCheckedList;
					let arr = []
					commit('setShoppingCart', res.result)
					if (res.result.length > 0) {
						for (let item of checkedList) {
							if (res.result.find(x => { return x.skuId === item })) {
								arr.push(item)
							}
						}
						checkedList = arr
						// uni.setTabBarBadge({
						// 	index: 2,
						// 	text: res.result.length + ''
						// })
					} else {
						arr = []
					}
          commit("setShoppingCartCheckedList", arr)
				},
			});
    }

  },
  modules: {
  }
})
