import {
  ArticleApi,
  ArticleWithoutParentDto,
} from '../../../openapi/reference-information';
import { ActionTree, GetterTree, MutationTree } from 'vuex';

const articleApi = new ArticleApi();
interface ArticleWithChildren extends ArticleWithoutParentDto {
  parentId?: string;
  children?: Array<ArticleWithChildren>;
}

interface State {
  articleRecords: Array<ArticleWithChildren>;
  activeArticle: ArticleWithChildren;
  loading: boolean;
}

export const state: State = {
  articleRecords: [],
  activeArticle: {},
  loading: false,
};

export const getters: GetterTree<State, State> = {
  setArticleRecords(state) {
    return state.articleRecords;
  },
  setActiveArticle(state) {
    return state.activeArticle;
  },
  servicesLoading(state) {
    return state.loading;
  },
};

export const mutations: MutationTree<State> = {
  setArticleRecords(state, card) {
    state.articleRecords = card;
  },
  setActiveArticle(state, article) {
    state.activeArticle = article;
  },
  servicesLoading(state, loading) {
    state.loading = loading;
  },
};

export const actions: ActionTree<State, State> = {
  setArticleRecordsJson({ commit }, newCard) {
    if (newCard) {
      commit('setArticleRecords', newCard);
    }
  },
  getArticleRecords({ commit }) {
    commit('servicesLoading', true);
    articleApi.hierarchy().then((res) => {
      let articleRecords = res.data as ArticleWithChildren[];
      const sortOrderList = articleRecords.map((e) => e.sortOrder || 0);
      const maxDepth = Math.max(...sortOrderList);

      for (let i = 1; i < maxDepth + 1; i++) {
        const parents = articleRecords.filter((e) => e.sortOrder === i - 1); // чтобы меньше переменных перебирать
        const childs = articleRecords.filter((e) => e.sortOrder === i);
        childs.forEach((e) => {
          if (e.sortOrder === i) {
            const findArticle = parents.find((y) => y.id === e.parentId) || {};

            if (findArticle.children && findArticle.children.length) {
              findArticle.children.push(e);
            } else {
              // findArticle.children = [e]
              Object.assign(findArticle, { children: [e] });
            }
          }
        });
      }
      articleRecords = articleRecords.filter((e) => e.sortOrder === 0);
      commit('setArticleRecords', articleRecords);
      commit('servicesLoading', false);
    });
  },
  getArticle({ commit }, id) {
    commit('servicesLoading', true);
    articleApi.getArticle(id).then((res) => {
      commit('setActiveArticle', res.data);
      commit('servicesLoading', false);
    });
  },
  setActiveArticleJson({ commit }, newArticle) {
    if (newArticle) {
      commit('setActiveArticle', newArticle);
    }
  },
  setLoadArticle({ commit }, load) {
    commit('servicesLoading', load);
  },
};
