const formatTime = date => {
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()

	return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
	n = n.toString()
	return n[1] ? n : '0' + n
}


//4合1 
function convert4to1(res) {
	let arr = [];
	for (let i = 0; i < res.length; i++) {
		if (i % 4 == 0) {
			let rule = 0.29900 * res[i] + 0.58700 * res[i + 1] + 0.11400 * res[i + 2];
			if (rule > 200) {
				res[i] = 0;
			} else {
				res[i] = 1;
			}
			arr.push(res[i]);
		}
	}
	return arr;
}

//8合1
function convert8to1(arr) {
	let data = [];
	for (let k = 0; k < arr.length; k += 8) {
		let temp = arr[k] * 128 + arr[k + 1] * 64 + arr[k + 2] * 32 + arr[k + 3] * 16 + arr[k + 4] * 8 + arr[k + 5] * 4 +
			arr[k + 6] * 2 + arr[k + 7] * 1
		data.push(temp);
	}
	return data;
}

//我的图片宽度是240，那么拼接的指令就是[29, 118, 48, 0, 30, 0, 240, 0]
//我的图片宽度是160，那么拼接的指令就是[29, 118, 48, 0, 20, 0, 160, 0]
//补充一点，打印非二维码的图片，宽度一定要是24的倍数，不然打印也会出现乱码
function toArrayBuffer(res) {
	let arr = convert4to1(res.data);
	let data = convert8to1(arr);
	let cmds = [].concat([27, 97, 1], [29, 118, 48, 0, 30, 0, 240, 0], data, [27, 74, 3], [27, 64]);
	return new Uint8Array(cmds);
}

function zip_image(res) {
	let arr = convert4to1(res.data);
	let data = convert8to1(arr);
	return data;
}

/**
 * 商品列表处理，防止数据过多超出标线
 */
function goodsGandle(a, b, c) {
	var name = addName(a)
	var SL = addSL(b)
	var DJ = addDJ(c)
	return name + SL + DJ
}
function addName(str) {
	str = '       ' + str
	var l = len(str)
	var zl = 14
	var bl = zl - l
	for (var i = 0; i < bl; i++) {
		str += ' '
	}
	return str
}
function addSL(str) {
	var l = len(str)
	var zl = 11
	var bl = zl - l
	for (var i = 0; i < bl; i++) {
		str += ' '
	}
	return str
}
function addDJ(str) {
	var l = len(str)
	var zl = 5
	var bl = zl - l
	for (var i = 0; i < bl; i++) {
		str = ' ' + str
	}
	return str
}
function len(s) {
	var l = 0
	var a = s.split('')
	for (var i = 0; i < a.length; i++) {
		if (a[i].charCodeAt(0) < 299) {
			l++
		} else {
			l += 2
		}
	}
	return l
}

/*************************************************
* 打印机工具
*/

/**
 * 蓝牙错误状态信息
 */
function BTStatus(code) {
	switch (code) {
		case 10000:
			return '未初始化蓝牙适配器'
			break
		case 10001:
			return '当前蓝牙适配器不可用'
			break
		case 10002:
			return '没有找到指定设备'
			break
		case 10003:
			return '连接失败请重试'
			break
		case 10004:
			return '没有找到指定服务请重试'
			break
		case 10005:
			return '没有找到指定特征值请重试'
			break
		case 10006:
			return '当前连接已断开'
			break
		case 10007:
			return '当前设备不支持'
			break
		case 10008:
			return '系统发生异常'
			break
		case 10009:
			return '系统版本低于 4.3 不支持 BLE'
			break
		default:
			return '打印机未启动'
	}
}

/**
 * @desdc 第二步初判断本机蓝牙是否可用
 * 获取本机蓝牙适配器状态
 */
function getBTAdapterState() {
	return new Promise((resolve, reject) => {
		uni.getBluetoothAdapterState({
			success(res) {
				resolve(res)
			},
			fail(error) {
				reject(BTStatus(error.errMsg))
			}
		})
	})
}



/**
 * @desc 第八步
 * 查询打印机状态
 */
function notifyBLEState(deviceId, serviceId, characteristicId) {
	// 发送给蓝牙打印机判断的状态
	let buf
	let dateView
	buf = new ArrayBuffer(3)
	dateView = new DataView(buf)
	dateView.setUint8(0, 16)
	dateView.setUint8(1, 4)
	dateView.setUint8(2, 2)

	return new Promise((resolve, reject) => {
		// 发送信息给蓝牙打印机
		uni.writeBLECharacteristicValue({
			deviceId: deviceId,
			serviceId: serviceId,
			characteristicId: characteristicId,
			value: buf,
			fail(error) {
				reject(BTStatus(error.errMsg))
			},
		});

		// 收到蓝牙发回的信息
		uni.notifyBLECharacteristicValueChange({
			deviceId: deviceId,
			serviceId: serviceId,
			characteristicId: characteristicId,
			state: true,
			success(res) {
				resolve(12)
				// 不知为何这个api调用不起来，导致蓝牙打印打印不出任何信息，以前是可以用的
				// 监听蓝牙特征变化
				// uni.onBLECharacteristicValueChange(function (r) {
				// 	let result = +ab2hex(r.value);
				// 	resolve(result)
				// })
			},
			fail(error) {
				// reject(BTStatus(error.errMsg))
				reject(BTStatus(error.errCode))
			}
		})
	})
}
// ArrayBuffer转16进度字符串
function ab2hex(buffer) {
	var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function (bit) {
		return ("00" + bit.toString(16)).slice(-2);
	});
	return hexArr.join("");

}

const util = {
	formatTime: formatTime,
	toArrayBuffer: toArrayBuffer,
	zip_image: zip_image,
	goodsGandle: goodsGandle,
	getBTAdapterState: getBTAdapterState,
	notifyBLEState: notifyBLEState

}

export default util
