import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';
import _ from 'lodash';
Vue.use(Vuex);
const api = {
  list: `/api/cms/news/list`,
  fetch: id => `/api/cms/news/fetch/${id}`,
  bugList: `/api/cms/newscreeper/list`,
};
export const state = () => ({});
export const mutations = {};
export const actions = {
  //请求所有新闻
  async getAllNews({ commit, dispatch }, payload) {
    let toGet = () => {
      let res = [];
      for (const item of payload) {
        let data = {
          skip: 0,
          limit: 8,
        };
        if (item.type === 'bugList') {
          data.news_type = `0`;
          data.parent_id = item.content_id;
        } else {
          data.news_type = `1`;
          data.parent_id = item.id;
        }
        res.push(
          dispatch('getNews', {
            type: 'bugList',
            data,
          })
        );
      }
      return res;
    };
    let result = await axios.all(toGet());
    //降维
    let arr = _.flattenDeep(_.flattenDeep(result).map(item => item.data));
    return arr;
  },
  async getNews({ commit }, { type, data }) {
    let result;
    if (type !== 'fetch') {
      result = await this.$axios.$get(api.bugList, { ...data, is_use: '0' });
    } else {
      let { id } = data;
      result = await this.$axios.$get(api.fetch(id));
    }

    return result;
  },
};
