import {
  getCartNumDataAPI,
  addCartAPI,
  updateCartAPI,
  getCartListDataAPI,
  deleteCartListDataAPI,
  deleteCartListData2API,
  emptyCartAPI
} from "../services/api";

import { getCustomer } from "@/utils/request";

/**
 * 购物车
 */
export default {
  namespace: "cartList",

  state: {},

  effects: {
    // 请求购物车数据
    *getCartListData({ payload }, { call, put }) {
      if (!payload) payload = {};
      payload.customer = getCustomer().id;
      const response = yield call(getCartListDataAPI, payload);
      yield put({
        type: "cartListData",
        cartListData: response
      });
    },
    *deleteAllCartListData({ payload }, { call, put }) {
      if (!payload) payload = {};
      payload.customer = getCustomer().id;
      const response2 = yield call(emptyCartAPI, payload);
      const response = yield call(getCartListDataAPI, payload);
      yield put({
        type: "cartListData",
        cartListData: response
      });
    },
    // 删除购物车-单项
    *deleteCartListData({ payload }, { call, put }) {
      if (!payload) payload = {};
      payload.customer = getCustomer().id;
      const response = yield call(deleteCartListDataAPI, payload);
      let cartNum = 0;
      for (const item of response) {
        const cartlist = item.cartlist;
        for (const cart of cartlist) {
          cartNum++;
        }
      }
      yield put({
        type: "cartListData",
        cartListData: response
      });
    },
    // 获取购物车数量
    *getCartNumData({ payload }, { call, put }) {
      if (!payload) payload = {};
     payload.customer = getCustomer().id;
      const response = yield call(getCartNumDataAPI, payload);
      yield put({
        type: "cartNum",
        cartNum: response
      });
    },
    // 添加购物车
    *addCart({ payload }, { call, put }) {
      if (!payload) payload = {};

      payload.customerId = getCustomer().id;
      payload.isPrimaryChannel = 1;

      const response = yield call(addCartAPI, payload);
      yield put({
        type: "getCartListData",
        payload
      });
    },
    // 更新购物车
    *updateCart({ payload }, { call, put }) {
      payload.customer = getCustomer().id;
      yield call(updateCartAPI, payload);
    }
  },

  reducers: {
    cartListData(state, { cartListData }) {
      let cartNum = 0;
      const cartCheckStatus = {};
      for (const item of cartListData) {
        cartCheckStatus[item.saleOrgId] = false;
        cartCheckStatus[`childSize${item.saleOrgId}`] = item.cartlist.length;
        cartCheckStatus[`checkedSize${item.saleOrgId}`] = 0;
        for (const i of item.cartlist) {
          const key = `${item.saleOrgId}${i.id}`;
          cartCheckStatus[key] = false;
          cartNum++;
        }
      }
      return {
        ...state,
        cartListData,
        cartCheckStatus,
        cartNum
      };
    },
    cartNum(state, { cartNum }) {
      return {
        ...state,
        cartNum
      };
    }
  }
};
