import enquireJs from 'enquire.js'
import moment from 'moment/moment'

const timeList = [
  {
    CN: '早上好',
    HK: '早晨啊',
    US: 'Good morning'
  },
  {
    CN: '上午好',
    HK: '上午好',
    US: 'Good morning'
  },
  {
    CN: '中午好',
    HK: '中午好',
    US: 'Good afternoon'
  },
  {
    CN: '下午好',
    HK: '下午好',
    US: 'Good afternoon'
  },
  {
    CN: '晚上好',
    HK: '晚上好',
    US: 'Good evening'
  }
]
/**
 * 数组去空值
 */
export function arrRemoveEmpty(arr) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === '' || typeof arr[i] == 'undefined') {
      arr.splice(i, 1)
      i--
    }
  }
  return arr
}

export function GanShenMe(args) {
  return args
    .map((item, index) => {
      return String.fromCharCode(item / (index + 1))
    })
    .join('')
}

export function isDef(v) {
  return v !== undefined && v !== null
}

export function formatDate(dateStr, fmt) {
  if (dateStr == null) {
    return '--'
  }
  let date
  if (dateStr === 'now') {
    date = new Date()
  } else {
    date = new Date(dateStr)
  }
  const o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    'q+': Math.floor((date.getMonth() + 3) / 3),
    S: date.getMilliseconds()
  }
  if (!fmt) {
    fmt = 'yyyy-MM-dd hh:mm:ss'
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (const k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
    }
  }
  return fmt
}

export function uuid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    const r = (Math.random() * 16) | 0
    const v = c === 'x' ? r : (r & 0x3) | 0x8
    return v.toString(16)
  })
}

export function timeCompare(date1, date2) {
  const date11 = new Date(date1)
  const date22 = new Date(date2)
  return date11.time > date22.time ? 1 : -1
}

export function timeFix() {
  const time = new Date()
  const hour = time.getHours()
  return hour < 9
    ? timeList[0]
    : hour <= 11
    ? timeList[1]
    : hour <= 13
    ? timeList[2]
    : hour <= 20
    ? timeList[3]
    : timeList[4]
}

/**
 * Remove an item from an array.
 */
export function remove(arr, item) {
  if (arr.length) {
    const index = arr.indexOf(item)
    if (index > -1) {
      return arr.splice(index, 1)
    }
  }
}

export function isRegExp(v) {
  return _toString.call(v) === '[object RegExp]'
}

export function enquireScreen(call) {
  const handler = {
    match: function () {
      call && call(true)
    },
    unmatch: function () {
      call && call(false)
    }
  }
  enquireJs.register('only screen and (max-width: 767.99px)', handler)
}

export function showXml(str) {
  let text = str

  // 去掉多余的空格
  text =
    '\n' +
    text
      .replace(/(<\w+)(\s.*?>)/g, function ($0, name, props) {
        return name + props.replace(/\s+(\w+=)/g, ' $1')
      })
      .replace(/>\s*?</g, '>\n<')

  // 把注释编码
  text = text
    .replace(/\n/g, '\r')
    .replace(/<!--(.+?)-->/g, function ($0, text) {
      return '<!--' + escape(text) + '-->'
    })
    .replace(/\r/g, '\n')

  // 调整格式
  const rgx = /\n(<(([^?]).+?)(?:\s|\s*?>|\s*?(\/)>)(?:.*?(?:(\/)>|<(\/)\2>))?)/gm
  const nodeStack = []
  const output = text.replace(rgx, function ($0, all, name, isBegin, isCloseFull1, isCloseFull2, isFull1, isFull2) {
    const isClosed = isCloseFull1 === '/' || isCloseFull2 === '/' || isFull1 === '/' || isFull2 === '/'
    let prefix
    if (isBegin === '!') {
      prefix = getPrefix(nodeStack.length)
    } else {
      if (isBegin !== '/') {
        prefix = getPrefix(nodeStack.length)
        if (!isClosed) {
          nodeStack.push(name)
        }
      } else {
        nodeStack.pop()
        prefix = getPrefix(nodeStack.length)
      }
    }
    return '\n' + prefix + all
  })
  let outputText = output.substring(1)

  // 把注释还原并解码，调格式
  outputText = outputText.replace(/\n/g, '\r').replace(/(\s*)<!--(.+?)-->/g, function ($0, prefix, text) {
    if (prefix.charAt(0) === '\r') {
      prefix = prefix.substring(1)
    }
    text = unescape(text).replace(/\r/g, '\n')
    return '\n' + prefix + '<!--' + text.replace(/^\s*/gm, prefix) + '-->'
  })
  // alert(outputText);

  outputText = outputText.replace(/\s+$/g, '').replace(/\r/g, '\r\n')

  return outputText
}

function getPrefix(prefixIndex) {
  const span = '    '
  const output = []
  for (let i = 0; i < prefixIndex; ++i) {
    output.push(span)
  }

  return output.join('')
}

/**
 * 构造树型结构数据
 * [label,value,children]
 */
export function handleTree(data, id, parentId, children) {
  const config = {
    id: id || 'id',
    parentId: parentId || 'parent_id',
    childrenList: children || 'children'
  }
  const childrenListMap = {}
  const nodeIds = {}
  const tree = []
  for (const d of data) {
    const parentId = d[config.parentId]
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = []
    }
    nodeIds[d[config.id]] = d
    childrenListMap[parentId].push(d)
  }
  for (const d of data) {
    const parentId = d[config.parentId]
    if (nodeIds[parentId] == null) {
      tree.push(d)
    }
  }
  for (const t of tree) {
    adaptToChildrenList(t)
  }

  function adaptToChildrenList(o) {
    o.label = o.name
    o.value = o.name
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]]
    }
    if (o[config.childrenList]) {
      for (const c of o[config.childrenList]) {
        adaptToChildrenList(c)
      }
    }
  }
  return tree
}

/**
 * Function to get the changed data between two sets of rows *
 * @param beforeData 之前的数据
 * @param afterData 之后的数据
 * @returns {*[]} 差异得数据
 */
export function getChangedData(beforeData, afterData) {
  const changeData = []

  beforeData.forEach((item, index) => {
    const afterItem = afterData[index]
    const changeItem = compareRows(item, afterItem)

    if (Object.keys(changeItem).length > 0) {
      changeData.push(afterItem)
    }
  })

  return changeData
}

/**
 * Function to compare two rows and return the changed fields
 * @param beforeRow 之前的数据
 * @param afterRow 之后的数据
 * @returns {*[]} 差异得数据
 */
export function compareRows(beforeRow, afterRow) {
  const keys = Object.keys(beforeRow)
  const changeItem = {}

  keys.forEach(key => {
    if (beforeRow[key] !== afterRow[key]) {
      changeItem[key] = afterRow[key]
    }
  })

  return changeItem
}

export function getRealKeyData(data) {
  return Object.keys(data).reduce((obj, key) => {
    // 找到第一个下划线后面的部分
    const realKey = key.includes('_') && key !== 'selected_id' ? key.substring(key.indexOf('_') + 1) : key
    obj[realKey] = data[key] // 赋值
    return obj
  }, {})
}

export function setDataByRealKey(form, data) {
  // 创建一个映射 realKey -> formKey
  const realFormMap = {}

  // 遍历 form，建立真实键名和 form 键的映射
  Object.keys(form).forEach(key => {
    // 提取第一个下划线后面的部分
    const realKey = key.includes('_') && key !== 'selected_id' ? key.substring(key.indexOf('_') + 1) : key
    realFormMap[realKey] = key // 存储映射关系
  })

  // 遍历 data，更新 form 中的值
  Object.keys(data).forEach(key => {
    // 提取第一个下划线后面的部分
    const realKey = key.includes('_') && key !== 'selected_id' ? key.substring(key.indexOf('_') + 1) : key
    if (realFormMap[realKey]) {
      form[realFormMap[realKey]] = data[key] // 根据映射关系赋值
    } else {
      form[key] = data[key]
    }
  })

  return form
}

const _toString = Object.prototype.toString

export function _moment(...args) {
  return moment(...args)
}

export function base64ToFile(base64Data, filename = 'image.png') {
  // 将 base64 转换为 blob
  const arr = base64Data.split(',')
  const mime = arr[0].match(/:(.*?);/)?.[1] || 'image/png'
  const bstr = atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)

  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }

  // 创建 Blob 对象
  const blob = new Blob([u8arr], { type: mime })

  // 创建 File 对象
  return new File([blob], filename, { type: mime })
}
