import moment from 'wechat_common/lib/moment'
import { getQnUrl } from 'wechat_common/utils/helpers/imageHelper'

export function reducerHelper(state, action, handlers) {
  const handler = handlers[action.type]
  return handler ? handler(state, action) : state
}

export function formatFactory(method, key = 'url') {
  let assertError = ''
  if (typeof method !== 'function') {
    assertError = new TypeError(
      `method pass into formatFactory must be a function, but get ${typeof method}`,
    )
  }
  return function(obj) {
    if (assertError) {
      throw assertError
    }

    return Object.assign({}, obj, {
      [key]: method(obj[key]),
    })
  }
}

export function formatProtocol(url) {
  const _url = url.replace('http:', '').replace('https:', '')
  return `https:${_url}`
}
// 判断十六进制色值是浅色还是深色 return true: 浅色，false：深色
const isLightFunc = hexColor => {
  const color = hexColor.toLowerCase()
  const sColorChange = []
  for (let i = 1; i < 7; i += 2) {
    sColorChange.push(parseInt(`0x${color.slice(i, i + 2)}`, 0))
  }
  if (
    sColorChange[0] * 0.299 +
      sColorChange[1] * 0.578 +
      sColorChange[2] * 0.114 >=
    192
  ) {
    return true
  } else {
    return false
  }
}
export function isWhite(color) {
  if (
    !color ||
    color === '' ||
    color === '#fff' ||
    color === '#ffffff' ||
    color === 'white'
  ) {
    return true
  } else if (color === 'black') {
    return false
  }
  return isLightFunc(color)
}

export function getDateDiff(dateTimeStamp) {
  const monthCount = moment().diff(dateTimeStamp, 'months')
  const weekCount = moment().diff(dateTimeStamp, 'weeks')
  const dayCount = moment().diff(dateTimeStamp, 'days')
  const hourCount = moment().diff(dateTimeStamp, 'hours')
  const minCount = moment().diff(dateTimeStamp, 'minutes')
  let result = ''
  if (monthCount >= 1) {
    result = `${String(parseInt(monthCount, 0))}月前`
  } else if (weekCount >= 1) {
    result = `${String(parseInt(weekCount, 0))}周前`
  } else if (dayCount >= 1) {
    result = `${String(parseInt(dayCount, 0))}天前`
  } else if (hourCount >= 1) {
    result = `${String(parseInt(hourCount, 0))}小时前`
  } else if (minCount >= 1) {
    result = `${String(parseInt(minCount, 0))}分钟前`
  } else {
    result = '刚刚'
  }
  return result
}

export function validatePhoneNumber(phoneNumer) {
  return /^1[34578]\d{9}$/.test(phoneNumer)
}

export function formatAmount(amount) {
  return (Number(amount) / 100).toFixed(2)
}

export function formatGrouponStatus(status) {
  switch (status) {
    case 'refund_pending':
      return { name: '待退款', color: '#fb7d2b', type: 'effective' }
    case 'enabled':
      return { name: '未使用', color: '#93b719', type: 'effective' }
    case 'used':
      return { name: '已核销', color: '#9298a0', type: 'used' }
    case 'refunded':
      return { name: '已退款', color: '#9298a0', type: 'refunded' }
    case 'expired':
      return { name: '已过期', color: '#9298a0', type: 'expired' }
    case 'disabled':
      return { name: '已失效', color: '#e64751', type: 'disabled' }
    default:
      return ''
  }
}

// parse the comment pictures and split comment to show or hide.
export function updateComment(comments) {
  let lessCommentImg = []
  let moreCommentImg = []
  let lessComments = []
  let holdPictures = []
  let newComments = []

  if (comments) {
    comments.forEach(value => {
      if (value.content && value.content.length > 82) {
        value.shortContent = `${value.content.substring(0, 82)}...`
      }
      value.createdAt = moment(value.createdAt)
        .locale('zh-cn')
        .fromNow()

      if (value.pictures && value.pictures.length > 0) {
        value.pictures.map(img => {
          if (img.image) {
            holdPictures.push(img.image)
          } else {
            holdPictures.push(getQnUrl(img))
          }
        })
        value.pictures = holdPictures
        holdPictures = []
      } else {
        value.pictures = []
      }

      if (value.pictures && value.pictures.length > 3) {
        lessCommentImg = value.pictures.slice(0, 2)
        moreCommentImg = value.pictures.slice(2, 3)
      } else if (value.pictures && value.pictures.length <= 3) {
        lessCommentImg = value.pictures
      }

      value.lessCommentImg = lessCommentImg || []
      value.moreCommentImg = moreCommentImg || []
    })
    newComments = [...comments]
    lessComments = newComments.slice(0, 1)
  }
  return {
    comments: newComments,
    lessComments,
  }
}

export function compare(property) {
  return (a, b) => {
    const value1 = a[property]
    const value2 = b[property]
    return value2 - value1
  }
}
export function simpleString(str = '', length = 5) {
  return str.length > length ? `${str.substr(0, length)}...` : str
}

/*
* return the main region of a detailed address
* @param {string} addr detailed address
* @return {string}
*/
export const getRegionFromAddress = addr => {
  const regEx = /^(.+[省|自治区])?(.+[地区|自治州|市])?(.+[县|区])?/
  const rslt = (addr || '').match(regEx)
  return rslt || ['']
}

/*
* get the type of the input value
* @param {string} addr detailed address
* @return {string}
*/
export const getType = param => {
  if (Array.isArray(param)) {
    return 'array'
  }
  if (param instanceof Date) {
    return 'date'
  }
  if (param === null) {
    return 'null'
  }
  if (param instanceof RegExp) {
    return 'regExp'
  }
  if (param instanceof Error) {
    return 'error'
  }
  return typeof param
}

/*
* compare the first input value to another,
*  return a boolean value if they are as same as each other
* @param {Object} a the first object which would be used to compare to another
* @return {Object} b another object
*/
export const isCongruence = (a, b) => {
  const typeFirst = getType(a)
  if (typeFirst !== getType(b)) {
    return false
  }
  const TYPE_METHODS_MAP = {
    array: (x, y) => {
      if (x === y) {
        return true
      }
      if (x.length !== y.length) {
        return false
      }
      const ifEqual = (pre, nex) => {
        const compareFirst = isCongruence(pre[0], nex[0])
        if (pre.length <= 1) {
          return compareFirst
        }
        return compareFirst && TYPE_METHODS_MAP.array(pre.slice(1), nex.slice(1))
      }
      return ifEqual(x, y)
    },
    function: (x, y) => {
      if (x === y) {
        return true
      }
      return String(x) === String(y)
    },
    object: (x, y) => {
      if (x === y) {
        return true
      }
      const xKeys = Object.keys(x)
      const yKeys = Object.keys(y)
      if (xKeys.length !== yKeys.length) {
        return false
      }
      const ifKeysEqual = TYPE_METHODS_MAP.array(xKeys, yKeys)
      const ifEqual = keys => {
        if (keys.length <= 0) {
          return true
        }
        const compareFirst = isCongruence(x[keys[0]], y[keys[0]])
        if (keys.length <= 1) {
          return compareFirst
        }
        return compareFirst && ifEqual(keys.slice(1))
      }
      return ifKeysEqual && ifEqual(xKeys)
    },
    otherwise: (x, y) => x === y,
  }
  return (TYPE_METHODS_MAP[typeFirst] || TYPE_METHODS_MAP.otherwise)(a, b)
}
