import * as types from './type';
import Vue from 'vue';
import { parseTime } from '../../../service/utils.service';
// import { saTrackEvent } from '@/utils/sa';
// import { getCartCount } from '@/api/home.api';
import { query, goodSelected, goodAdd, goodFee, getCartCount } 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,
    selectedAddress: {},
    pullRefresh: false,
    timer: null,
    timeArray: []
  },
  mutations: {
    [types.SET_TIMER](state, data) {
      state.timer = data;
    },
    [types.SET_TIME_ARRAY](state, data) {
      state.timeArray = data;
    },
    [types.SET_PULL_REFRESH](state, data) {
      state.pullRefresh = data;
    },
    [types.CHOOSE_ADDRESS](state, data) {
      Vue.set(state, 'selectedAddress', data);
    },
    [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, idx = null, goodInfo = {}, isAll = false, cartList = [] }
    ) {
      if (isAll) {
        // 全选
        Vue.set(state, 'cartList', cartList);
      } else {
        Vue.set(state.cartList[idx].skus, index, goodInfo);
      }
    },
    [types.DEL_CART_GOOD](state, { goodsInfo }) {
      const cart = state.cartList;
      goodsInfo.forEach(good => {
        for (let i = 0; i < cart.length; i++) {
          for (let j = 0; j < cart[i].skus.length; j++) {
            if (cart[i].skus[j].skuId === good.skuId) {
              cart[i].skus.splice(j, 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}`
      // };
      // console.log(params);
      // goodCount ? uni.setTabBarBadge(params) : uni.removeTabBarBadge({ index: 1 });
      Vue.set(state, 'cartCount', count);
    }
  },
  actions: {
    async add_to_cart({ commit, dispatch }, goodInfo) {
      const params = {
        type: 'ADD_CART',
        goodInfo: {
          skuId: goodInfo.skuId,
          skuNum: goodInfo.skuNum,
          skuSource: goodInfo.skuSource,
          selected: true
        }
      };
      const [, error] = await dispatch('good_add', params);
      if (!error) {
        Vue.prototype.$toast('购物车添加成功！');
        dispatch('queryCartCount');
        commit(types.SET_PULL_REFRESH, true);
      }
    },
    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) {
      commit(types.SET_PULL_REFRESH, false);
      const [data] = await query(params);
      if (data) {
        dispatch('update_cart_list', data);
      }
    },
    update_cart_list({ commit, dispatch }, data) {
      let goods = [];
      if (data && (data.cartInfoList || data.addCartMore30CartInfoList)) {
        goods = data.cartInfoList && [...goods, ...data.cartInfoList];
        goods = data.addCartMore30CartInfoList && [...goods, ...data.addCartMore30CartInfoList];
        console.log(goods, 'goods');
        const timeArray = goods.map(item => {
          return item.skus.map(it => {
            if (it.activityShowInfo && it.activityShowInfo.activityTimeInfo) {
              const activityTimeInfo = it.activityShowInfo.activityTimeInfo;
              const { startTime, endTime, currentTime } = activityTimeInfo;
              const overStartTimeOneDay = startTime - currentTime > 24 * 60 * 60 * 1000; // 是否距离开始时间超过一天
              const activityStart = startTime < currentTime; // 活动是否开始
              const overEndTimeOneDay = endTime - currentTime > 24 * 60 * 60 * 1000; // 是否距离结束时间超过一天
              const activityEnd = currentTime > endTime; // 活动是否结束
              it.activityShowInfo.activityTimeInfo.activityText = '';
              if (overStartTimeOneDay) {
                it.activityShowInfo.activityTimeInfo.activityText = `开始时间 ${parseTime(
                  startTime,
                  '{m}月{d}日 {h}:{i}'
                )}`;
                return 0;
              }
              if (!overStartTimeOneDay && !activityStart) {
                it.activityShowInfo.activityTimeInfo.activityText = '距开始 ';
                return startTime - currentTime;
              }
              if (overEndTimeOneDay && activityStart) {
                it.activityShowInfo.activityTimeInfo.activityText = `结束时间 ${parseTime(
                  endTime,
                  '{m}月{d}日 {h}:{i}'
                )}`;
                return 0;
              }
              if (!overEndTimeOneDay && !activityEnd) {
                it.activityShowInfo.activityTimeInfo.activityText = '距结束 ';
                return endTime - currentTime;
              }
              if (activityEnd) {
                it.activityShowInfo.activityTimeInfo.activityText = '活动已经结束';
                return 0;
              }
            } else {
              return 0;
            }
          });
        });
        let arr = [];
        timeArray.forEach(i => {
          arr = arr.concat([...i]);
        });
        if (arr.some(i => !!i)) {
          dispatch('count_down');
        }
        commit(types.SET_TIME_ARRAY, timeArray);
        commit(types.CHOOSE_ADDRESS, data?.addrReceiverInfo || {});
        commit(types.SAVE_CART_LIST, goods);
        commit(types.SAVE_CART_CALC_FEE_INFO, data?.calcFeeInfo ?? {});
        dispatch('good_fee');
      }
    },
    count_down({ state, commit, dispatch }) {
      const timer = setInterval(() => {
        const timeArray = state.timeArray.map(it => {
          return it.map(i => {
            if (i > 0) {
              i = i - 1000 >= 0 ? i - 1000 : 0;
              if (i === 0) {
                dispatch('clear_timer');
                dispatch('query_cart_list');
              }
            }
            return i;
          });
        });
        commit(types.SET_TIME_ARRAY, timeArray);
      }, 1000);
      commit(types.SET_TIMER, timer);
    },
    clear_timer({ state, commit }) {
      state.timer && clearInterval(state.timer);
      commit(types.SET_TIMER, null);
    },
    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.skus.forEach(i => {
          i.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 [res] = await dispatch('good_add', params);
      if (res?.needRefresh) {
        commit(types.SELECT_CART_GOOD, params);
        dispatch('good_fee');
      } else {
        Vue.prototype.$toast(res?.message || '操作失败，请稍后重试');
      }
    },
    good_selected({ state }, params) {
      let skuList = [];
      let selected = null;
      if (typeof params === 'boolean') {
        const arr = state?.cartList?.map(i => i.skus) || [];
        let skus = [];
        arr.forEach(i => {
          skus = [...skus, ...i];
        });
        skuList = skus.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;
      const [result] = await goodFee({
        skuInfoList: selectedList
      });
      // commit(types.SAVE_ACTIVITY_INFO, [result][0]?.activityInfo ?? []);
      commit(types.SAVE_CART_CALC_FEE_INFO, [result][0]?.calcFeeInfo ?? {});
      dispatch('queryCartCount');
    },
    // 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 && data.count) {
        const count = data.count > 99 ? '99+' : data.count ? data.count : '';
        commit(types.SAVE_CART_COUNT, count);
      } else {
        commit(types.SAVE_CART_COUNT, '');
      }
    }
  },
  getters: {
    cartTotal: state => {
      return state.cartList.length;
    },
    cartCount: state => {
      return state.cartCount;
    },
    cartSkuList: state => {
      const arr = state.cartList?.map(i => i.skus);
      return [].concat(...arr);
    },
    isSelectedAll: state => {
      const arr = state.cartList.map(i => i.skus);
      const arr1 = [].concat(...arr);
      const selectList = arr1.filter(item => {
        if (item.selected) {
          return item;
        }
      });
      return state.cartList.length && selectList.length === arr1.length;
    },
    selectedList: state => {
      const selectedGoods = [];
      const arr = state.cartList.map(i => i.skus);
      const arr1 = [].concat(...arr);
      arr1.forEach(item => {
        if (item.selected) {
          const good = {
            skuId: item.skuId,
            skuNum: item.count,
            skuSource: item.skuSource,
            product: {
              skuId: item.skuId,
              skuImg: item.skuImg,
              skuName: item.skuName,
              commonLimitCount: item.commonLimitCount,
              count: item.count,
              userType: item.activityShowInfo?.userType || null
            }
          };
          selectedGoods.push(good);
        }
      });
      return selectedGoods;
    }
  }
};
export default shopCart;
