import { formatProtocol } from 'root/utils/helpers/ecommerceHelper'
import moment from 'wechat_common/lib/moment'
import compose from 'ramda/src/compose'

export function getQnUrl(image) {
  if (image.url && image.url !== '!') {
    return image.url
  }
  return `https://user-assets.sxlcdn.com/${image.storageKey}`
}

export function formattedPrice(price) {
  if (price > 0) {
    return Number(price / 100).toFixed(2)
  } else {
    return 0
  }
}

export function getAmount(cart) {
  let result = 0
  for (const id in cart) {
    result += cart[id].quantity * cart[id].price
  }
  return formattedPrice(result)
}

export function getQuantity(cart) {
  let result = 0
  for (const id in cart) {
    result += cart[id].quantity
  }
  return result
}

export function getOrderItems(cart) {
  const result = []
  for (const id in cart) {
    result.push({
      id,
      quantity: cart[id].quantity,
    })
  }
  return result
}

export function formatPack(target) {
  function addPacketName(packet) {
    const { cards } = packet
    const quantity = cards.length
    if (quantity === 1) {
      packet.name = `${cards[0].title}`
    } else if (quantity > 1) {
      packet.name = `${cards[0].title}等多份`
    } else {
      packet.name = ''
    }
    return packet
  }

  function fotmatPacketBackground(packet) {
    packet.background = formatProtocol(getQnUrl(packet.background))
    return packet
  }

  function _formatTime(time) {
    return moment(time).format('YYYY年MM月DD日 HH:mm')
  }

  function formatPacketTime(packet) {
    packet.created = _formatTime(packet.created)
    packet.updated = _formatTime(packet.updated)
    return packet
  }

  function formattedPackPrice(packet) {
    packet.price = formattedPrice(packet.price)
    return packet
  }

  return compose(
    addPacketName,
    fotmatPacketBackground,
    formatPacketTime,
    formattedPackPrice,
  )(target)
}

export function getCardList(packet) {
  const { cards } = packet
  return cards.map(card => {
    const newCard = {
      cardId: card.cardId,
    }
    return newCard
  })
}
