// import axios from 'axios'
// import API from '@utils/sha256/myHttpClient'
import menu_date from './menu_date' // 菜单栏数据
// 处理input，select框默认样式
function focusElementInputStatus(ev, that) {
  that.$set(ev.target.parentNode, 'className', 'el-input')
}
function focusElementSelectStatus(ev, that) {
  that.$set(ev.target.parentNode.parentNode, 'className', 'el-input')
}
function focusElementCascaderStatus(ev, that) {
  that.$set(ev.target.parentNode, 'className', 'el-input')
}
function blurElementInputStatus(ev, that) {
  that.$set(ev.target.parentNode, 'className', 'inputLine el-input')
}

function blurElementSelectStatus(ev, that) {
  that.$set(ev.target.parentNode.parentNode, 'className', 'inputLine el-input')
}

function blurElementCascaderStatus(ev, that) {
  that.$set(
    ev.target.parentNode,
    'className',
    'inputLine el-input el-input--suffix'
  )
}
// data: 传入数组,attributes 封装属性
function toTreeData(data, attributes) {
  const resData = data
  const tree = [] // 返回树状
  // 遍历 传入的数组
  for (let i = 0; i < resData.length; i++) {
    // 如果 当前便利的节点为 根节点
    if (resData[i].parent_id === attributes.rootId) {
      // 创建根节点对象
      const obj = {
        id: resData[i][attributes.id],
        label: resData[i][attributes.name],
        parent_id: resData[i][attributes.parent],
        enabled: resData[i][attributes.enabled],
        description: resData[i][attributes.description],
        children: []
      }
      // 将根节点对象添加到树状结构数组
      tree.push(obj)
      // 将当前遍历的的节点删除
      resData.splice(i, 1)
      // 重定遍历标识符
      i--
    }
  }
  // 执行run 方法 传入参数 当前树状结构
  run(tree)
  function run(chiArr) {
    // 若传入数组还有值
    if (resData.length !== 0) {
      // 遍历树状结构
      for (let i = 0; i < chiArr.length; i++) {
        // 树状结构循环迭代内,遍历剩余传入数组
        for (let j = 0; j < resData.length; j++) {
          // 若 当前便利的树状结构中的id === 传入数组的 parent
          if (chiArr[i].id === resData[j][attributes.parent]) {
            // 创建子节点对象
            const obj = {
              id: resData[j][attributes.id],
              label: resData[j][attributes.name],
              parent_id: resData[j][attributes.parent],
              enabled: resData[j][attributes.enabled],
              description: resData[j][attributes.description],
              children: []
            }
            // 当前遍历树状结构 childrenpush 子节点对象
            chiArr[i].children.push(obj)
            // 传入数组 加入子节点的值 删除
            resData.splice(j, 1)
            // 重定遍历标识符
            j--
          }
        }
        // 递归 当前遍历到的树状结构的 children节点
        run(chiArr[i].children)
      }
    }
  }
  return tree
}

/*
平面数据转换成前端的树形结构
原数据

{
  "material_types": [
    {
      "material_type_id": "mt001",
      "material_type_name": "棉布",
      "material_type_parent_id": "mt001"
    }
  ]
}
使用
let attributes = { // 树状结构属性
  id: 'material_type_id',
  parent_id: 'material_type_parent_id',
  label: 'material_type_name',
  extend: 'extend'
}
let treeData = this.$pub_fun.plainToTreeData(data.material_types, attributes)
转换成children形式的数据，主要用于tree控件
*/
function plainToTreeData(items, attributes, alwayChildren = true) {
  function attributeMap(item) {
    const rstItem = item
    for (var attr in attributes) {
      rstItem[attr] = item[attributes[attr]]
    }
    return rstItem
  }

  function getChildren(parentId, items) {
    const resItems = items
    const children = []

    resItems.forEach(function(item) {
      if (item[attributes['parent_id']] === parentId) {
        const curChildren = getChildren(
          item[attributes['id']],
          resItems,
          attributes
        )
        if (alwayChildren || (curChildren !== null && curChildren.length > 0)) {
          item.children = curChildren
        }
        children.push(attributeMap(item))
      }
    })

    return children
  }

  const resItems = items
  const treeData = []
  resItems.forEach(function(item) {
    if (
      item[attributes['parent_id']] === '' ||
      item[attributes['parent_id']] === null
    ) {
      const curChildren = getChildren(item[attributes['id']], resItems)
      if (alwayChildren || (curChildren !== null && curChildren.length >= 0)) {
        item.children = curChildren
      }
      treeData.push(attributeMap(item, attributes))
    }
  })

  return treeData
}

// 树状结构递归成普通数组
function normalizeTree(arr, ret) {
  const count = arr.length
  if (count) {
    for (let i = 0; i < count; i++) {
      const temp = arr[i]
      ret.push({
        name: temp.label,
        parent_id: temp.parent,
        enabled: 'true',
        description: '描述'
      })
      if (temp.children.length) {
        normalizeTree(temp.children, ret)
      }
    }
  }
  return ret
}

// 获取区域数据方法
// function getChildAreaInfo (ev, that) {
//   that.$api.getChildAreaInfo(ev[ev.length - 1]).then(res => {
//   })
// }

/*
* 处理时间格式
* val：有值则返回相应的日期  没有值则 返回当前日期
* 返回值：格式 yyyy-mm-dd
*/
function formatDate(val = '') {
  let date = new Date(val)
  if (val === '' || !val) {
    date = new Date()
  }
  return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
}
function getWeekNumber(src) {
  const date = new Date(src)
  date.setHours(0, 0, 0, 0)
  // Thursday in current week decides the year.
  date.setDate(date.getDate() + 3 - ((date.getDay() + 6) % 7))
  // January 4 is always in week 1.
  const week1 = new Date(date.getFullYear(), 0, 4)
  // Adjust to Thursday in week 1 and count number of weeks from date to week 1.
  return (
    1 +
    Math.round(
      ((date.getTime() - week1.getTime()) / 86400000 -
        3 +
        ((week1.getDay() + 6) % 7)) /
        7
    )
  )
}

// 数组对象  按照属性值，查找对象是否存在数组中 -1不存在 存在返回所在的下标
function findElem(arrayToSearch, attr, val) {
  for (let i = 0; i < arrayToSearch.length; i++) {
    if (arrayToSearch[i][attr] === val) {
      return i
    }
  }
  return -1
}
// 计算权限的值
function computedPerm(data) {
  let text = 'n'
  if (data.modify) {
    text = 'rw'
  } else if (data.readOnly) {
    text = 'r'
  }
  return text
}
// UUID in js 生成UUID
function generateUUID() {
  let d = new Date().getTime()
  const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(
    c
  ) {
    const r = (d + Math.random() * 16) % 16 | 0
    d = Math.floor(d / 16)
    return (c === 'x' ? r : (r & 0x7) | 0x8).toString(16)
  })
  return uuid
}

function deepCopy(obj) {
  if (!obj) return
  var newObj
  try {
    newObj = obj.constructor && obj.constructor === Array ? [] : {}
    newObj.constructor = obj.constructor
  } catch (e) {
    newObj = []
  }
  if (typeof obj !== 'object') {
    return
  } else if (window.JSON) {
    // 若需要考虑特殊的数据类型，如正则，函数等，需把这个else if去掉即可
    newObj = JSON.parse(JSON.stringify(obj))
  } else {
    for (var prop in obj) {
      if (obj[prop].constructor === RegExp || obj[prop].constructor === Date) {
        newObj[prop] = obj[prop]
      } else if (typeof obj[prop] === 'object') {
        // 递归
        newObj[prop] = deepCopy(obj[prop])
      } else {
        newObj[prop] = obj[prop]
      }
    }
  }
  return newObj
}

function getRandomColor() {
  return (
    '#' +
    ('00000' + ((Math.random() * 16777215 + 0.5) >> 0).toString(16)).slice(-6)
  )
}
// 获取1年中指定的礼拜几
function getWeekDayForYear(iYear, iWeekDay) {
  iYear = parseInt(iYear)
  var leap = iYear % 4 === 0 && iYear % 100 !== 0
  var all = []
  var end = 0
  for (var month = 1; month <= 12; month++) {
    switch (month) {
      case 1:
      case 3:
      case 5:
      case 7:
      case 8:
      case 10:
      case 12:
        end = 31
        break
      case 4:
      case 6:
      case 9:
      case 11:
        end = 30
        break
      case 2:
        end = leap ? 29 : 28
        break
    }
    for (var date = 1; date <= end; date++) {
      all.push(
        iYear +
          '-' +
          (month < 10 ? '0' + month : month) +
          '-' +
          (date < 10 ? '0' + date : date)
      )
    }
  }
  var begin = new Date()
  begin.setFullYear(iYear)
  begin.setMonth(0)
  begin.setDate(1)
  iWeekDay = parseInt(iWeekDay)
  begin =
    begin.getDay() === iWeekDay
      ? 0
      : begin.getDay() < iWeekDay
        ? iWeekDay - begin.getDay()
        : iWeekDay - begin.getDay() + 7
  end = leap ? 366 : 365
  var days = []
  while (begin < end) {
    days.push(all[begin])
    begin += 7
  }
  return days
}

// 递归获取树 [{id: 1, parentId: null, name: '11'}, {id: 2, parentId: null, name: '22'}, {id: 3, parentId: 1, name: '33'}, {id: 4, parentId: 1, name: '44'}]
function getTreeData(data, idField, parentField, childField) {
  // 删除 所有 children,以防止多次调用
  if (!childField) childField = 'childData'
  data.forEach(function(item) {
    delete item[childField]
  })

  // 将数据存储为 以 id 为 KEY 的 map 索引数据列
  var map = {}
  data.forEach(function(item) {
    map[item[idField]] = item
  })
  //        console.log(map);
  var val = []
  data.forEach(function(item) {
    // 以当前遍历项，的pid,去map对象中找到索引的id
    var parent = map[item[parentField]]
    // 好绕啊，如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
    if (parent) {
      if (!parent[childField]) parent[childField] = []
      parent[childField].push(item)
    } else {
      // 如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
      val.push(item)
    }
  })
  return val
}

function notificationErrorText(text, htmlString = false) {
  Notification.error({
    dangerouslyUseHTMLString: htmlString,
    message: htmlString
      ? '<span>' +
        text +
        '</br><a href="http://www.huansi.net" target="_blank" style="margin-right:10px;">客服中心</a><a href="http://www.huansi.net" target="_blank">反馈信息</a></span>'
      : text,
    duration: 10000
  })
}

// 获取字符串的时间
function getStringDate(date) {
  if (!date || date === null) {
    return ''
  }
  var sDate = new Date(date)
  return (
    sDate.getFullYear() +
    '-' +
    add0(sDate.getMonth() + 1) +
    '-' +
    add0(sDate.getDate())
  )
}

function add0(i) {
  return i < 10 ? '0' + i : i
}

// 比较两个数组的差异并返回新数组
function compareArr(sOldArr, sNewArr, sKey) {
  var resArr = []
  var bExists
  var item
  var i
  var j
  // 得到删除了的
  for (i = 0; i < sOldArr.length; i++) {
    bExists = false
    item = sOldArr[i]
    for (j = 0; j < sNewArr.length; j++) {
      if (item[sKey] === sNewArr[j][sKey]) {
        bExists = true
        break
      }
    }
    if (bExists) continue
    item.op_action = 'delete'
    resArr.push(item)
  }
  // 得到添加的了的
  for (i = 0; i < sNewArr.length; i++) {
    bExists = false
    item = sNewArr[i]
    for (j = 0; j < sOldArr.length; j++) {
      if (item[sKey] === sOldArr[j][sKey]) {
        bExists = true
        break
      }
    }
    if (bExists) continue
    item.op_action = 'add'
    resArr.push(item)
  }
  return resArr
}
function getStringFilter(filter) {
  if (!filter || filter === null || filter.length === 0) return
  var res = ''
  for (var key in filter) {
    res += key + '=' + filter[key] + '&'
  }
  return res
}

function goUrl(sUrl) {
  if (!sUrl) return
  this.$router.push(sUrl)
}

function sureDelete(obj, sMsg) {
  sMsg = sMsg ? sMsg + '' : '此操作将删除, 是否继续?'
  return obj.$confirm(sMsg, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
}

function exportExcel(tableId) {
  tableToExcel(tableId)
}
var tableToExcel = (function() {
  var uri = 'data:application/vnd.ms-excel;base64,'
  var template =
    '<html><head><meta charset="UTF-8"></head><body><table>{table}</table></body></html>'
  var base64 = function(s) {
    return window.btoa(unescape(encodeURIComponent(s)))
  }
  var format = function(s, c) {
    return s.replace(/{(\w+)}/g, function(m, p) {
      return c[p]
    })
  }
  return function(table, name) {
    if (!table.nodeType) table = document.getElementById(table)
    var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
    window.location.href = uri + base64(format(template, ctx))
  }
})()

function propUnique(arr, prop) {
  const hash = {}
  const ret = arr.reduce((init, next) => {
    hash[next[prop]] ? '' : (hash[next[prop]] = true && init.push(next))
    return init
  }, [])
  return ret
}
// 数组对象指定属性排序升序
function compare(prop) {
  return function(a, b) {
    const valueA = a[prop]
    const valueB = b[prop]
    return valueA - valueB
  }
}

function propSort(
  originData = validateParameters('originData'),
  sortProp = validateParameters('sortProp'),
  originWrap = validateParameters('originWrap'),
  originProp = validateParameters('originProp')
) {
  console.log('已经排序了')
  if (originData.length) {
    const handelData = [...originData]
    handelData.forEach((item, index, self) => {
      self[index][originProp] = item[originWrap][originProp]
    })
    return handelData.sort(compare(sortProp))
  } else {
    console.log('origindata.haven`t length')
    return false
  }
}

function validateParameters(parameterName) {
  throw new Error(`miss parameters ${parameterName}`)
}

// 菜单项
// function getMenu() {
//   const interrogationParms = {
//     id: sessionStorage.app_id
//   }
//   return API.get('mesAPI/sm_role/query_list/', {}, interrogationParms).then
// }

function getMenuData() {
  return menu_date
}
// 深度拷贝
function deep_copy(target) {
  if (typeof target !== 'object') return target
  const target_copy = typeof target === Array ? [] : {}
  Object.keys(target).forEach(x => {
    if (target[x] && typeof target[x] === 'object') {
      target_copy[x] = deep_copy(target[x])
    } else {
      target_copy[x] = target[x]
    }
  })
  return target_copy
}
function filter_change_data(oldData = {}, newData = {}, billNotCheck = {}) {
  const oldDataold = deep_copy(oldData)
  const newDataO = deep_copy(newData)
  const parm = {}
  for (const prop in newDataO) {
    const op = oldDataold[prop]
    const np = newDataO[prop]
    const false_list = [undefined, null, '']
    if (Array.isArray(op) && Array.isArray(np)) {
      const str_op = op.sort().toString()
      const str_np = np.sort().toString()
      if (str_op !== str_np) {
        parm[prop] = newDataO[prop]
      }
      continue
    }
    if (op !== np || Reflect.has(billNotCheck, prop)) {
      const jop = false_list.includes(op)
      const pnp = false_list.includes(np)
      if (jop && pnp) {
        delete newDataO[prop]
      } else {
        parm[prop] = newDataO[prop]
      }
    }
  }
  return parm
}
const elementStatus = {
  focusElementInputStatus: focusElementInputStatus,
  focusElementSelectStatus: focusElementSelectStatus,
  blurElementInputStatus: blurElementInputStatus,
  blurElementSelectStatus: blurElementSelectStatus,
  blurElementCascaderStatus: blurElementCascaderStatus,
  focusElementCascaderStatus: focusElementCascaderStatus,
  formatDate: formatDate,
  getWeekNumber: getWeekNumber,
  findElem: findElem,
  toTreeData: toTreeData,
  normalizeTree: normalizeTree,
  computedPerm: computedPerm,
  generateUUID: generateUUID,
  deepCopy: deepCopy,
  getRandomColor: getRandomColor,
  getWeekDayForYear: getWeekDayForYear,
  notificationErrorText: notificationErrorText,
  getStringDate: getStringDate,
  getTreeData: getTreeData,
  compareArr: compareArr,
  getStringFilter: getStringFilter,
  exportExcel: exportExcel,
  goUrl: goUrl,
  sureDelete: sureDelete,
  propUnique,
  propSort,
  plainToTreeData,
  getMenuData,
  // getMenu,
  deep_copy,
  filter_change_data
}
export default elementStatus
