import { getGoodsSupplyDetailAPI, getGoodsListAPI } from "../services/api";
import { getCustomer } from '@/utils/request';

export default {
  namespace: "goodsSupplyDetail",

  state: {},

  effects: {
    // 获取供应商列表
    *getGoodsSupplyDetailList({ payload }, { call, put }) {
      payload.customerId = getCustomer().id;
      const response = yield call(getGoodsSupplyDetailAPI, payload);
      yield put({
        type: "goodsSupplyDetailData",
        goodsSupplyDetailData: response
      });
    },
    // 获取货补商品及本供货方最高可用货补金额
    *getSupplyAmountAndGoodsList({ payload }, { call, put }) {
      const key = payload.key;
      const params = {
        search_organization: payload.supplierId,
        search_casttype: payload.castTypeId,
        search_financeOrgId: payload.financeOrgId,
        search_customerId: getCustomer().id
      };
      const response = yield call(getGoodsListAPI, params) || [];
      // 返回值必须封装key值 key=goodsIds
      if (response && response.goodsItems) {
        let goodsItems = response.goodsItems;
        goodsItems.forEach(item => {
          item.key = item.id;
        });
        // 如果Key有值，则过滤商品行
        if (key) {
          goodsItems = goodsItems.filter(
            item =>
              item.displayName.indexOf(key) >= 0 || item.code.indexOf(key) >= 0
          );
        }
        response.goodsItems = goodsItems;
      }
      yield put({
        type: "supplyAmountAndGoodsList",
        supplyAmountAndGoodsList: response
      });
    }
  },

  reducers: {
    goodsSupplyDetailData(state, payload) {
      return {
        ...state,
        goodsSupplyDetailData: payload.goodsSupplyDetailData
      };
    },
    supplyAmountAndGoodsList(state, payload) {
      return {
        ...state,
        supplyAmountAndGoodsList: payload.supplyAmountAndGoodsList
      };
    }
  }
};
