const common = require('../common.js');
const app = getApp();
const BMSSet = require('./BMSSet/BMSSet.js');
const readServiceID = '0000FEE7-0000-1000-8000-00805F9B34FB';
const readID = '000036F6-0000-1000-8000-00805F9B34FB';
const writeServiceID = '0000FEE7-0000-1000-8000-00805F9B34FB';
const writeID = '000036F5-0000-1000-8000-00805F9B34FB';
const MTU = 115;
var joinPack = [];
var curTime = 0;
var stateRepeatTime = 0;
var readRepeatTime = 0;
var totalPackLength = 0;
function acceptDevice(device) {
    return device.btid ? true : false;
}
function isSingleBt() {
    return true;
}
function haveBms() {
    console.log('是单蓝牙并且带bms');
    return true;
}
function isDevice(device, data) {
    const advertisData = new Uint8Array(data.advertisData);
    const mac = device.btid
        .split('')
        .map((p, i) => parseInt(p + device.btid[i + 1], 16))
        .filter((p, i) => i % 2 == 0);
    if (advertisData.slice(0, 4).toString() == [9, 255, 1, 2].toString() && advertisData.slice(4, 10).toString() == mac.toString()) {
        return true;
    }
    return false;
}
function sendCommand(cmd, data = []) {
    data = [cmd, data.length].concat(data);
    return common.completArrayCRC(data, data.length);
}

// 鉴权
// function alterConnect(device, deviceId) {
//   return [sendCommand(0x01, [0xAB, 0xCD, 0xAB, 0xCD])]
// }

function readData(device, value, data) {
    if (device.bms == 0) {
        var value = new Uint8Array(value);
        switch (value[0]) {
            case 68:
                if (value.length == 5) {
                    data.voltage = (((value[2] << 8) | value[3]) / 100).toFixed(2);
                }
                break;
            case 66:
                break;
        }
        var endTime = new Date().getTime();
        if (endTime - curTime < 15000) {
            return;
        }
        if (value[0] != 68 && value.length != 5) {
            return;
        }
        if (endTime - curTime > 15000) {
            if (value[0] == 68) {
                curTime = new Date().getTime();
            }
            return data;
        }
    } else {
        var value = new Uint8Array(value);
        var endTime = new Date().getTime();
        if (endTime - curTime > 3000) {
            curTime = new Date().getTime();
            data = packBmsData(device, value, data, true);
            return data;
        }
        if (endTime - curTime <= 3000) {
            data = packBmsData(device, value, data, false);
            return data;
        }
    }
}
function packBmsData(device, value, data, isInit) {
    if (value) {
        if (isInit) {
            joinPack = [];
            totalPackLength = value[2] * 256 + value[3];
            console.log(totalPackLength);
        }
        joinPack = mergeUint8Array(joinPack, value);
        console.log(joinPack);
        if (joinPack.length === totalPackLength + 2) {
            return joinPack;
        }
    }
}
function mergeUint8Array(arr1, arr2) {
    let len1 = arr1 ? arr1.length : 0;
    let len2 = arr2.length;
    let arr = new Uint8Array(len1 + len2);
    for (let i = 0; i < len1; i++) {
        arr[i] = arr1[i];
    }
    for (let i = 0; i < len2; i++) {
        arr[len1 + i] = arr2[i];
    }
    return arr;
}
function stateUpdate(device, deviceId) {
    if (device.bms == 0) {
        curTime = 0;
        return [sendCommand(4)];
    } else {
        readRepeatTime = 0;
        var endTime = new Date().getTime();
        if (endTime - stateRepeatTime > 3000) {
            //防止多条数据重发
            stateRepeatTime = endTime;
            const bluetoothConfig = app.globalData.bluetoothConfig;
            if (Object.keys(bluetoothConfig).includes(device.device_type)) {
                var readCommandList = bluetoothConfig[device.device_type].read;
                console.log(readCommandList);
                var commandList = [];
                for (var i = 0; readCommandList.length > i; i++) {
                    var list = hexToList(readCommandList[i]);
                    commandList.push(list);
                }
                console.log(commandList);
                return commandList;
            }
        }
    }
}
function turnOn(device, deviceId) {
    if (device.bms == 0) {
        return [sendCommand(3, [170])];
    } else {
        readRepeatTime = 0;
        const bluetoothConfig = app.globalData.bluetoothConfig;
        if (Object.keys(bluetoothConfig).includes(device.device_type)) {
            var turnonCommand = bluetoothConfig[device.device_type].turnon;
            var commandList = [];
            var list = hexToList(turnonCommand);
            commandList.push(list);
            return commandList;
        }
    }
}
function turnOff(device, deviceId) {
    if (device.bms == 0) {
        return [sendCommand(3, [187])];
    } else {
        readRepeatTime = 0;
        const bluetoothConfig = app.globalData.bluetoothConfig;
        if (Object.keys(bluetoothConfig).includes(device.device_type)) {
            var turnoffCommand = bluetoothConfig[device.device_type].turnoff;
            var commandList = [];
            var list = hexToList(turnoffCommand);
            commandList.push(list);
            return commandList;
        }
    }
}
function bmsDischargeMOS(value, device) {
    if (value == 1) {
        const bluetoothConfig = app.globalData.bluetoothConfig;
        if (Object.keys(bluetoothConfig).includes(device.device_type)) {
            var turnonCommand = bluetoothConfig[device.device_type].turnon;
            var commandList = [];
            var list = hexToList(turnonCommand);
            commandList.push(list);
            return commandList;
        }
    } else {
        const bluetoothConfig = app.globalData.bluetoothConfig;
        if (Object.keys(bluetoothConfig).includes(device.device_type)) {
            var turnoffCommand = bluetoothConfig[device.device_type].turnoff;
            var commandList = [];
            var list = hexToList(turnoffCommand);
            //this.getConsoleData(sendDataCommand(list))
            commandList.push(list);
            return commandList;
        }
    }
}
function bmsChargingMOS(value, device) {
    if (value == 1) {
        const bluetoothConfig = app.globalData.bluetoothConfig;
        if (Object.keys(bluetoothConfig).includes(device.device_type)) {
            var chargingMosOn = bluetoothConfig[device.device_type].chargingMosOn;
            var commandList = [];
            var list = hexToList(chargingMosOn);
            commandList.push(list);
            return commandList;
        }
    } else {
        const bluetoothConfig = app.globalData.bluetoothConfig;
        if (Object.keys(bluetoothConfig).includes(device.device_type)) {
            var chargingMosOff = bluetoothConfig[device.device_type].chargingMosOff;
            var commandList = [];
            var list = hexToList(chargingMosOff);
            commandList.push(list);
            return commandList;
        }
    }
}
function turnOnBuzzer(device, deviceId) {
    return [sendCommand(80, [170])];
}
function turnOffBuzzer(device, deviceId) {
    return [sendCommand(80, [187])];
}
function queryBaud(device, deviceId) {
    // console.log("下发查询波特率")
    // return [[0x07, 0x01, 0x08]]
}
function setBaud(value, device) {
    console.log('下发设置波特率');
    console.log('下发baud');
    console.log([sendCommand(8, [value])]);
    return [sendCommand(8, [value])];
}
function hexToList(str) {
    var val = [];
    for (var i = 0; i < str.length / 2; i++) {
        val.push(parseInt(str.substring(0 + i * 2, 2 + i * 2), 16));
    }
    return val;
}
function bmsSet(device) {
    if (BMSSet.isBleBmsSet(device)) {
        var bmsSetCmd = BMSSet.bmsSet(device);
        var list = hexToList(bmsSetCmd);
        return [list];
    } else {
        return false;
    }
}
module.exports = {
    readServiceID: readServiceID,
    readID: readID,
    writeServiceID: writeServiceID,
    writeID: writeID,
    MTU: MTU,
    acceptDevice: acceptDevice,
    isDevice: isDevice,
    // alterConnect: alterConnect,
    readData: readData,
    stateUpdate: stateUpdate,
    turnOn: turnOn,
    turnOff: turnOff,
    isSingleBt: isSingleBt,
    haveBms: haveBms,
    bmsDischargeMOS: bmsDischargeMOS,
    bmsChargingMOS: bmsChargingMOS,
    turnOnBuzzer: turnOnBuzzer,
    turnOffBuzzer: turnOffBuzzer,
    queryBaud: queryBaud,
    setBaud: setBaud,
    bmsSet: bmsSet
};
