import '@/types/Store/Shopee/Shopee';
import { apiCollectionList, apiKeywordList, apiKeywordAdd } from '@/api/autoshopee/shopee/keyword';
import { exportSheet } from '@/lib/utils/sheet';
import i18n from '@/vue/i18n';

/** @type {VuexStoreModule} */
export const keywordStore = {
  state() {
    return {
      listCollection: [],
    };
  },
  mutations: {
    SHOPEE_KEYWORD_SET_LIST_COLLECTION(state, listCollection) {
      state.listCollection = listCollection;
    },
    SHOPEE_KEYWORD_INC_COUNT_COLLECTION(state, collectionId) {
      const collection = state.listCollection.find((item) => item._id === collectionId);
      if (collection) {
        collection.count++;
      }
    },
  },
  getters: {
    getShopeeKeywordCollection(state) {
      return state.listCollection.map((item) => ({
        label: i18n.t('KEYWORD_COLLETION_LABEL', item),
        ...item,
      }));
    },
  },
  actions: {
    async ShopeeKeywordFetch({ commit }) {
      const listData = (await apiCollectionList()).data;
      commit('SHOPEE_KEYWORD_SET_LIST_COLLECTION', listData);
      return listData;
    },
    async ShopeeKeywordAdd({ commit }, {
      collectionId, keyword, price, type, algorithm,
    }) {
      const payload = {
        keyword,
        price: Number(price),
        algorithm: algorithm || 'kwrcmdv3',
        type: type || 'exact',
        active: true,
      };

      const result = (await apiKeywordAdd(collectionId, payload)).data;

      commit('SHOPEE_KEYWORD_INC_COUNT_COLLECTION', collectionId);

      return result;
    },
    async ShopeeKeywordGet(_, id) {
      return (await apiKeywordList(id)).data;
    },
    async ShopeeKeywordExport(_, { id, name }) {
      const listKeyword = (await apiKeywordList(id)).data.map((item) => {
        return {
          [i18n.t('KEYWORD_COLUM.KEYWORD')]: item.keyword,
          [i18n.t('KEYWORD_COLUM.PRICE')]: item.price,
          [i18n.t('KEYWORD_COLUM.PRICE_CURRENT')]: item.priceCurrent,
          [i18n.t('KEYWORD_COLUM.PRICE_MIN')]: item.priceMin,
          [i18n.t('KEYWORD_COLUM.PRICE_MAX')]: item.priceMax,
          [i18n.t('KEYWORD_COLUM.NOTE')]: item.note,
        };
      });

      return exportSheet(listKeyword, i18n.t('EXPORT_KEYWORD_SHEET', { name }));
    },
  },
};
