coupon.js 2.24 KB
export default function() {
  return {
    namespaced: true,
    state: {
      unused: {
        type: 'unused',
        isFetching: false,
        reachedEnd: false,
        isEmpty: false,
        list: [],
        filter: 0,
        page: 0,
        limit: 10,
        total: 0
      },
      used: {
        type: 'used',
        isFetching: false,
        reachedEnd: false,
        isEmpty: false,
        list: [],
        filter: 0,
        page: 0,
        limit: 10,
        total: 0
      },
      overtime: {
        type: 'overtime',
        isFetching: false,
        reachedEnd: false,
        isEmpty: false,
        list: [],
        filter: 0,
        page: 0,
        limit: 10,
        total: 0
      },
    },
    mutations: {
      addList(state, { data }) {
        state[data.type] = data;
      }
    },
    actions: {
      async fetchCouponList({ commit, state }, param) {
        if (!param.type) {
          return;
        }
        let couponData = {...state[param.type]};

        if (!param.isReset && couponData.reachedEnd) {
          return;
        }

        let params = {
          page: couponData.page,
          limit: couponData.limit,
          type: couponData.type,
        };

        if (param.isReset) {
          params.page = 1;
        } else {
          params.page += 1;
        }

        let result = await this.$api.get('/api/ufo/coupon/list', {...params});

        if (result.code === 200) {
          let data = result.data;

          if (typeof data === 'object' && Object.keys(data).length) {
            for (let key in data) {
              if (key === 'coupons') {
                couponData.list = data.page > 1 ? couponData.list.concat(data.coupons) : data.coupons;
              } else {
                couponData[key] = data[key];
              }
            }
            if (couponData.list.length === couponData.total) {
              couponData.reachedEnd = true;
            }
            couponData.list.length ? couponData.isEmpty = false : couponData.isEmpty = true;

            commit('addList', { data: couponData });
          }
        } else {
          couponData.isEmpty = true;
          commit('addList', { data: couponData });
        }
        return couponData.list || [];
      },
    },
  };
}