import { mapActions, mapGetters } from 'vuex';
import { importProduct, handlerUpload, saveUpload } from '@/api/autoshopee/lazada';
import { defineComponent } from '@vue/composition-api';
import { loggerLazada } from '@/plugins/logger';

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

const platform = 'lazada';

export default defineComponent({
  data() {
    return {
      product: null,
      rendered: null,
      selected: {
        shop: '',
      },
      log: {
        color: '',
        text: '',
      },
      btnLoading: false,
    };
  },
  methods: {
    ...mapActions('lazada', ['LazadaSelectShop', 'LazadaGetListShop']),
    downScore() {
      this.UseScoreClone(platform);
    },
    openAddShop() {
      this.openExternalUrl(`${this.configAppApi.appHost}/lazada/shop/oauth`);
    },
    buyScore() {
      this.openExternalUrl(`${this.configAppApi.appHost}/upgrade`);
    },
    async refactorProduct(weight = 10, all = 10) {
      try {
        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');

        loggerLazada.error({
          msg: 'REFACTOR_PRODUCT_ERROR',
          error,
        });
      }
    },
    async onChangeShop(value) {
      if (value) {
        this.LazadaSelectShop(value);
      }
    },
    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);

        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}/lazada/upload/product/edit/${save._id}`, true);
        } else {
          throw 'ERROR_SAVE';
        }
      } catch (error) {
        loggerLazada.error({
          msg: 'SAVE_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.item_id) {
          this.openExternalUrl(`${this.configAppApi.lazada.seller}/apps/product/publish?productId=${result.data.item_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;
        loggerLazada.error({
          msg: 'HANDLER_ERROR',
          error,
        });
      }

      this.btnLoading = false;
    },
    async init() {
      await this.LazadaGetListShop();

      if (!this.selected.shop && this.getLazadaShopList[0].length) {
        this.selected.shop = this.getLazadaShopList[0]._id;
        this.onChangeShop(this.selected.shop);
      }
    },
  },
  created() {
    this.product = this.getProductShopee;
    this.selected.shop = this.getLazadaShopSelect;
    this.init();
  },
  computed: {
    ...mapGetters('lazada', ['getLazadaShopSelect', 'getLazadaShopList']),
    score() {
      return this.getScoreClone(platform);
    },
    dataRendered() {
      return this.product;
    },
    btnDisabled() {
      return !!(this.btnLoading || !this.selected.shop || !this.getProductShopeeLoaded);
    },
  },
});
