mutations.js 2.83 KB
import * as Types from './types';
import { find, set } from 'lodash';

import { defaultProduct, defaultSelectedSize } from './index';

function ensureProduct(state, productId) {
  if (state.products[productId] === undefined) {
    state.products = {...state.products, [productId]: defaultProduct()};
  }
}
function ensureSelectedProduct(state, productId) {
  if (!state.selectedProductInfo || state.selectedProductInfo.productId !== productId) {
    ensureProduct(state, productId);

    state.selectedProductInfo = {
      productId,
      product: state.products[productId],
      sizeId: null,
      storageId: null,
      size: {},
    };
  }
}

export default {
  [Types.ENSURE_PRODUCT_DETAIL](state, { productId }) {
    ensureProduct(state, productId);
  },
  [Types.UPDATE_PRODUCT_DETAIL](state, payload) {
    state.products = {...state.products, [payload.product_id]: payload};
    ensureSelectedProduct(state, payload.product_id);
  },
  [Types.UPDATE_BRAND_PRODUCT_TOP_LIST](state, { productId, topList }) {
    state.topLists = {...state.topLists, [productId]: topList};
  },
  [Types.UPDATE_PRODUCT_COUPON_LIST](state, { productId, couponList }) {
    state.couponLists = {...state.couponLists, [productId]: couponList};
  },
  [Types.UPDATE_PRODUCT_COUPON_TOP_LIST](state, { productId, couponTopList }) {
    state.couponTopLists = {...state.couponTopLists, [productId]: couponTopList};
  },
  [Types.UPDATE_PRODUCT_FAV](state, { productId, isFav }) {
    state.fav = {...state.fav, [productId]: isFav};
  },
  [Types.UPDATE_SELECTED_PRODUCT_SIZE](state, { productId, sizeId, storageId }) {
    ensureSelectedProduct(state, productId);

    const sizeList = state.selectedProductInfo.product.goods_list[0].size_list;

    let sizeInfo;

    if (storageId) {
      sizeInfo = find(sizeList, (size) => size.storage_id === storageId);
    } else {
      sizeInfo = find(sizeList, (size) => size.size_id === sizeId);
    }

    if (sizeInfo) {
      state.selectedProductInfo.sizeId = sizeInfo.size_id;
      state.selectedProductInfo.storageId = sizeInfo.storage_id;
    }
    state.selectedProductInfo.size = sizeInfo;
  },
  [Types.RESET_SELECTED_PRODUCT_SIZE](state) {
    Object.assign(state.selectedProductInfo, defaultSelectedSize());
  },
  [Types.SETUP_INITIAL_PRODUCT_INFO](state, payload) {
    const { id: productId } = payload;

    const productInfo = state.products[productId];

    // 规格化数据
    [['id', 'product_id'], ['price', 'least_price'], ['product_name'], ['default_images', 'goods_list[0].image_list[0].image_url']].forEach((keyMap) => {
      const val = payload[keyMap[0]];

      if (val !== null) {
        set(productInfo, keyMap[1] || keyMap[0], val);
        if (keyMap[0] === 'default_images') {
          set(productInfo, 'goods_list[0].image_list[0].initial', true); // 区分初始化数据,方便使用缓存
        }
      }
    });
  }
};