import { Loading } from 'element-ui'
/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    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(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

export function parseTime2(time, format = 'yyyy-MM-dd hh:mm:ss') {
  const date = time instanceof Date ? time : new Date(time)

  const o = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'h+': date.getHours() % 12, // 12小时
    'H+': date.getHours(), // 24小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    'S': date.getMilliseconds(), // 毫秒
    'D': (() => {
      switch (date.getDay()) {
        case 1:
          return '星期一'
        case 2:
          return '星期二'
        case 3:
          return '星期三'
        case 4:
          return '星期四'
        case 5:
          return '星期五'
        case 6:
          return '星期六'
        case 0:
          return '星期日'
        default:
          return String(date.getDay())
      }
    })()
  }
  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (const k in o) {
    if (new RegExp('(' + k + ')').test(format)) {
      format = format.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
  }
  if (/CN/.test(format)) {
    format = format.replace('CN', () => {
      const now = Date.now()
      const diff = (now - date) / 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天前'
      }
    })
  }
  return format
}

/**
 * @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 = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"')
        .replace(/\+/g, ' ') +
      '"}'
  )
}

export function resetObj(obj, defaultValue = {}) {
  for (const key in obj) {
    switch (typeof obj[key]) {
      case 'string': {
        obj[key] = defaultValue[key] || ''
        break
      }
      case 'number': {
        obj[key] = defaultValue[key] || 0
        break
      }
      case 'object': {
        if (Array.isArray(obj[key])) {
          obj[key] = defaultValue[key] || []
        } else {
          resetObj(obj[key], defaultValue[key])
        }
        break
      }
    }
  }
}

export const createGlobalLoading = (function() {
  const handlersMap = {
    default: []
  }
  let loading
  return function(handler, scopeKey = 'default', cusLoading) {
    if (!handlersMap[scopeKey]) {
      handlersMap[scopeKey] = []
    }
    const handlers = handlersMap[scopeKey]
    if (handlers.length === 0) {
      if (cusLoading) {
        if (typeof cusLoading.start === 'function') {
          cusLoading.start()
        }
      } else {
        loading = Loading.service({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
      }
    }
    const id = (new Date()).valueOf()
    handlers.push(id)
    return (async() => { return typeof handler === 'function' ? handler() : handler })().then((result) => {
      return result
    }).finally(() => {
      handlers.splice(handlers.indexOf(id), 1)
      if (handlers.length === 0) {
        if (cusLoading) {
          if (typeof cusLoading.finally === 'function') {
            cusLoading.finally()
          }
        } else {
          loading.close()
        }
      }
    })
  }
})()

/**
 * 调用浏览器的打印打印元素
 * @param {*} el
 * @param {*} userStyle
 * @param {*} width
 */
export function printElement(el, userStyle = {}, width) {
  try {
    const newWindow = window.open('打印窗口', '_blank')// 打印窗口要换成页面的url
    let styles = ''
    const tags = document.querySelectorAll('style')
    for (const tag of tags) {
      styles += `<style type="text/css">${tag.innerHTML}</style>`
    }
    for (const { cssRules } of document.styleSheets) {
      let style = ''
      for (const { cssText } of cssRules) {
        style += cssText
      }
      styles += `<style type="text/css">${style}</style>`
    }
    let userStyles = ''
    for (const selector in userStyle) {
      let style = ''
      for (const cssKey in userStyle[selector]) {
        style += `${cssKey}:${userStyle[selector][cssKey]};`
      }
      userStyles += `${selector}{${style}}`
    }
    styles += `<style type="text/css">${userStyles}</style>`
    const docStr = el.outerHTML
    newWindow.document.write(`
      <html>
        <head>
          <meta charset="utf-8">
          <style type="text/css">
            body{
              width: ${width || el.offsetWidth}px!important;
              margin: 0 auto!important;
            }
            @page {
              /* A4纸 */
              size: a4 portrait;
              /* todo */
              margin: 15mm 20mm;
            }
      
            /*设置横向页面*/
            @page landscape {
              /* A4纸 landscape */
              size: a4 landscape;
              /* todo */
              margin: 28mm 28mm;
            }
            tr{
              page-break-inside:avoid;
            }
          </style>
          ${styles}
        </head>
        <body>
          ${docStr}
        </body>
      </html>
    `)
    newWindow.document.close()
    newWindow.print()
    newWindow.close()
  } catch (e) {
    console.log(e)
  }
}
