import { getListAdsCampaign } from '@/api/shopee/seller/ads';
import { imageUrl } from '@/adapter/shopee/render/index';
import lodash from 'lodash';

import { unixTime, roundNumber, tableCampaginColumn } from './Data';

import { defineComponent } from '@vue/composition-api';

export default defineComponent({
  data() {
    return {
      tableCampagin: {
        column: tableCampaginColumn,
        data: [],
        loading: true,
      },
      query: {
        limit: 10,
        page: 0,
        state: 'all',
        type: '',
        search: '',
      },
    };
  },
  methods: {
    openCampagin(id) {
      return this.openExternalUrl(this.createPopupUrl(`/shopee/ads/${id}`));
    },
    async getList() {
      this.tableCampagin.loading = true;

      const listCampagin = await getListAdsCampaign(this.query.limit, this.query.page, this.query.state, this.query.type, this.query.search);

      this.tableCampagin.data = listCampagin.map((item, index) => {
        const imageId = item.product.images ? item.product.images.split(',')[0] : '';
        const listKeyword = lodash.get(item, 'advertisements[1].extinfo.keywords', []);

        const payload = {
          index: index + 1,
          id: item.campaign.campaignid,
          type: this.$t(`SHOPEE_ADS_TYPE_BY.${item.campaign.type}`),
          state: this.$t(`SHOPEE_ADS_STATE_BY.${item.campaign.state}`),
          name: item.product.name || this.getShopeeShopName,
          itemid: item.product.itemid,
          stock: item.product.stock,
          image: imageId ? imageUrl(imageId) : this.getShopeeShopImage,
          timeStart: unixTime(item.campaign.start_time),
          timeEnd: item.campaign.end_time ? unixTime(item.campaign.end_time) : '',
          dailyExpense: Number(item.campaign.daily_expense) || 0,
          dailyQuota: Number(item.campaign.daily_quota) || 0,
          totalExpense: Number(item.campaign.total_expense) || 0,
          listKeyword,
          countKeyword: listKeyword.length,
        };

        payload.dailyExpense = this.$n(roundNumber(payload.dailyExpense));
        payload.dailyQuota = this.$n(roundNumber(payload.dailyQuota));
        payload.totalExpense = this.$n(roundNumber(payload.totalExpense));

        payload.timeStart = this.$d(payload.timeStart);
        payload.timeEnd = payload.timeEnd ? this.$d(payload.timeEnd) : '';

        return payload;
      });

      this.tableCampagin.loading = false;
    },
  },
  created() {
    this.getList();
  },
});
