/**
 * Created by PanJiaChen on 16/11/18.
 */

import reagentRouter from '@/router/modules/reagent'
import userRouter from '@/router/modules/user'

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

// 防抖
export function debounce(fn, time) {
  time = time || 200
  // 定时器
  let timer = null
  return function(...args) {
    var _this = this
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(function() {
      timer = null
      fn.apply(_this, args)
    }, time)
  }
}

// 节流
export function throttle(fn, time) {
  let timer = null
  time = time || 1000
  return function(...args) {
    if (timer) {
      return
    }
    const _this = this
    timer = setTimeout(() => {
      timer = null
    }, time)
    fn.apply(_this, args)
  }
}

export function filterAsyncRoutes(routers, roles) {
  return routers.filter(item => {
    if (item.meta && item.meta.title === '返回主页') {
      return true
    }
    return !!roles.find(it => it.module_code === item.meta.module_code)
  })
}

export function getALLRouter(data) {
  // TODO: 其他路由都在此操作
  const rasr = filterAsyncRoutes(reagentRouter, data.drug_manage)
  const uasr = filterAsyncRoutes(userRouter, data.drug_manage)
  const asyncRoutes = [
    ...rasr,
    ...uasr,
    // 404 page must be placed at the end !!!
    { path: '*', redirect: '/404', hidden: true }
  ]
  const option = [
    {
      name: 'reagent',
      router: rasr[0],
      title: '试剂管理'
    },
    {
      name: 'user',
      router: uasr[0],
      title: '用户管理'
    }
  ]
  return { asyncRoutes, option }
}

export let userMedia = function(constraints, success, error) {
  if (navigator.mediaDevices.getUserMedia) {
    userMedia = function(constraints, success, error) {
      navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error)
    }
  } else if (navigator.webkitGetUserMedia) {
    userMedia = function(constraints, success, error) {
      navigator.webkitGetUserMedia(constraints, success, error)
    }
  } else if (navigator.mozGetUserMedia) {
    userMedia = function(constraints, success, error) {
      navigator.mozGetUserMedia(constraints, success, error)
    }
  } else if (navigator.getUserMedia) {
    userMedia = function(constraints, success, error) {
      navigator.getUserMedia(constraints, success, error)
    }
  }

  userMedia(constraints, success, error)
}

export const web_stream = {
  get: function(url, callback) {
    let webClient

    if (url.startsWith('http://')) {
      webClient = require('http')
    } else if (url.startsWith('https://')) {
      webClient = require('https')
    } else {
      // eslint-disable-next-line no-throw-literal
      throw 'Unsupported protocol.'
    }

    const clientRequest = webClient.get(url, function(response) {
      response.on('data', function(chunk) {
        // let data = chunk.toString().split(/\r\n/);
        callback(chunk)
      })
    })

    return {
      url: url,
      handler: clientRequest,
      on: function(type, listener) {
        clientRequest.on(type, listener)
      },
      destroy: function() {
        clientRequest.destroy()
      }
    }
  }
}

