import curry from 'ramda/src/curry'

export function getCacheTime(duration) {
  return new Date().getTime() + duration
}

export const commonAnimation = wx.createAnimation({
  duration: 400,
  timingFunction: 'ease',
})

export const parseScene = scene => {
  const params = {}
  decodeURIComponent(scene)
    .split('&')
    .forEach((item, index) => {
      const itemArr = item.split('=')
      if (itemArr.length === 2) {
        params[itemArr[0]] = itemArr[1]
      } else {
        params[index] = itemArr[0]
      }
    })
  return params
}

// blog ecommerce presentation
export const baseFilterRelationData = curry(
  (baseType, data, relationData = {}) => {
    const filterData = data.filter(item => {
      const type = item.category || baseType
      if (item.type === 'blogPost' || item.type === 'product') {
        if (
          relationData[`${type}ProductIdList`] &&
          relationData[`${type}ProductIdList`].find(
            value => value.toString() === item.value.toString(),
          )
        ) {
          return false
        }
      } else if (item.type === 'category') {
        if (
          relationData[`${type}CategoryIdList`] &&
          relationData[`${type}CategoryIdList`].find(
            value => value.toString() === item.value.id.toString(),
          )
        ) {
          return false
        }
      }
      return true
    })
    return filterData
  },
)

// hexToRgba('#fff', 0.1) => rgba(255, 255, 255, 0.1)
export const hexToRgba = function(hex, alpha = 1) {
  let c
  if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)) {
    c = hex.substring(1).split('')
    if (c.length === 3) {
      c = [c[0], c[0], c[1], c[1], c[2], c[2]]
    }
    c = `0x${c.join('')}`
    return `rgba(${(c >> 16) & 255}, ${(c >> 8) & 255}, ${c & 255}, ${alpha})`
  }
  return c
}

// 1600 => 1.6k
export const KFormatter = num =>
  num > 999 ? `${(num / 1000).toFixed(1)}k` : num
