<template>
  <div>
    <Table
        ref="TableProductList"
        :columns="tableProductSpy.columns"
        :data="tableProductSpy.data"
        highlight-row
        size="small"
        height="800"
        border
      >
        <template
          slot="name"
          slot-scope="{ row }"
        >
          <a
            :href="row.productUrl"
            target="_blank"
          >{{ row.name | maxString(80) }}</a>
        </template>
        <template
          slot="shopName"
          slot-scope="{ row }"
        >
          <a
            :href="row.shopUrl"
            target="_blank"
          >{{ row.shopName }}</a>
        </template>
        <template
          slot="image"
          slot-scope="{ row }"
        >
          <img
            :src="row.image"
            style="width: 50px"
          >
        </template>
        <template
          slot="action"
          slot-scope="{ row }"
        >
          <Button
            type="primary"
            ghost
            size="small"
            class="mr-5"
            :loading="row.loading"
            @click="onFetchProduct(row)"
          >
            {{ $t('FETCH_BTN') }}
          </Button>

          <Button
            type="error"
            ghost
            size="small"
            :loading="row.loading"
            @click="onRemoveProduct(row)"
          >
            {{ $t('REMOVE_BTN') }}
          </Button>
        </template>
      </Table>
  </div>
</template>

<script>
import { ShopeeSpyList, ShopeeSpyLog, fetchSpyUpdate } from '@/models/shopee/spy';
import { getShopeeProductId } from '@/api/shopee/client/product';
import { productUrl, shopUrlId } from '@/adapter/shopee/render/index';
import { openAndCloselUrl } from '@/browser/tab';
import { getDateOnly } from '@/lib/utils/moment';
import { tableSpyDashboard } from '@/vue/components/Shopee/Spy/mixin/Table';
import { loggerShopee } from '@/plugins/logger';

export default {
  name: 'ShopeeSpyDashboard',
  data() {
    return {
      listProductSpy: [],
    };
  },
  methods: {
    async fetchList() {
      this.listProductSpy = (
        await ShopeeSpyList.findMany({
          type: 'product',
        })
      ).map((item) => ({
        ...item,
        loading: false,
      }));
    },
    getSpyId(id) {
      return this.listProductSpy.find((item) => item._id === id);
    },
    async onFetchProduct(spyData) {
      const getSpy = this.getSpyId(spyData._id);
      getSpy.loading = true;

      try {
        if (spyData.type === 'product') {
          let productData = await getShopeeProductId(spyData.productId, spyData.shopId);

          if (!productData) {
            await openAndCloselUrl(spyData.productUrl, 2000).catch(() => {});
            productData = await getShopeeProductId(spyData.productId, spyData.shopId);
          }

          if (productData) {
            fetchSpyUpdate(spyData, productData);
          }
        }
      } catch (error) {
        loggerShopee.error({
          msg: 'SHOPEE_SPY_FETCH_ERROR',
          error,
        });
      }

      getSpy.loading = false;
    },
    onRemoveProduct(spyData) {
      this.$Modal.confirm({
        content: spyData.name,
        title: this.$t('REMOVE_CONFIRM'),
        onOk: async () => {
          this.$Message.success(this.$t('REMOVE_SUCCESS'));
          ShopeeSpyList.removeId(spyData._id);

          if (spyData.type === 'product') {
            this.listProductSpy = this.listProductSpy.filter((item) => item._id !== spyData._id);
          }
        },
      });
    },
  },
  created() {
    this.fetchList();
    ShopeeSpyList.syncRemote();
    ShopeeSpyLog.syncRemote();
  },
  computed: {
    tableProductSpy() {
      return {
        columns: tableSpyDashboard.columns,
        data: this.listProductSpy.map((product) => {
          return {
            ...product,
            productUrl: productUrl(product.productId, product.shopId),
            shopUrl: shopUrlId(product.shopId),
            showTime: getDateOnly(new Date(product.time)),
            sale: product.sale,
            sold: product.sold,
            price: product.price,
            promotion: product.promotion,
          };
        }),
      };
    },
  },
};
</script>
