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

let util = {
  cookies,
  log
}

/**
 * @description 更新标题
 * @param {String} title 标题
 */
util.title = function (titleText) {
  const processTitle = '产业园区智慧消防系统'
  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-menu-link')
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(document.getElementById('d2admin-menu-link'))
}

 /**
 * @about Tree 数据格式转化
 * @param rows:json数据对象
 * @param idFieldName:表id的字段名
 * @param pidFieldName:表父级id的字段名
 * @param fileds:要显示的字段,多个字段用逗号分隔
 *
 * @return 无
 * @author dake
 */
util.ConvertToTreeJson = function (rows, idFieldName, pidFieldName, fileds) {
   function exists(rows, ParentId) {
        for (var i = 0; i < rows.length; i++) {
            if (rows[i][idFieldName] == ParentId) { return true }
        }
        return false
    }
    var nodes = []
    // get the top level nodes
    for (var i = 0; i < rows.length; i++) {
        var row = rows[i]
        if (!exists(rows, row[pidFieldName])) {
            var data = {
                id: row[idFieldName]
            }
            var arrFiled = fileds.split(',')
            for (var j = 0; j < arrFiled.length; j++) {
                if (arrFiled[j] != idFieldName) { data[arrFiled[j]] = row[arrFiled[j]] }
            }
            nodes.push(data)
        }
    }

    var toDo = []
    for (var i = 0; i < nodes.length; i++) {
        toDo.push(nodes[i])
    }

    while (toDo.length) {
        var node = toDo.shift() // the parent node
        // get the children nodes
        for (var i = 0; i < rows.length; i++) {
            var row = rows[i]
            if (row[pidFieldName] == node.id) {
                var child = {
                    id: row[idFieldName]
                }
                var arrFiled = fileds.split(',')
                for (var j = 0; j < arrFiled.length; j++) {
                    if (arrFiled[j] != idFieldName) {
                        child[arrFiled[j]] = row[arrFiled[j]]
                    }
                }
                if (node.children) {
                    node.children.push(child)
                } else {
                    node.children = [child]
                }
                toDo.push(child)
            }
        }
    }
    return nodes
}

export default util
