import * as types from "./type";
import Vue from "vue";
import { saTrackEvent } from "@/utils/sa";
import { getCartCount } from "@/api/home.api";
import { query, goodSelected, goodAdd, goodFee } from "@/api/shopCart.api";
const ADD_TYPES = {
  ADD_CART: 1,
  ADD_NUM: 2,
  REDUCE_NUM: 3,
  DEL_GOOD: 4,
  EDIT_NUM: 5
};
const shopCart = {
  namespaced: true,
  state: {
    manageCartState: false,
    cartList: [],
    calcFeeInfo: {},
    activityInfo: [],
    cartCount: 0
  },
  mutations: {
    [types.OPEN_MANAGE_CART_STATE](state) {
      state.manageCartState = true;
    },
    [types.CLOSE_MANAGE_CART_STATE](state) {
      state.manageCartState = false;
    },
    [types.SAVE_CART_LIST](state, data) {
      Vue.set(state, "cartList", data);
    },
    [types.SELECT_CART_GOOD](state, { index = null, goodInfo = {}, isAll = false, cartList = [] }) {
      if (isAll) {
        // 全选
        Vue.set(state, "cartList", cartList);
      } else {
        Vue.set(state.cartList, index, goodInfo);
      }
    },
    [types.DEL_CART_GOOD](state, { goodsInfo }) {
      const cart = state.cartList;
      goodsInfo.map(good => {
        for (let i = 0; i < cart.length; i++) {
          if (cart[i].skuId === good.skuId) {
            cart.splice(i, 1);
            break;
          }
        }
      });
      Vue.set(state, "cartList", cart);
    },
    [types.SAVE_CART_CALC_FEE_INFO](state, calcFeeInfo) {
      for (const key in calcFeeInfo) {
        calcFeeInfo[key] = +calcFeeInfo[key];
      }
      Vue.set(state, "calcFeeInfo", calcFeeInfo);
    },
    [types.SAVE_ACTIVITY_INFO](state, activityInfo) {
      Vue.set(state, "activityInfo", activityInfo);
    },
    [types.SAVE_CART_COUNT](state, count) {
      const goodCount = count > 99 ? "99+" : count ? count : "";
      const params = {
        index: 1,
        text: `${goodCount}`
      };
      goodCount ? uni.setTabBarBadge(params) : uni.removeTabBarBadge({ index: 1 });
      Vue.set(state, "cartCount", count);
    }
  },
  actions: {
    open_manage_cart_state({ commit }) {
      commit(types.OPEN_MANAGE_CART_STATE);
    },
    close_manage_cart_state({ commit }) {
      commit(types.CLOSE_MANAGE_CART_STATE);
    },
    async query_cart_list({ commit, dispatch }, params) {
      const [data] = await query(params);
      let goods = [];
      data?.shopSkuList?.map(sku => {
        goods = [...goods, ...sku.skuList];
      });
      if (data) {
        commit(types.SAVE_CART_LIST, goods);
        commit(types.SAVE_CART_CALC_FEE_INFO, data?.calcFeeInfo ?? {});
        dispatch("good_fee");
      }
    },
    async select_cart_good({ commit, dispatch }, params) {
      const [, error] = await dispatch("good_selected", params?.goodInfo);
      if (!error) {
        commit(types.SELECT_CART_GOOD, params);
        dispatch("good_fee");
      }
    },
    async select_all_cart_good({ commit, state, dispatch }, isSelectActive) {
      const cartList = state.cartList.map(item => {
        item.selected = isSelectActive;
        return item;
      });
      const [, error] = await dispatch("good_selected", isSelectActive);
      if (!error) {
        commit(types.SELECT_CART_GOOD, { isAll: true, cartList });
        dispatch("good_fee");
      }
    },
    async del_cart_good({ commit, dispatch }, goodsInfo) {
      // 删除全部和删除部分的
      const {
        "shopCart/selectedList": selectedList,
        "shopCart/isSelectedAll": isSelectedAll
      } = this.getters;
      const params = {
        type: "DEL_GOOD",
        isSelectedAll,
        goodsInfo: goodsInfo || selectedList
      };
      const [, error] = await dispatch("good_add", params);
      dispatch("delGoodSaEvent", params);
      uni.showToast({ title: "删除成功！", icon: "none" });
      if (!goodsInfo) {
        dispatch("close_manage_cart_state");
      }
      if (!error) {
        commit(types.DEL_CART_GOOD, params);
        dispatch("good_fee");
      }
    },
    async change_cart_good_num({ commit, dispatch }, params) {
      const [data, error] = await dispatch("good_add", params);
      if (!error) {
        commit(types.SELECT_CART_GOOD, params);
        dispatch("good_fee");
      }
      return data;
    },
    good_selected({ state }, params) {
      let skuList = [];
      let selected = null;
      if (typeof params === "boolean") {
        skuList = state?.cartList?.map(item => ({
          skuNo: item.skuId,
          skuNum: item.count,
          skuSource: item.skuSource
        }));
        selected = params;
      } else {
        selected = params.selected;
        skuList.push({ skuNo: params.skuId, skuSource: params.skuSource, skuNum: params.count });
      }
      return goodSelected({
        skuList,
        selected
      });
    },
    good_add(_, params) {
      let shopCartBaseList = [];
      let selected = null;
      if (params.type === "DEL_GOOD") {
        selected = false;
        shopCartBaseList = params.goodsInfo.map(item => ({
          skuId: item.skuId,
          skuNum: item.count,
          skuSource: item.skuSource,
          type: ADD_TYPES[params.type]
        }));
      } else {
        const goodInfo = params.goodInfo || {};
        selected = goodInfo?.selected;
        if (+goodInfo.skuNum) {
          shopCartBaseList.push({
            type: ADD_TYPES[params.type],
            skuId: goodInfo.skuId,
            skuNum: goodInfo.skuNum,
            skuSource: goodInfo.skuSource
          });
        }
      }
      if (shopCartBaseList.length) {
        return goodAdd({
          selected,
          shopCartBaseList
        });
      }
    },
    async good_fee({ commit, dispatch, getters }) {
      const { selectedList } = getters;
      dispatch("queryCartCount");
      const [result] = await goodFee({
        skuInfoList: selectedList
      });
      commit(types.SAVE_ACTIVITY_INFO, [result][0]?.activityInfo ?? []);
      commit(types.SAVE_CART_CALC_FEE_INFO, [result][0]?.calcFeeInfo ?? {});
    },
    delGoodSaEvent(_, params) {
      const sku_nos = params.goodsInfo.map(item => `${item.skuId}`);
      saTrackEvent("MINI_ShoppingCartPageDeletePopupWindowDeleteBtnClick", { sku_nos });
    },
    saveCartCount({ commit }, count) {
      commit(types.SAVE_CART_COUNT, count);
    },
    async queryCartCount({ commit }) {
      const [data] = await getCartCount();
      if (data) {
        commit(types.SAVE_CART_COUNT, data.count);
      }
    }
  },
  getters: {
    cartTotal: state => {
      return state.cartList.length;
    },
    isSelectedAll: state => {
      const selectList = state.cartList.filter(item => {
        if (item.selected) {
          return item;
        }
      });
      return state.cartList.length && selectList.length === state.cartList.length;
    },
    selectedList: state => {
      const selectedGoods = [];
      state.cartList.forEach(item => {
        if (item.selected) {
          const good = {
            skuId: item.skuId,
            skuNum: item.count,
            skuSource: item.skuSource,
            product: item
          };
          selectedGoods.push(good);
        }
      });
      return selectedGoods;
    }
  }
};
export default shopCart;
