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

const parse = require('./blueParse/LSCabinet/LSCabinet.js');

const tool = require('./blueParse/LSCabinet/LSCabinetTool.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 app = getApp();
const MTU = 115;
var isStart = 0; //0 未开始 1 已开始 2进行中 3已完成

var timeOut = 0; //超时次数

var deviceData = {};

function acceptDevice(device) {
    return device.btid ? true : false;
}

function isSingleBt() {
    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 sendExchangeCommand(data) {
    deviceData = data;
    app.globalData.deviceBTBMSBuf[data.mac_id] = {
        bms_origin_data: null
    };
    var body = tool.togetherCommand([0x01, 0x01], data);
    common.reportLog(2, deviceData.dev_id, '下发换电指令：' + Uint8ArrayToString(body));
    return [body];
} //租电指令

function sendHireCommand(data) {
    deviceData = data;
    app.globalData.deviceBTBMSBuf[data.mac_id] = {
        bms_origin_data: null
    };
    var body = tool.togetherCommand([0x02, 0x01], data);
    common.reportLog(2, deviceData.dev_id, '下发租电指令：' + Uint8ArrayToString(body));
    return [body];
} //还电指令

function sendBackCommand(data) {
    deviceData = data;
    app.globalData.deviceBTBMSBuf[data.mac_id] = {
        bms_origin_data: null
    };
    var body = tool.togetherCommand([0x03, 0x01], data);
    common.reportLog(2, deviceData.dev_id, '下发还电指令：' + Uint8ArrayToString(body));
    return [body];
} //确认指令 (序列号，密钥，消息头)

function sendConfirmCommand(value, serialNum) {
    app.globalData.deviceBTBMSBuf[deviceData.mac_id] = {
        bms_origin_data: null
    };
    var body = tool.confirmCommand(value, serialNum, deviceData.key);
    common.reportLog(2, deviceData.dev_id, '下发确认指令：' + Uint8ArrayToString(body));
    return [body];
} //取消确认指令

function sendCancelCommand(serialNum) {
    app.globalData.deviceBTBMSBuf[deviceData.mac_id] = {
        bms_origin_data: null
    };
    var body = tool.confirmCommand([0x04, 0x01], serialNum, deviceData.key);
    common.reportLog(2, deviceData.dev_id, '下发取消指令：' + Uint8ArrayToString(body));
    return [body];
} //获取柜体信息

function sendGetCabinetInfoCommand(data) {
    isStart = 1;
    deviceData = data;
    app.globalData.deviceBTBMSBuf[data.mac_id] = {
        bms_origin_data: null
    };
    deviceData.serialNum = new Date().getTime().toString();
	console.log(deviceData.serialNum + "deviceData.serialNum")
    var body = tool.confirmCommand([0x06, 0x01], deviceData.serialNum, deviceData.key);
    common.reportLog(2, deviceData.dev_id, '下发获取柜体信息指令：' + Uint8ArrayToString(body));
    return [body];
} //开仓指令

function sendOpenBoxCommand() {
    app.globalData.deviceBTBMSBuf[deviceData.mac_id] = {
        bms_origin_data: null
    };
    return [tool.confirmCommand([0x05, 0x01], deviceData.serialNum, deviceData.key)];
} // // 鉴权
// function alterConnect(device, deviceId) {
//   return [sendCommand(0x01, [0xAB, 0xCD, 0xAB, 0xCD])]
// }

function readData(device, value, data) {
    var value = new Uint8Array(value);
    console.log('接收到的指令');
    console.log(value.toString);
    let macid = device.mac_id;

    if (value[value.length - 1] === 0x78 && value[0] === 0x7a) {
        //单包封包直接结束
        var bms_data = value;
        app.globalData.deviceBTBMSBuf[macid].bms_origin_data = bms_data;
        common.reportLog(1, deviceData.dev_id, '接收蓝牙返回指令：' + Uint8ArrayToString(bms_data));
        var json = getCompleteData(bms_data);
        app.globalData.deviceBTBMSBuf[macid].bms_origin_data = null;
        return json;
    }

    if (value[value.length - 1] !== 0x78 && value[0] === 0x7a) {
        //分包开头
        var bms_data = value;
        app.globalData.deviceBTBMSBuf[macid].bms_origin_data = bms_data;
    }

    if (value[value.length - 1] !== 0x78 && value[0] !== 0x7a) {
        //分包中间过程封包
        var bms_data = tool.mergeUint8Array(app.globalData.deviceBTBMSBuf[macid].bms_origin_data, value);
        app.globalData.deviceBTBMSBuf[macid].bms_origin_data = bms_data;
    }

    if (value[value.length - 1] === 0x78 && value[0] !== 0x7a) {
        //分包结束
        var bms_data = tool.mergeUint8Array(app.globalData.deviceBTBMSBuf[macid].bms_origin_data, value);
        app.globalData.deviceBTBMSBuf[macid].bms_origin_data = bms_data;
        common.reportLog(1, deviceData.dev_id, '接收蓝牙返回指令：' + Uint8ArrayToString(bms_data));
        var json = getCompleteData(bms_data);
        app.globalData.deviceBTBMSBuf[macid].bms_origin_data = null;
        return json;
    }
}

function Uint8ArrayToString(fileData) {
    var dataString = '';

    for (var i = 0; i < fileData.length; i++) {
        var dataInt = parseInt(fileData[i]);
        dataString = (dataString == '' ? dataString : dataString + ',') + (dataInt < 16 ? '0' + dataInt.toString(16) : dataInt.toString(16));
    }

    return dataString;
}

function getCompleteData(value) {
    var json = parse.realData(value);

    if (json.state !== 10001) {
        common.reportLog(1, +deviceData.dev_id, '接收蓝牙指令转化json：' + JSON.stringify(json));
    } //响应进行确认数据

    if (json.response == 1) {
        app.globalData.reponseData = json;
    } //上次操作未确认 发送取消指令

    json = cancleConfirm(json); //汇报进行确认数据

    json = reportConfirm(json, value); //获取电柜信息

    json = getCabintInfo(json);
    return json;
} //上次操作未确认 发送取消指令

function cancleConfirm(json) {
    if (json.response === 1) {
        app.globalData.reportData = json;
    }

    return json;
} //汇报进行确认数据

function reportConfirm(json, value) {
    if (json.report == 1) {
        var reportData = {};
        reportData.serialNo = json.serialNo;
        reportData.state = json.state;
        reportData.msg = json.msg;
        reportData.report = 1;
        app.globalData.reportData = reportData;

        if (value[2] === 0x82) {
            parse.reportCabintHire(deviceData.dev_id, json.orderNo, json);
            sendConfirmCommandBlue([0x02, 0x02], json.serialNo);
        }

        if (value[2] === 0x81) {
            parse.reportCabintExchange(deviceData.dev_id, json);
            sendConfirmCommandBlue([0x01, 0x02], json.serialNo);
        }

        if (value[2] === 0x83) {
            parse.reportCabintReturn(deviceData.dev_id, json.orderNo, json);
            sendConfirmCommandBlue([0x03, 0x02], json.serialNo);
        }
    }

    return json;
}

function sendConfirmCommandBlue(value, serialNum) {
    const bluetooth = require('../bluetooth.js');

    if (bluetooth.isConnected(deviceData.mac_id)) {
        bluetooth.sendConfirmCommand(
            deviceData.mac_id,
            value,
            serialNum,
            function () {},
            function () {}
        );
    } else {
    }
} //获取电柜信息 蓝牙超时三次请求操作

function getCabintInfo(json) {
    if (json.command === 0x86) {
        if (json.state === 10000) {
            isStart = 3;
        } else {
            if (isStart === 1) {
                setTimeout(function () {
                    if (isStart !== 3) {
                        isStart = 0;

                        if (timeOut < 3) {
                            //超时次数
                            timeOut++;
                            sendGetCabinetInfoCommand(deviceData);
                        } else {
                            json.state = 10002; //失败

                            timeOut = 0;
                        }
                    }
                }, 1500);
            }

            isStart = 2;
        }
    }

    return json;
}

module.exports = {
    readServiceID: readServiceID,
    readID: readID,
    writeServiceID: writeServiceID,
    writeID: writeID,
    MTU: MTU,
    acceptDevice: acceptDevice,
    sendGetCabinetInfoCommand: sendGetCabinetInfoCommand,
    isDevice: isDevice,
    sendHireCommand: sendHireCommand,
    sendBackCommand: sendBackCommand,
    sendExchangeCommand: sendExchangeCommand,
    sendConfirmCommand: sendConfirmCommand,
    sendCancelCommand: sendCancelCommand,
    // alterConnect: alterConnect,
    readData: readData,
    isSingleBt: isSingleBt
};
