import Taro from '@tarojs/taro'
const configRight = (params = {key: '', name: ''}, bc) => {
  const sysMenuObj = Taro.getStorageSync('sysMenuObj')
	if (sysMenuObj[params.key]) {
    if (bc) bc(params)
  } else {
		// 临时方案，后续优化
		Taro.$msg(`您没有${params.name}的权限~`)
		return
  }
}
const msgBase = (msgText, bc) => {
  Taro.showToast({
    title: msgText,
    icon: 'none',
    duration: 2000
  }).then(() => {
		if (bc) bc()
	})
}
const confirmMsgFn = (msgText, successBc, errorBc, title = '提示') => {
  Taro.showModal({
    title,
    content: msgText,
    success: function (res) {
      if (res.confirm) {
        if (successBc) successBc()
      } else if (res.cancel) {
        if (errorBc) errorBc()
      }
    }
  })
}
const getXOR = (val) => {
	var data = formatHex(val)
	var count = 0
	var sum = 0
	var ss = data.split(" ")
	for (var i = 0; i < ss.length; i++) {
		if (ss[i] === "") continue
		sum = sum ^ parseInt(ss[i], 16)
		count++
	}
	var hex = sum.toString(16)
	hex = hex.toUpperCase()
	if (hex.length < 2) hex = '0' + hex
	return hex
}

const formatHex = (s) => {
	var n = ""
	s = s.replace(/ ([0-9A-Fa-f]) /g, " 0$1 ")
	s = s.replace(/\s/g, "")
	for (var i = 0; i < s.length; i++) {
		n += s[i]
		if (i % 2 == 1 && i != s.length - 1) n += " "
	}
	return n
}

const transToArray = (str, num) => { // 将字符串分割成每n个一组
	let arr = [] //保存每次截取后的字符串
	let counts = Math.ceil(str.length / num) //循环截取的次数,向上取整
	let [s, e] = [0, num]
	for (let i = 0; i < counts; i++) {
		let newStr = str.substring(s, e)
		arr.push(newStr)
		s = e
		e += num
	}
	return arr
}

const transBuffer = (hex) => {
	const typeArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map((h) => {
		return parseInt(h, 16)
	}))
	const buffer = typeArray.buffer
	return buffer
}

const ab2hex = (buffer) => {// ArrayBuffer转16进度字符串示例
	const hexArr = Array.prototype.map.call(new Uint8Array(buffer),function(bit) {
		return ('00' + bit.toString(16)).slice(-2)
	})
	return hexArr.join('')
}
export {
  configRight,
  msgBase,
  confirmMsgFn,
  getXOR, // 异或校验
	formatHex,
	transToArray,
	transBuffer,
	ab2hex
}
 