import Vue from 'vue'
import store from '../store'
import { getQueryString } from '@/utils/getQueryString'
import { platform } from '@/utils/platform'

/**
 * 清除登录信息
 */
export function clearLoginInfo () {
  Vue.cookie.delete('phone')
  Vue.cookie.delete('token')

  store.commit('common/UPDATE_PHONE', '')
  store.commit('common/UPDATE_TOKEN', '')
}

export function clearStore () {
  store.commit('resetStore')
}

export function fen2Yuan (num) {
  return isNaN(num) ? '' : (num * 0.01).toFixed(2)
}

export function yuan2Fen (num) {
  if (isNaN(num)) {
    return ''
  }
  const amount = num.toString()
  const index = amount.indexOf('.')
  const arr = amount.split('.')
  let result = arr[0] * 100
  if (index > -1) {
    result += arr[1].split('').reduce((total, cur, index) => {
      if (index === 0) {
        return total + cur * 10
      } else {
        return total + cur * 1
      }
    }, 0)
  }
  return result
}

export function getCookieValue (name) {
  return Object.prototype.toString.call(Vue.cookie.get(name)) === '[object Null]' ? '' : Vue.cookie.get(name)
}

/**
 * 获取wechatToken，只有在微信内才有这个参数
 */
export function updateWechatToken () {
  const wechatToken = getQueryString('wechatToken') || ''
  if (wechatToken && platform.isWeixin) {
    Vue.cookie.set('afhousewechatToken', wechatToken)
  }
}

/**
 * 数组展平
 * @param arr 原始数组
 * @returns {[]}
 */
export function formatArray (arr) {
  let result = []
  let i = 0

  if (Array.isArray(arr)) {
    while (i < arr.length) {
      if (Array.isArray(arr[i])) {
        result = result.concat(formatArray(arr[i]))
      } else {
        result.push(arr[i])
      }
      i++
    }
  }

  return result
}
