import moment from 'moment';
import { defineComponent } from '@vue/composition-api';
import { Message } from 'view-design';
import lodash from 'lodash';
import asyncRetry from 'async-retry';
import Promise from 'bluebird';
import { mapActions, mapGetters } from 'vuex';
import PromiseMap from 'p-map';
import { renderCloneProduct, syncVideoProduct, overrideDescriptionJson } from '@/adapter/shopee/product';
import * as shopeeRender from '@/adapter/shopee/render/index';
import { shopeeSetting } from '@/plugins/setting';
import {
  getShopeeSellerProductId, getShopeeAttributeCategoryId, shopeeSellerUpdateProductId, shopeeSellerCreateProduct, shopeeSellerSearchProductList,
} from '@/api/shopee/seller/product';
import { uploadImageBas64 } from '@/api/shopee/image';
import { downloadVideoShopee } from '@/api/autoshopee/public';
import { gptWriterProductDescription, gptWriterProductTitle } from '@/api/gpt';
import { saveAs, zipFileBase64, getBase64Url } from '@/lib/utils/save';
import { useUsageStore } from '@/vue/pinia/usage';
import { UsageShopee } from '@/models/usage';
import { configShopee, getShopeePayloadClone } from '@/config/shopee';
import { useLocalStorage, useSessionStorage } from '@vueuse/core';
import { STORAGE_KEYS } from '@/constant/storage';
import {
  changeImageMd5, watermarkImageFrame, extractBas64Image, appendBase64Image,
} from '@/vue/plugins/image';
import { loggerShopee } from '@/plugins/logger';

const configShopeeProduct = configShopee.product;
const usageStore = useUsageStore();

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

const productCloneRetry = {
  retries: 3,
  maxTimeout: 30 * 1000,
  factor: 1,
};

export default defineComponent({
  props: {
    productId: {
      type: String || Number,
      require: true,
    },
    shopId: {
      type: String || Number,
      require: true,
    },
  },
  data() {
    /** @type {ProductCloneEditPayload} */
    const editData = {
      ...getShopeePayloadClone(),
      ...useLocalStorage(STORAGE_KEYS.LOCAL_STORAGE.SHOPEE_PRODUCT_CLONE_EDIT_DATA, getShopeePayloadClone()),
    };

    const logClone = {
      color: colorStatus.text,
      text: '',
      detail: {},
    };

    const shopWarehouse = useSessionStorage(STORAGE_KEYS.SESSION_STORAGE.SHOPEE_PRODUCT_CLONE_SHOP_WAREHOUSE, {
      selected: shopeeSetting.shopeeShopWarehouse.get(),
      options: [],
    });

    const syncVideoProduct = {
      query: '',
      isSelected: false,
      productSelected: {},
      listProduct: [],
      loading: false,
    };

    /** @type {ShopeeProductData} */
    const shopeeProduct = {
      sku: '',
      name: '',
      description: '',
    };

    return {
      log: logClone,
      shopeeProduct,
      productHasVideo: false,
      editData,
      shopWarehouse,
      syncVideoProduct,
      btnDisable: false,
      btnLoading: false,
      loadingImage: false,
      loadingVideo: false,
      loadingPostVideo: false,
    };
  },
  methods: {
    ...mapActions(['ShopeeSetClonePayload', 'ShopeeSellerConfig', 'ShopeeSellerLogisticSet', 'ShopeeSellerWarehouseSet', 'SetWartermarkProductActive', 'SetWartermarkProductBase64', 'ShopeeGetProduct', 'ShopeeProductFetchStock']),
    onChangeWartermark(status) {
      this.SetWartermarkProductActive(status);
      this.editData.image.watermark = status;
    },
    openSellerLogin() {
      this.openExternalUrl(shopeeRender.sellerLoginUrl, false);
    },
    async openSpyProduct() {
      this.openPopupUrl('/shopee/spy/product', {
        productId: this.shopeeProduct.item_id,
        shopId: this.shopeeProduct.shop_id,
      });
    },
    async openFetchReview() {
      this.openPopupUrl('/shopee/product/review/get', {
        productId: this.shopeeProduct.item_id,
        shopId: this.shopeeProduct.shop_id,
      });
    },
    onChangeFetchStock(value) {
      if (value) {
        this.fetchStockHandler();
      }
    },
    async openViewImage() {
      if (!usageStore.getUsageShopeeDownloadImage.allow) {
        return this.$Message.error({
          content: usageStore.getUsageShopeeDownloadImage.errorMsg,
          top: 450,
          duration: 2,
        });
      }

      const listAllImage = this.getListImageUrl();
      this.openPopupUrl('/shopee/product/image/view', {
        source: JSON.stringify(listAllImage),
      });

      usageStore.incShopeeDownloadImage();
    },
    getListImageUrl() {
      return shopeeRender.renderProductDetail(this.shopeeProduct).listImage;
    },
    getListVideo() {
      return lodash.get(this.shopeeProduct, 'video_info_list', []);
    },
    renderProduct() {
      if (!(this.shopeeProduct && this.shopeeProduct.itemid)) {
        return null;
      }

      this.shopeeProduct.sku = this.shopeeProduct.itemid.toString();
      this.productHasVideo = lodash.has(this.shopeeProduct, 'video_info_list[0].video_id');
    },
    async searchProduct(query) {
      this.syncVideoProduct.loading = true;
      try {
        const searchType = isNaN(query) ? 'name' : 'id';
        const { listProduct } = await shopeeSellerSearchProductList(query, 1, 10, searchType);
        this.syncVideoProduct.listProduct = listProduct;
      } catch (error) {}
      this.syncVideoProduct.loading = false;
    },
    onChangeProduct(productId) {
      const selectedProduct = this.syncVideoProduct.listProduct
        .find(({ id }) => id.toString() === productId.toString());

      if (selectedProduct) {
        this.syncVideoProduct.productSelected = selectedProduct;
        this.syncVideoProduct.isSelected = true;
        this.syncVideoProduct.query = `[${selectedProduct.id}] ${selectedProduct.name}`;
      }
    },
    onChangeWarehouse(value) {
      shopeeSetting.shopeeShopWarehouse.set(value);
      this.ShopeeSellerWarehouseSet(value);
    },
    onChangeLogistic(value) {
      this.ShopeeSellerLogisticSet(value);
    },
    async getBase64ListImage() {
      const listImage = this.getListImageUrl();

      const listBase64 = await Promise.mapSeries(listImage, async (item) => {
        const base64 = await getBase64Url(item.url);

        return {
          ...item,
          base64,
        };
      });

      return listBase64;
    },
    async renderImageUrl(url, index, total) {
      const getProductWartermark = this.getProductWartermark;

      try {
        if (getProductWartermark.active && getProductWartermark.base64) {
          Message.success(this.$t('IMAGE_PROCESSING_WARTERMARK', { url, index, total }));

          const base64Frame = getProductWartermark.base64;

          const base64Result = await watermarkImageFrame(url, appendBase64Image(base64Frame), getProductWartermark.size);

          if (!base64Result) {
            throw 'WARTERMARK_ERROR';
          }

          const imageId = await uploadImageBas64(
            extractBas64Image(base64Result),
          );
          return imageId;
        } if (this.editData.image.changeMd5) {
          Message.success(this.$t('IMAGE_PROCESSING_MD5', { url, index, total }));

          const imageBase64 = await changeImageMd5(url);
          const imageId = await uploadImageBas64(
            extractBas64Image(imageBase64),
          );

          return imageId;
        }
      } catch (error) {
        loggerShopee.error({
          msg: 'ERROR_RENDER_IMAGE_URL',
          url,
          error,
        });

        return url;
      }
      return url;
    },
    async downLoadAllImageZip() {
      if (!usageStore.getUsageShopeeDownloadImage.allow) {
        return this.$Message.error({
          content: usageStore.getUsageShopeeDownloadImage.errorMsg,
          top: 450,
          duration: 2,
        });
      }
      this.btnDisable = true;
      this.loadingImage = true;

      try {
        const saveName = `${lodash.snakeCase(this.shopeeProduct.name)}.zip`;

        const listFileBase64 = await this.getBase64ListImage();

        await zipFileBase64(listFileBase64, saveName);
        usageStore.incShopeeDownloadImage();
      } catch (error) {}

      this.btnDisable = false;
      this.loadingImage = false;

      this.$Message.success(this.$t('DOWNLOAD_IMAGE_PRODUCT_SUCCESS'));
    },
    async downloadAllVideo() {
      if (!usageStore.getUsageShopeeDownloadVideo.allow) {
        return this.$Message.error({
          content: usageStore.getUsageShopeeDownloadVideo.errorMsg,
          top: 450,
          duration: 2,
        });
      }

      this.btnDisable = true;
      this.loadingVideo = true;
      this.log.text = this.$t('DOWNLOAD_VIDEO_PRODUCT_PROCESSING');
      this.log.color = colorStatus.pending;

      if (this.getListVideo().length) {
        const listVideo = this.getListVideo();
        await Promise.mapSeries(listVideo, async (videoData, indexVideo) => {
          try {
            const { video_id: videoId, version: videoVersion } = videoData;

            if (videoVersion && videoVersion >= 1) {
              this.log.text = this.$t('DOWNLOAD_VIDEO_PRODUCT_PROCESSED');

              try {
                const videoName = `${this.shopeeProduct.name}_${indexVideo + 1}.mp4`;

                if (videoData.formats && videoData.formats[0] && videoData.formats[0].url) {
                  await saveAs(videoData.formats[0].url, videoName);
                } else if (videoData.default_format && videoData.default_format.url) {
                  await saveAs(videoData.default_format.url, videoName);
                } else {
                  await saveAs(shopeeRender.videoUrl(videoId), videoName);
                }
              } catch (error) {
                this.openExternalUrl(shopeeRender.videoUrl(videoId));
              }

              this.log.color = colorStatus.success;
            } else {
              const downloadVideo = await downloadVideoShopee(videoId);
              if (downloadVideo.success && downloadVideo.data) {
                this.log.text = this.$t('DOWNLOAD_VIDEO_PRODUCT_PROCESSED');
                this.log.color = colorStatus.success;

                this.openExternalUrl(downloadVideo.data);
              } else {
                this.log.text = this.$t('DOWNLOAD_VIDEO_PRODUCT_ERROR');
                this.log.color = colorStatus.error;
              }
            }
          } catch (error) {
            this.log.text = this.$t('DOWNLOAD_VIDEO_PRODUCT_ERROR');
            this.log.color = colorStatus.error;
          }
        });

        usageStore.incShopeeDownloadVideo();
      } else if (this.shopeeProduct.video) {
        const videoName = `${this.shopeeProduct.name}.mp4`;
        await saveAs(this.shopeeProduct.video, videoName);

        usageStore.incShopeeDownloadVideo();
      }

      this.btnDisable = false;
      this.loadingVideo = false;

      this.$Message.success(this.$t('DOWNLOAD_VIDEO_PRODUCT_SUCCESS'));
    },
    resolveShopeeVideoUrl() {
      const listVideo = this.getListVideo();

      if (listVideo.length) {
        const videoData = listVideo[0];

        if (videoData.formats && videoData.formats[0] && videoData.formats[0].url) {
          return videoData.formats[0].url;
        }

        if (videoData.default_format && videoData.default_format.url) {
          return videoData.default_format.url;
        }

        if (videoData.video_id) {
          return shopeeRender.videoUrl(videoData.video_id);
        }
      }

      if (this.shopeeProduct.video) {
        return this.shopeeProduct.video;
      }

      return '';
    },
    postShopeeVideoToChannel() {
      const videoUrl = this.resolveShopeeVideoUrl();

      if (!videoUrl) {
        this.$Message.error(this.$t('SHOPEE_VIDEO_POST_NO_DATA'));
        return;
      }

      this.openPopupUrl('/shopee/video/compose', {
        source: 'shopee',
        videoUrl,
        title: this.shopeeProduct.name || '',
      });
    },
    async fetchStockHandler() {
      if (!this.editData.fetchStock) {
        return null;
      }

      const payloadQuery = {
        productId: this.productId,
        shopId: this.shopId,
      };

      let intervalFetch = null;
      await this.ShopeeProductFetchStock(payloadQuery);

      intervalFetch = setInterval(async () => {
        await this.ShopeeGetProduct(payloadQuery);
        const listModel = this.getProductShopee.models;
        this.shopeeProduct.models = listModel;

        if (!listModel.some((model) => !model.fetched_stock)) {
          clearInterval(intervalFetch);
        }
      }, 1000);
    },
    async copyProduct() {
      if (!usageStore.getUsageShopeeCloneProduct.allow) {
        return this.$Message.error({
          content: usageStore.getUsageShopeeCloneProduct.errorMsg,
          top: 450,
          duration: 2,
        });
      }

      /** @type {ProductCloneEditPayload} */
      const productCloneOption = this.editData;

      let isActive = true;
      this.btnDisable = true;
      this.log.color = colorStatus.pending;
      this.log.text = this.$t('PRODUCT_COPYING');

      if (productCloneOption.skipDuplicateSku) {
        try {
          const searchSku = this.shopeeProduct.sku;
          const { listProduct } = await shopeeSellerSearchProductList(searchSku, 1, 20, 'sku');

          if (listProduct && listProduct.length) {
            this.log.text = this.$t('PRODUCT_CREATE_ERROR_WAS_DUPLICATE');
            this.log.color = colorStatus.error;
            isActive = false;
          }
        } catch (error) {
          this.log.text = this.$t('SHOPEE_NO_LOGIN');
          this.log.color = colorStatus.error;
          isActive = false;
        }
      }

      if (!isActive) {
        this.btnDisable = false;

        return false;
      }

      productCloneOption.logisticsChannels = this.getShopeeSellerLogistic.selected.map((item) => Number(item));

      if (!productCloneOption.logisticsChannels.length) {
        this.log.text = this.$t('SHOP_LOGISTIC_NOT_ENABLE');
        this.log.color = colorStatus.error;

        this.btnDisable = false;

        return false;
      }

      await this.fetchStockHandler().catch((error) => {
        loggerShopee.error({
          msg: 'SHOPEE_PRODUCT_FETCH_STOCK_ERROR',
          error,
        });
      });

      /** @type {ShopeePayloadProductCreate} */
      let payloadProduct = null;

      try {
        const listAttribute = (await getShopeeAttributeCategoryId(this.shopeeProduct.categories[this.shopeeProduct.categories.length - 1].catid)) || [];

        const listWarehouseId = this.shopWarehouse.selected.filter((warehouseId) => this.shopWarehouse.options.find((item) => item.value === warehouseId));

        payloadProduct = renderCloneProduct(this.shopeeProduct, listAttribute, productCloneOption, listWarehouseId);

        let totalImage = payloadProduct.images.length + (payloadProduct.long_images?.length || 0);
        let indexPage = 1;

        payloadProduct.images = await PromiseMap(
          payloadProduct.images,
          async (url) => {
            indexPage++;
            url = await this.renderImageUrl(url, indexPage, totalImage);
            const id = shopeeRender.imageId(url);

            return id;
          },
          {
            concurrency: 4,
          },
        );

        if (payloadProduct.long_images && payloadProduct.long_images.length) {
          payloadProduct.long_images = await PromiseMap(
            payloadProduct.long_images,
            async (url) => {
              indexPage++;
              url = await this.renderImageUrl(url, indexPage, totalImage);
              const id = shopeeRender.imageId(url);

              return id;
            },
            {
              concurrency: 4,
            },
          );
        }

        if (payloadProduct.tier_variation && payloadProduct.tier_variation.length) {
          payloadProduct.tier_variation = await Promise.mapSeries(payloadProduct.tier_variation, async (model) => {
            const result = {
              ...model,
              images: model.images && model.images.length ? model.images.map((img) => shopeeRender.imageId(img)) : model.images || [],
            };

            totalImage += result.images.length;
            result.images = await PromiseMap(
              result.images,
              async (id) => {
                let url = shopeeRender.imageUrl(id);
                indexPage++;
                url = await this.renderImageUrl(url, indexPage, totalImage);

                const imageId = shopeeRender.imageId(url);

                return imageId;
              },
              {
                concurrency: 4,
              },
            );

            return result;
          });
        }

        if (productCloneOption.title.gptWriter) {
          this.log.text = this.$t('PRODUCT_CLONE_LOG_GPT_WRITER_TITLE');
          payloadProduct.name = await gptWriterProductTitle(payloadProduct.name);
        }

        if (productCloneOption.description.gptWriter) {
          this.log.text = this.$t('PRODUCT_CLONE_LOG_GPT_WRITER_DESCRIPTION');
          payloadProduct.description = await gptWriterProductDescription(payloadProduct.description);

          if (productCloneOption.description.json && payloadProduct.description_json && payloadProduct.description_json.length) {
            payloadProduct.description_json = overrideDescriptionJson(payloadProduct.description_json, payloadProduct.description);
          }
        }

        const payloadOverride = {
          attributeFormatUnixTime: false,
          attributeRemoveCustom: false,
        };

        const cloneResult = await asyncRetry(async (stopClone) => {
          const createResult = await shopeeSellerCreateProduct(payloadProduct);

          const msgError = lodash.get(createResult, 'user_message', '').toLowerCase();

          loggerShopee.info({
            msg: 'COPY_PRODUCT_DONE',
            result: createResult,
            payload: payloadProduct,
            msgError,
          });

          if (lodash.has(createResult, 'data.product_id')) {
            return createResult;
          }

          if (msgError.includes('listing limit')) {
            return createResult;
          }

          const matchImgInvalid = 'image is invalid: ';

          if (msgError.includes(matchImgInvalid)) {
            const listImageIdError = msgError.replace(matchImgInvalid, '').trim().split(',');
            payloadProduct.images = payloadProduct.images.filter((imageCurrent) => !listImageIdError.find((imgError) => imageCurrent.includes(imgError)));
          } else if (msgError.includes('image for product description')) {
            payloadProduct.description_json = null;
          } else if (msgError.includes('brand')) {
            payloadProduct.brand_id = 0;
          } else if (msgError.includes('product is duplicated')) {
            payloadProduct.name += '0';
          } else if (msgError.includes('hỏa tốc')) {
            payloadProduct.logistics_channels = payloadProduct.logistics_channels.filter(({ channelid }) => channelid !== 5000);
          } else if (msgError.includes('size chart')) {
            const sizeChartUrl = productCloneOption.sizeChart || configShopeeProduct.sizeChartDefault;
            const sizeChartId = shopeeRender.imageId(sizeChartUrl);

            payloadProduct.size_chart_info = {
              size_chart_id: 0,
              size_chart: sizeChartId,
            };
          } else if (msgError.includes('condition')) {
            payloadProduct.condition = 1;
          } else if (msgError.includes('create product')) {
            if (payloadProduct.video_list) {
              payloadProduct.video_list = [];
            } else if (payloadProduct.attributes.length) {
              payloadProduct.attributes = [];
            }
          } else if (msgError.includes('product weight or dimesion out of channel required range')) {
            const channelId = 5004;

            payloadProduct.logistics_channels = [{
              price: '0',
              cover_shipping_fee: false,
              enabled: true,
              item_flag: '0',
              channelid: channelId,
              sizeid: 0,
              size: 0,
            }];
          } else if (msgError.includes('your attribute info is invalid')) {
            if (!payloadOverride.attributeFormatUnixTime) {
              const convertDateToUnix = (dateString) => moment(dateString, 'DD-MM-YYYY').unix().toString();
              const createValueObject = (unixValue) => ({ raw_value: unixValue, unit: '' });

              payloadProduct.attributes = payloadProduct.attributes.map((attribute) => {
                const rawValueList = lodash.get(attribute, 'attribute_values.0.raw_value', '');
                const rawValueCustom = lodash.get(attribute, 'custom_value.raw_value', '');

                if (rawValueList && moment(rawValueList, 'DD-MM-YYYY', true).isValid()) {
                  const unixValue = convertDateToUnix(rawValueList);
                  attribute.attribute_values = [createValueObject(unixValue)];
                } else if (rawValueCustom && moment(rawValueCustom, 'DD-MM-YYYY', true).isValid()) {
                  const unixValue = convertDateToUnix(rawValueCustom);
                  attribute.custom_value = createValueObject(unixValue);
                } else if (attribute.attribute_name === 'Expiry Date' || attribute.attribute_id === 100061) {
                  const expiredDays = Number(lodash.get(productCloneOption, 'expiredDay', 0)) || 365;
                  const futureUnix = moment().add(expiredDays, 'day').unix().toString();
                  attribute.custom_value = createValueObject(futureUnix);
                }

                return attribute;
              });

              payloadOverride.attributeFormatUnixTime = true;
            } else if (!payloadOverride.attributeRemoveCustom) {
              payloadProduct.attributes = payloadProduct.attributes.filter((attribute) => attribute.mandatory || attribute.attribute_value_id);
              payloadOverride.attributeRemoveCustom = true;
            }
          } else if (msgError.includes('mandatory_direct')) {
            throw {
              user_message: msgError,
            };
          } else {
            stopClone(createResult);
          }

          throw {
            user_message: msgError,
          };
        }, productCloneRetry);

        if (lodash.has(cloneResult, 'data.product_id')) {
          const productId = cloneResult.data.product_id;

          const payloadUsage = {
            type: 'productClone',
            shopId: this.getShopeeShopId,
            payload: {
              from: 'shopee',
              name: this.shopeeProduct.name,
              productId: this.shopeeProduct.item_id,
              shopId: this.shopeeProduct.shop_id,
            },
            result: {
              name: payloadProduct.name,
              productId,
              shopId: this.getShopeeShopId,
            },
          };

          UsageShopee.insert(payloadUsage).catch(() => {});

          usageStore.incShopeeCloneProduct();

          this.openExternalUrl(shopeeRender.productSeller(productId), false);

          this.btnDisable = false;
          this.log.text = this.$t('PRODUCT_CREATE_SUCCESS');
          this.log.color = colorStatus.success;

          return productId;
        }

        const errorCode = cloneResult.code.toString();
        const errorMsg = lodash.get(cloneResult, 'user_message', '').toLowerCase();

        const mapErrorCode = {
          100011445: this.$t('SHOP_IS_OFF_STATUS'),
          100010006: this.$t('SHOP_REACH_MAX_PRODUCT'),
          100021445: this.$t('SHOP_MISSING_LOGISTIC'),
          100010239: this.$t('PRODUCT_INVALID_LOGISTIC'),
          100010243: this.$t('COPY_PRODUCT_TOO_FAST'),
          100010242: this.$t('PRODUCT_CREATE_ERROR_WAS_DUPLICATE'),
        };

        const isDuplicated = errorMsg.includes('product is duplicated') || errorMsg.includes('duplicate with another product') || errorMsg.includes('The product is duplicated with another');

        if (isDuplicated) {
          this.log.text = this.$t('PRODUCT_CREATE_ERROR_WAS_DUPLICATE');
          this.log.color = colorStatus.error;
        } else if (Object.keys(mapErrorCode).includes(errorCode)) {
          this.log.text = this.$t(mapErrorCode[errorCode]);
          this.log.color = colorStatus.error;
        } else {
          this.log.text = errorMsg;
          this.log.color = colorStatus.error;
        }
      } catch (error) {
        loggerShopee.error({
          msg: 'COPY_PRODUCT_ERROR',
          result: error,
          payload: payloadProduct,
        });

        this.log.text = error.user_message || error.message || this.$t('COPY_PRODUCT_ERROR');
        this.log.color = colorStatus.error;
      }

      this.btnDisable = false;
    },
    async syncVideoToProductId() {
      if (!this.syncVideoProduct.isSelected) {
        this.log.text = this.$t('PLESE_SELECT_PRODUCT_TO_SYNC_PRODUCT');
        this.log.color = colorStatus.error;
        return false;
      }

      this.btnDisable = true;
      this.log.text = this.$t('SYNC_VIDEO_PRODUCT_PROCESSING');
      this.log.color = colorStatus.pending;

      const productId = this.syncVideoProduct.productSelected.id;
      try {
        const getProduct = await getShopeeSellerProductId(productId);
        const payloadUpdate = syncVideoProduct(getProduct, this.getListVideo());

        const payloadRetry = {
          retries: 2,
          factor: 0,
        };

        const updateResult = await asyncRetry(async () => {
          const resultUpdate = await shopeeSellerUpdateProductId(productId, payloadUpdate);

          const msgError = lodash.get(resultUpdate, 'user_message', '').toLowerCase();

          if (msgError.includes('size chart')) {
            const sizeChartUrl = configShopeeProduct.sizeChartDefault;
            const sizeChartId = shopeeRender.imageId(sizeChartUrl);

            payloadUpdate.size_chart_info = {
              size_chart_id: 0,
              size_chart: sizeChartId,
            };
            throw 'RETRY_UPDATE';
          }

          return resultUpdate;
        }, payloadRetry);

        const resultMsg = lodash.get(updateResult, 'user_message', '').toLowerCase();

        if (resultMsg !== 'success') {
          throw resultMsg || 'SYNC_VIDEO_PRODUCT_ERROR';
        }

        this.log.text = this.$t('SYNC_VIDEO_PRODUCT_SUCCESS');
        this.log.color = colorStatus.success;

        this.openExternalUrl(shopeeRender.productSeller(productId), false);
      } catch (error) {
        loggerShopee.error({
          msg: 'SYNC_VIDEO_PRODUCT_ERROR',
          error,
        });
        this.log.text = this.$t('SYNC_VIDEO_PRODUCT_ERROR');
        this.log.color = colorStatus.error;
      }
      this.btnDisable = false;
    },
  },
  async created() {
    this.shopeeProduct = this.getProductShopee;

    this.editData = {
      ...this.editData,
      ...this.getShopeeClonePayload,
    };

    this.renderProduct();
    this.ShopeeSellerConfig();

    setInterval(usageStore.fetchUsage, 1000);

    setTimeout(() => {
      if (!this.getUsageGptWriter.allow) {
        this.editData.title.gptWriter = false;
        this.editData.description.gptWriter = false;
      }
    }, 1000);

    UsageShopee.syncRemote();

    this.fetchStockHandler().catch((error) => {
      loggerShopee.error({
        msg: 'SHOPEE_PRODUCT_FETCH_STOCK_ERROR',
        error,
      });
    });
  },
  watch: {
    editData: {
      deep: true,
      handler(data) {
        this.ShopeeSetClonePayload(data);
      },
    },
    getShopeeSellerWarehouse: {
      deep: true,
      handler(getWarehouse) {
        if (!getWarehouse.list.length) {
          return [];
        }

        this.shopWarehouse.options = getWarehouse.list;

        if (!this.shopWarehouse.selected.length) {
          this.shopWarehouse.selected = getWarehouse.selected;
          shopeeSetting.shopeeShopWarehouse.set(getWarehouse.selected);
        }

        return this.shopWarehouse.selected;
      },
    },
  },
  computed: {
    ...mapGetters(['getShopeeClonePayload', 'getShopeeSellerLogistic', 'getProductWartermark', 'getShopeeSellerWarehouse']),
    warningCloneText() {
      return usageStore.getUsageShopeeCloneProduct.allow ? '' : usageStore.getUsageShopeeCloneProduct.errorMsg;
    },
    btnDisabled() {
      return !!(this.btnDisable || !this.getShopeeSellerAuthed || !this.getProductShopeeLoaded);
    },
    isShopWarehouse() {
      return this.shopWarehouse.options.length || this.shopWarehouse.selected.length;
    },
    productStockStats() {
      if (!(this.getProductShopee && this.getProductShopee.models && this.getProductShopee.models.length)) {
        return [
          0,
          0,
        ].join('/');
      }

      const listModelAll = this.getProductShopee.models;
      const listModelFetched = listModelAll.filter((model) => model.fetched_stock);

      return [
        listModelFetched.length,
        listModelAll.length,
      ].join('/');
    },
  },
});
