const common = require('../common.js');

const app = getApp();
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 = 128;
var joinPack = [];
var lastLength = 0;
var curTime = 0;
var stateRepeatTime = 0;
var readRepeatTime = 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() == [0x09, 0xff, 0x01, 0x02].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 0x44:
                if (value.length == 5) {
                    data.voltage = (((value[2] << 8) | value[3]) / 100).toFixed(2);
                }

                break;

            case 0x42:
                break;
        }

        var endTime = new Date().getTime();
        if (endTime - curTime < 15000) return;
        if (value[0] != 0x44 && value.length != 5) return;

        if (endTime - curTime > 15000) {
            if (value[0] == 0x44) {
                curTime = new Date().getTime();
            }

            return data;
        }
    } else {
        var value = new Uint8Array(value);
        console.log(value);

        switch (value[0]) {
            case 0x42:
                data = packBmsData(device, value, data);
                return data;
                break;
        }
    }
}

function packBmsData(device, value, data) {
    if (value) {
        if (value[1] === value.length - 6) {
            var totalPackLength = value[2] * 0x100 + value[3];

            if (totalPackLength !== lastLength) {
                joinPack = [];
            }

            lastLength = totalPackLength;

            if (totalPackLength > joinPack.length && totalPackLength > 50) {
                if (value.length > 4 && value[4] !== 0) {
                    var pack = value.slice(5, -1);

                    if (joinPack.length === 0) {
                        joinPack = pack;
                    } else {
                        joinPack = mergeUint8Array(joinPack, pack);
                    }
                }

                if (value.length > 4 && value[4] === 0) {
                    var endTime = new Date().getTime();

                    if (endTime - readRepeatTime > 15000) {
                        //防止多条数据重发
                        var pack = value.slice(5, -1);
                        joinPack = mergeUint8Array(joinPack, pack);
                        readRepeatTime = endTime;
                        data = joinPack;
                        joinPack = [];
                        return data;
                    } else {
                        joinPack = [];
                    }
                }
            }
        }
    }
}

function sendDataCommand(data) {
    data = [0x02, data.length, (data.length & 0xff00) >> 8, data.length & 0x00ff, 0].concat(data);
    return common.completArrayCRC(data, data.length);
}

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(0x04)];
    } 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;
                var commandList = [];

                for (var i = 0; readCommandList.length > i; i++) {
                    var list = hexToList(readCommandList[i]);
                    commandList.push(sendDataCommand(list));
                }

                return commandList;
            }
        }
    }
}

function turnOn(device, deviceId) {
    if (device.bms == 0) {
        return [sendCommand(0x03, [0xaa])];
    } 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(sendDataCommand(list));
            return commandList;
        }
    }
}

function turnOff(device, deviceId) {
    if (device.bms == 0) {
        return [sendCommand(0x03, [0xbb])];
    } 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(sendDataCommand(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(sendDataCommand(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);
            commandList.push(sendDataCommand(list));
            return commandList;
        }
    }
}

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;
}

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
};
