import unixTimestamp from 'unix-timestamp';
import lodash from 'lodash';
import numberPrecision from 'number-precision';
import sumBy from 'sum-by';

import { imageUrl } from './utils';

const getPriceDiscountPercent = (price = 0, promotion = 0) => {
  if (!price) {
    return 0;
  }

  if (!promotion) {
    return 0;
  }

  if (price === promotion) {
    return 0;
  }

  const percent = 100 - numberPrecision.round((promotion * 100) / price, 0);
  return percent;
};

/**
 *
 * @param {ShopeeProductData} productData
 */
export const renderProductDetail = (productData) => {
  const metaData = {
    name: productData.name,
    description: productData.description,
    image: productData.image,
    video: productData.video,
    currency: productData.currency,
    timeCreate: unixTimestamp.toDate(productData.ctime).toLocaleString(),
    totalVaritaion: 0,
    totalSale: 0,
    totalSold: 0,
  };

  const shopValue = productData.shop_data || {};

  const shopData = {
    name: shopValue.name,
    image: imageUrl(shopValue.account.portrait),
    username: shopValue.account.username,
    phone: '',
    email: '',
    isMall: shopValue.is_official_shop,
    shopId: shopValue.shopid,
    userId: shopValue.userid,
    location: shopValue.place || shopValue.shop_location,
    totalSold: shopValue.sold_total,
    totalProduct: shopValue.item_count,
    totalFollower: shopValue.follower_count,
    ratingStar: shopValue.rating_star,
    ratingBad: shopValue.rating_bad,
    ratingGood: shopValue.rating_good,
    ratingNormal: shopValue.rating_normal,
    timeCreate: unixTimestamp.toDate(shopValue.ctime).toLocaleString(),
    timeOnline: unixTimestamp.toDate(shopValue.last_active_time).toLocaleString(),
  };

  const listTag = (productData.description.match(/#(\w+)/g) || []).map((item) => item.replace(/\#/g, ''));

  const listVariation = productData.models.map((item) => {
    return {
      id: item.modelid,
      name: item.name,
      image: '',
      price: item.price_before_discount,
      promotion: item.price || 0,
      stock: item.stock,
      discount: getPriceDiscountPercent(item.price_before_discount, item.price),
      sold: item.sold,
      sale: item.sold * item.price,
    };
  });

  const listImage = [
    ...productData.images.map((url, indexImage) => ({
      url,
      fileName: `main-${indexImage + 1}.jpg`,
      type: 'main',
    })),
    ...(productData.long_images || []).map((url, indexImage) => ({
      url,
      fileName: `long-${indexImage + 1}.jpg`,
      type: 'long',
    })),
  ];

  if (productData.rich_text_description && productData.rich_text_description.paragraph_list) {
    productData.rich_text_description.paragraph_list
      .filter((item) => item.img_id)
      .forEach((item, indexImage) => {
        const url = imageUrl(item.img_id);

        listImage.push({
          url,
          fileName: `description-${indexImage + 1}.jpg`,
          type: 'description',
        });
      });
  }

  if (productData.tier_variations) {
    productData.tier_variations.map((tierVariation) => {
      if (tierVariation.images && tierVariation.images.length) {
        listImage.push(
          ...tierVariation.images.map((url, indexImage) => ({
            url,
            fileName: `${lodash.snakeCase(tierVariation.options[indexImage])}.jpg`,
            type: 'variation',
          })),
        );
      }
    });
  }

  metaData.totalSale = sumBy(listVariation, (item) => item.sale);
  metaData.totalSold = sumBy(listVariation, (item) => item.sold);
  metaData.totalVaritaion = listVariation.length;
  return {
    metaData,
    shopData,
    listVariation,
    listImage,
    listTag,
  };
};

export const renderProductSearch = () => {};
