<template>
  <div class="shopee-video-posts p-3">
    <h3 class="mb-2">
      {{ $t('SHOPEE_VIDEO_POSTS_TITLE') }}
    </h3>

    <Row
      :gutter="8"
      class="mb-3"
    >
      <Col span="8">
        <Card>
          <p>{{ $t('SHOPEE_VIDEO_STATS_CAMPAIGNS') }}</p>
          <h2>{{ stats.campaigns }}</h2>
        </Card>
      </Col>
      <Col span="8">
        <Card>
          <p>{{ $t('SHOPEE_VIDEO_STATS_DONE') }}</p>
          <h2>{{ stats.done }}</h2>
        </Card>
      </Col>
      <Col span="8">
        <Card>
          <p>{{ $t('SHOPEE_VIDEO_STATS_ERROR') }}</p>
          <h2>{{ stats.error }}</h2>
        </Card>
      </Col>
    </Row>

    <Select
      v-model="campaignId"
      class="mb-2"
      @on-change="loadItems"
    >
      <Option
        v-for="campaign in campaigns"
        :key="campaign._id"
        :value="campaign._id"
      >
        {{ campaign.name }}
      </Option>
    </Select>

    <Table
      :columns="columns"
      :data="items"
      :loading="loading"
    />
  </div>
</template>

<script>
import { defineComponent } from '@vue/composition-api';
import { getShopeeSellerInfo } from '@/api/shopee/seller/get';
import {
  apiShopeeVideoCampaignStats,
  apiShopeeVideoCampaignList,
  apiShopeeVideoItemList,
} from '@/api/autoshopee/shopee/shopeeVideo';

export default defineComponent({
  data() {
    return {
      shopId: '',
      stats: {
        campaigns: 0,
        items: 0,
        done: 0,
        error: 0,
        pending: 0,
      },
      campaigns: [],
      campaignId: '',
      items: [],
      loading: false,
      columns: [
        { title: this.$t('SHOPEE_VIDEO_COL_SOURCE'), key: 'source' },
        { title: this.$t('SHOPEE_VIDEO_COL_CAPTION'), key: 'caption' },
        { title: this.$t('SHOPEE_VIDEO_COL_STATUS'), key: 'status' },
        { title: this.$t('SHOPEE_VIDEO_COL_POSTED'), key: 'postedAt' },
      ],
    };
  },
  async created() {
    const sellerInfo = await getShopeeSellerInfo();

    if (sellerInfo && sellerInfo.shop_id) {
      this.shopId = `${sellerInfo.shop_id}`;
    }

    if (!this.shopId) {
      return;
    }

    this.stats = await apiShopeeVideoCampaignStats(this.shopId);
    this.campaigns = await apiShopeeVideoCampaignList(this.shopId);

    if (this.campaigns.length) {
      this.campaignId = this.campaigns[0]._id;
      await this.loadItems();
    }
  },
  methods: {
    async loadItems() {
      if (!this.campaignId) {
        this.items = [];
        return;
      }

      this.loading = true;
      this.items = await apiShopeeVideoItemList(this.campaignId);
      this.loading = false;
    },
  },
});
</script>
