/**
 * 项目的公共方法
 */
import $ from 'jquery'

/**
 * 对象重新排序
 * @param {*} obj
 * @returns
 */
export function sortObjASCII(obj) {
  let arr = Object.keys(obj).sort()
  if (arr.length === 0) {
    return {}
  }
  let sortObj = {}
  for (let ii in arr) {
    sortObj[arr[ii]] = obj[arr[ii]]
  }
  return sortObj
}

/**
 * @desc 格式化日期字符串
 * @param { Nubmer} - 时间戳
 * @returns { String } 格式化后的日期字符串
 */
export function formatDate(timestamp) {
  // 补全为13位
  let arrTimestamp = (timestamp + '').split('')
  for (let start = 0; start < 13; start++) {
    if (!arrTimestamp[start]) {
      arrTimestamp[start] = '0'
    }
  }
  timestamp = arrTimestamp.join('') * 1
  let minute = 1000 * 60
  let hour = minute * 60
  let day = hour * 24
  let month = day * 30
  let now = new Date().getTime()
  let diffValue = now - timestamp
  // 如果本地时间反而小于变量时间
  if (diffValue < 0) {
    return '不久前'
  }
  // 计算差异时间的量级
  let monthC = diffValue / month
  let weekC = diffValue / (7 * day)
  let dayC = diffValue / day
  let hourC = diffValue / hour
  let minC = diffValue / minute
  // 数值补0方法
  let zero = function (value) {
    if (value < 10) {
      return '0' + value
    }
    return value
  }
  // 使用
  if (monthC > 4) {
    // 超过1年，直接显示年月日
    return (function () {
      let date = new Date(timestamp)
      return date.getFullYear() + '年' + zero(date.getMonth() + 1) + '月' + zero(date.getDate() + 1) + '日'
    })()
  } else if (monthC >= 1) {
    return parseInt(monthC) + '月前'
  } else if (weekC >= 1) {
    return parseInt(weekC) + '周前'
  } else if (dayC >= 1) {
    return parseInt(dayC) + '天前'
  } else if (hourC >= 1) {
    return parseInt(hourC) + '小时前'
  } else if (minC >= 1) {
    return parseInt(minC) + '分钟前'
  }
  return '刚刚'
}

/**
 * 获取日期字符串
 * @returns
 */
export function getDateStr() {
  const date = new Date(),
    year = date.getFullYear(),
    month = date.getMonth() > 9 ? date.getMonth() + 1 : `0${date.getMonth() + 1}`,
    day = date.getDate() + 1 > 9 ? date.getDate() + 1 : `0${date.getDate() + 1}`,
    hh = date.getHours() > 9 ? date.getHours() : `0${date.getHours()}`,
    mm = date.getMinutes() > 9 ? date.getMinutes() : `0${date.getMinutes()}`
  return `${year}${month}${day}${hh}${mm}`
}

/**
 * 随机生成字符串
 * @param {*} len
 * @returns
 */
export function randomString(len) {
  const length = len || 32
  let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz12345678',
    maxPos = chars.length,
    pwd = ''
  for (let i = 0; i < length; i++) {
    pwd += chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}

// 根据id 查找树中的节点内容
export const findTreeElementByKey = (tree, key, value) => {
  for (let i = 0; i < tree.length; i++) {
    const bool = !isNaN(value) ? parseFloat(tree[i][key]) === parseFloat(value) : tree[i][key] === value
    if (bool) {
      // 找到元素
      return tree[i]
    } else if (Array.isArray(tree[i].children)) {
      // 递归遍历子节点
      const found = findTreeElementByKey(tree[i].children, key, value)
      if (found) {
        return found
      }
    }
  }
  return null // 没有找到元素
}

// 设置所有有children 的展开项
export const findParentsExpanded = (treeData, targetKey = 'id') => {
  const keys = []

  function traverse(nodes) {
    if (!nodes) return

    for (const node of nodes) {
      if (node.children) {
        keys.push(node[targetKey])
        traverse(node.children)
      }
    }
  }

  traverse(treeData)

  return keys
}

// 将路由菜单转为树形菜单
export const treeRouterData = (source, id = 'menuId', parentId = 'pid', children = 'children') => {
  const cloneData = JSON.parse(JSON.stringify(source))
  if (source.length === 0) return source
  return cloneData.filter(father => {
    const branchArr = cloneData.filter(child => parseFloat(father[id]) === parseFloat(child[parentId]))

    father[children] = branchArr.length > 0 ? branchArr : null
    return father[parentId] === 0
  })
}

// 将数组转换成Tree所需要的数组
export function convertToAntdTreeData(data, target = 'label') {
  const antdTreeData = []

  const convertNode = node => {
    const antdTreeNode = {
      ...node,
      title: node[target],
      key: node.id,
      select: false,
      edit: false
    }

    if (node.children && node.children.length > 0) {
      antdTreeNode.children = node.children.map(convertNode)
    }

    return antdTreeNode
  }

  antdTreeData.push(...data.map(convertNode))

  return antdTreeData
}

// 查找树里面的所有父级节点
export const findParents = (treeData, targetKey = 'id', value) => {
  for (const node of treeData) {
    if (parseFloat(node[targetKey]) === parseFloat(value)) {
      return []
    }
    if (node.children) {
      const parents = findParents(node.children, targetKey, value)
      if (parents) {
        return [node[targetKey], ...parents]
      }
    }
  }
  return null
}

export const findNodeById = (tree, targetKey = 'id', targetId) => {
  // 递归处理树节点
  for (const node of tree) {
    // 如果当前节点的 id 等于目标 id，返回当前节点的所有子节点的 id
    if (node[targetKey] === targetId) {
      if (node.children && node.children.length) {
        return collectChildrenIds(node.children, targetKey)
      }
    }

    // 递归处理子节点
    if (node.children && node.children.length > 0) {
      const result = findNodeById(node.children, targetKey, targetId)
      if (result) {
        return result
      }
    }
  }

  // 如果未找到目标节点，返回空数组
  return []
}

function collectChildrenIds(children, targetKey) {
  // 收集子节点的 id
  const ids = []
  for (const child of children) {
    ids.push(child[targetKey])

    // 递归处理孙子节点
    if (child.children && child.children.length > 0) {
      ids.push(...collectChildrenIds(child.children, targetKey))
    }
  }
  return ids
}

// 查找树里面的所有父级节点
export const findAllParents = (tree, key, value, parents = []) => {
  for (const node of tree) {
    const currentKey = node[key]
    const children = node.children || []

    if (currentKey === value) {
      return parents.concat(currentKey)
    }

    if (children.length > 0) {
      const result = findAllParents(children, key, value, parents.concat(currentKey))
      if (result.length > 0) {
        return result
      }
    }
  }

  return []
}

// 查找树里面的所有子级节点
export const findAllChildren = (tree, key, value) => {
  for (const node of tree) {
    const currentKey = node[key]
    const currentChildren = (node.children || []).map(child => child[key])

    if (currentKey === value) {
      return currentChildren
    }

    if (currentChildren.length > 0) {
      const result = findAllChildren(node.children, key, value, currentChildren)
      return result
    }
  }
}

// 将树形结构转为一维数组
export const treeDataToArray = source => {
  const res = []
  // 第二种方式
  source.length &&
    source.forEach(item => {
      res.push(item)
      item.children && res.push(...treeDataToArray(item.children))
    })
  return res
}

export const getStyleValue = (elem, styleKey) => {
  let res = ''

  const styleStr = $(elem).attr('style') || '' // 如 'line-height: 2.5; color: red;'
  const styleArr = styleStr.split(';') // 如 ['line-height: 2.5', ' color: red', '']
  const length = styleArr.length
  for (let i = 0; i < length; i++) {
    const styleItemStr = styleArr[i] // 如 'line-height: 2.5'
    if (styleItemStr) {
      const arr = styleItemStr.split(':') // ['line-height', ' 2.5']
      if (arr[0].trim() === styleKey) {
        res = arr[1].trim()
      }
    }
  }

  return res
}

// 根据id 查找树中的节点内容
export const findFirstNotHasChildren = tree => {
  if (tree.length > 0) {
    if (tree[0].children && tree[0].children.length > 0) {
      return findFirstNotHasChildren(tree[0].children)
    }
    return tree[0]
  }
  return null // 没有找到元素
}

// 只返回父级， 只找上面第一层的父级
export const findParentLevelOne = (data, key = 'id', value) => {
  for (let i = 0; i < data.length; i++) {
    const item = data[i]
    if (item.children) {
      const child = item.children.find(c => c[key] === value)
      if (child) {
        // 找到目标子元素，返回其父元素
        return item
      } else {
        // 递归查找子元素的子元素
        const result = findParentLevelOne(item.children, key, value)
        if (result) {
          return result
        }
      }
    }
  }
  // 没有找到目标子元素，返回null
  return null
}

// 找所在位置
export const findTreeToIndex = (data, key, value) => {
  let index = data.findIndex(item => item[key] === value)
  return index > -1 ? index : -1
}

export const hexToRgb = hex => {
  // 移除前缀#符号
  let hexTemp = hex.replace(/^\s*#|\s*$/g, '')

  // 将三位十六进制转为六位
  if (hexTemp.length === 3) {
    hexTemp = hexTemp.replace(/(.)/g, '$1$1')
  }

  // 提取R、G、B各自的十六进制表示方式
  const rgb = /^(\w{2})(\w{2})(\w{2})$/.exec(hexTemp)

  // 转为10进制并返回
  return rgb
    ? {
        r: parseInt(rgb[1], 16),
        g: parseInt(rgb[2], 16),
        b: parseInt(rgb[3], 16)
      }
    : null
}

export const clacTopicText = (type, radio, checkbox, judge, fill, textarea) => {
  let i = 0
  let arr = ['一', '二', '三', '四', '五']
  if (type === 'radio') {
    return '一'
  }
  if (type === 'checkbox') {
    if (radio.length > 0) {
      return '二'
    } else {
      return '一'
    }
  }
  if (type === 'judge') {
    if (radio.length > 0 && checkbox.length > 0) {
      return '三'
    } else {
      if (radio.length > 0 || checkbox.length > 0) {
        return '二'
      } else {
        return '一'
      }
    }
  }
  if (type === 'fill') {
    if (radio.length > 0) {
      i++
    }
    if (checkbox.length > 0) {
      i++
    }
    if (judge.length > 0) {
      i++
    }
    return arr[i]
  }
  if (type === 'textarea') {
    if (radio.length > 0) {
      i++
    }
    if (checkbox.length > 0) {
      i++
    }
    if (judge.length > 0) {
      i++
    }
    if (fill.length > 0) {
      i++
    }
    return arr[i]
  }
}

export const downloadFile = (res = '') => {
  window.open(import.meta.env.VITE_API_URL_WORD + '/' + res)
}

// 延时函数
export const sleep = time => new Promise(resolve => setTimeout(resolve, time))
