import cookies from './util.cookies'
import db from './util.db'
import log from './util.log'

const util = {
  cookies,
  db,
  log
}

/**
 * 扁平数组转树形结构
 * @param {Array} data 扁平数组
 * @param {String} key 主键字段名
 * @param {String} pid 父节点字段名
 */
util.formatDataToTree = (data, key = 'menu_id', pid = 'parent_id') => {
  if (!data || data.length <= 0) {
    return []
  }

  const map = {}
  data.forEach(value => { map[value[key]] = { ...value } })

  const tree = []
  data.forEach(item => {
    const id = item[key]
    if (map[id][pid] && map[map[id][pid]]) {
      if (!map[map[id][pid]].children) {
        map[map[id][pid]].children = []
      }
      map[map[id][pid]].children.push(map[id])
    } else {
      tree.push(map[id])
    }
  })
  return tree
}

/**
 * @description 更新标题
 * @param {String} title 标题
 */
util.title = function (titleText) {
  const processTitle = process.env.VUE_APP_TITLE || 'D2Admin'
  window.document.title = `${processTitle}${titleText ? ` | ${titleText}` : ''}`
}

/**
 * @description 打开新页面
 * @param {String} url 地址
 */
util.open = function (url) {
  var a = document.createElement('a')
  a.setAttribute('href', url)
  a.setAttribute('target', '_blank')
  a.setAttribute('id', 'd2admin-link-temp')
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(document.getElementById('d2admin-link-temp'))
}

export default util
