import { mapActions, mapGetters } from 'vuex';
import { importProduct, saveUpload, handlerUpload } from '@/api/autoshopee/tiktok';

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

const colorStatus = {
  text: '#000',
  pending: '#ff9900',
  success: '#19be6b',
  error: '#ed4014',
};

const platform = 'tiktok';

export default defineComponent({
  data() {
    return {
      product: null,
      rendered: null,
      selected: {
        shop: '',
        warehouse: '',
      },
      log: {
        color: '',
        text: '',
      },
      btnLoading: false,
    };
  },
  methods: {
    ...mapActions('tiktok', ['TiktokSelectShop', 'TiktokGetListShop', 'TiktokSelectWarehouse', 'TiktokGetListWarehouse']),
    downScore() {
      this.UseScoreClone(platform);
    },
    openAddShop() {
      this.openExternalUrl(`${this.configAppApi.appHost}/tiktok/shop/oauth`);
    },
    buyScore() {
      this.openExternalUrl(`${this.configAppApi.appHost}/upgrade`);
    },
    async refactorProduct(weight = 10, all = 10) {
      try {
        this.product.promotion = 0;
        this.product.price = this.product.price_before_discount || this.product.price;
        this.product.models = this.product.models.map((item) => ({
          ...item,
          promotion: item.price_before_discount ? item.price : 0,
          price: item.price_before_discount || item.price,
        }));
        this.product.weight = weight;
        this.product.dimension = {
          weight,
          height: all,
          length: all,
          width: all,
        };

        const { data } = await importProduct(this.product, {
          category: null,
          platform: this.product.platform,
        });

        if (data) {
          data.source.from = this.product.platform;

          data.source.params = {
            isQueue: true,
            shopId: this.product.shopId,
            productId: this.product.productId,
            url: this.product.url || '',
          };

          this.rendered = data;
        } else {
          throw 'EROR_RENDER_PRODUCT';
        }
      } catch (error) {
        this.log.color = colorStatus.error;
        this.log.text = this.$t('ERROR_GET_DATA');

        loggerTiktok.error({
          msg: 'REFACTOR_PRODUCT_ERROR',
          error,
        });
      }
    },
    async saveUpload(uploadNow = false) {
      this.btnLoading = true;
      this.log.color = colorStatus.pending;
      this.log.text = `${this.$t('PROCESSING_MSG')}...`;

      await this.refactorProduct();
      try {
        const { data: save } = await saveUpload(this.rendered, this.selected.shop, this.selected.warehouse);
        if (save) {
          if (uploadNow) {
            return save;
          }

          this.btnLoading = false;
          this.log.color = colorStatus.success;
          this.log.text = this.$t('SUCCESS_MSG');

          this.openExternalUrl(`${this.configAppApi.appHost}/tiktok/upload/product/edit/${save._id}`, true);
        } else {
          throw this.rendered;
        }
      } catch (error) {
        loggerTiktok.error({
          msg: 'PRE_HANDLER_ERROR',
          error,
        });
        this.btnLoading = false;
        this.log.color = colorStatus.error;
        this.log.text = this.$t('SAVE_ERROR_UNKNOW');

        return null;
      }
    },
    async handlerUpload() {
      this.btnLoading = true;

      try {
        this.log.color = colorStatus.pending;
        this.log.text = `${this.$t('PROCESSING_MSG')}...`;
        const save = await this.saveUpload(true);
        const result = await handlerUpload(save._id);

        if (result.success && result.data && result.data.product_id) {
          this.openExternalUrl(`${this.configAppApi.tiktok.seller}/product/edit/${result.data.product_id}`, false);
          this.log.color = colorStatus.success;
          this.log.text = this.$t('SUCCESS_MSG');
          this.downScore();
        } else {
          this.log.color = colorStatus.error;
          this.log.text = result.msg;
        }
      } catch (error) {
        this.log.text = this.$t('SYNC_ERROR_UNKNOW');
        this.log.color = colorStatus.error;
        loggerTiktok.error({
          msg: 'HANDLER_ERROR',
          error,
        });
      }

      this.btnLoading = false;
    },
    async onWarehouse(value) {
      if (value) {
        this.TiktokSelectWarehouse(value);
      }
    },
    async onChangeShop(value, loading = true) {
      if (loading) {
        this.btnLoading = true;
      }

      if (value) {
        await this.TiktokSelectShop(value).catch(() => {});
      }

      if (this.getTiktokWarehouseList && this.getTiktokWarehouseList.length) {
        this.selected.warehouse = this.getTiktokWarehouseList[0].warehouse_id;
        this.onWarehouse(this.selected.warehouse);
      }

      if (loading) {
        this.btnLoading = false;
      }
    },
    async init() {
      await this.TiktokGetListShop();

      if (!this.selected.shop && this.getTiktokShopList[0].length) {
        this.selected.shop = this.getTiktokShopList[0]._id;
      }

      if (this.selected.shop) {
        this.onChangeShop(this.selected.shop, false);
      }
    },
  },
  created() {
    this.product = this.getProductShopee;
    this.selected.shop = this.getTiktokShopSelect;
    this.selected.warehouse = this.getTiktokWarehouseSelect;
    this.init();
  },
  computed: {
    ...mapGetters('tiktok', ['getTiktokShopSelect', 'getTiktokShopList', 'getTiktokWarehouseSelect', 'getTiktokWarehouseList']),
    score() {
      return this.getScoreClone(platform);
    },
    dataRendered() {
      return this.product;
    },
    btnDisabled() {
      return !!(this.btnLoading || !this.selected.warehouse || !this.selected.shop || !this.getProductShopeeLoaded);
    },
  },
});
