//\公司文件\项目\GPS服务\16D、信驰达低功耗蓝牙(BLE)模块及协议 v5.10u_(RS02A1-B)191230.pdf
const common = require('../common.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';
var readPart = '';

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

var curTime = 0;

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

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 readData(device, value, data) {
    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;
    }
} // function readData(device, value, data) {
//   value = Array.from(new Int8Array(value)).map(p => String.fromCharCode(p)).join('')
//   if (value[value.length - 1] == ')') {
//     value = readPart.concat(value)
//     readPart = ''
//   } else if (value[0] == '(') {
//     readPart = value
//   } else {
//     readPart = readPart.concat(value)
//   }
//   if (value[0] == '(' && value[value.length-1] == ')') {
//     value = value.slice(1, value.length-1)
//     if (value.slice(0, 12) == device.mac_id) {
//       console.log(value)
//       value = value.slice(12, value.length)
//       switch (value.slice(0, 4)) {
//         case 'BP00':
//           return readDataBP00(value.slice(4, value.length), data)
//       }
//     }
//   }
//   return false
// }
// function stateUpdate(device, deviceId) {
//   var data = '(' + device.mac_id + 'AU20)'
//   console.log(data)
//   return [data.split('').map(p => p.charCodeAt(0))]
// }
// function turnOn(device, deviceId) {
//   var data = '(' + device.mac_id + 'AV011)'
//   console.log(data)
//   console.log([data.split('').map(p => p.charCodeAt(0))])
//   return [data.split('').map(p => p.charCodeAt(0))]
// }
// function turnOff(device, deviceId) {
//   var data = '(' + device.mac_id + 'AV010)'
//   console.log(data)
//   return [data.split('').map(p => p.charCodeAt(0))]
// }

function stateUpdate(device, deviceId) {
    console.log('读电压');
    curTime = 0;
    return [sendCommand(0x04)];
}

function turnOn(device, deviceId) {
    console.log('通电');
    return [sendCommand(0x03, [0xaa])];
}

function turnOff(device, deviceId) {
    console.log('断电');
    return [sendCommand(0x03, [0xbb])];
} // 鉴权

function alterConnect(device, deviceId) {
    return [sendCommand(0x01, [0xab, 0xcd, 0xab, 0xcd])];
}

function sendCommand(cmd, data = []) {
    data = [cmd, data.length].concat(data);
    return common.completArrayCRC(data, data.length);
}

function bmsInfo(device, deviceId, info) {
    return {
        state: {
            soc: 0,
            voltageAll: info.voltage ? info.voltage : 0,
            tempCount: info.temp ? 1 : 0,
            temp: info.temp ? [info.temp] : []
        },
        state_v2: [
            {
                class: '',
                class_eng: '',
                icon: 0,
                vars: [
                    {
                        label: '总电压',
                        label_eng: 'voltageAll',
                        name: '',
                        type: 'readonly',
                        value: info.voltage || info.voltage == 0 ? info.voltage + 'V' : '未知'
                    },
                    {
                        label: '充电保护',
                        label_eng: '',
                        name: '',
                        type: 'readonly',
                        value: info.chargeProtectState == 0 ? '正常' : info.chargeProtectState == 1 ? '异常' : '未知'
                    },
                    {
                        label: '放电保护',
                        label_eng: '',
                        name: '',
                        type: 'readonly',
                        value: info.dischargeProtectState == 0 ? '正常' : info.dischargeProtectState == 1 ? '异常' : '未知'
                    },
                    {
                        label: '电池超温',
                        label_eng: '',
                        name: '',
                        type: 'readonly',
                        value: info.highTempProtectState == 0 ? '正常' : info.highTempProtectState == 1 ? '异常' : '未知'
                    },
                    {
                        label: '电池温度',
                        label_eng: '',
                        name: '',
                        type: 'readonly',
                        value: info.temp || info.temp == 0 ? info.temp + '°C' : '未知'
                    },
                    {
                        label: '电池低温保护',
                        label_eng: '',
                        name: '',
                        type: 'readonly',
                        value: info.lowTempProtectState == 0 ? '正常' : info.lowTempProtectState == 1 ? '异常' : '未知'
                    },
                    {
                        label: '充放电状态',
                        label_eng: '',
                        name: '',
                        type: 'readonly',
                        value: info.chargeState == 1 ? '充电' : info.chargeState == 2 ? '放电' : '静止'
                    },
                    {
                        label: '循环次数',
                        label_eng: '',
                        name: '',
                        type: 'readonly',
                        value: info.cycle || info.cycle == 0 ? info.cycle + '次' : '未知'
                    }
                ]
            }
        ],
        btsets: [
            {
                class: '高低温保护阀值',
                name: 'AU10',
                vars: [
                    {
                        label: '低温保护阀值',
                        name: 'AU100',
                        type: 'number',
                        value: ''
                    },
                    {
                        label: '高温保护阀值',
                        name: 'AU101',
                        type: 'number',
                        value: ''
                    }
                ]
            },
            {
                class: '充放电保护电压',
                name: 'AU12',
                vars: [
                    {
                        label: '充电保护电压',
                        name: 'AU120',
                        type: 'number',
                        value: ''
                    },
                    {
                        label: '放电保护电压',
                        name: 'AU121',
                        type: 'number',
                        value: ''
                    }
                ]
            },
            {
                class: '充放电保护开关',
                name: 'AU13',
                vars: [
                    {
                        label: '充电保护',
                        name: 'AU130',
                        type: 'radio',
                        option: [
                            {
                                label: '关闭',
                                value: '0'
                            },
                            {
                                label: '开启',
                                value: '1'
                            }
                        ],
                        value: ''
                    },
                    {
                        label: '放电保护',
                        name: 'AU131',
                        type: 'radio',
                        option: [
                            {
                                label: '关闭',
                                value: '0'
                            },
                            {
                                label: '开启',
                                value: '1'
                            }
                        ],
                        value: ''
                    }
                ]
            },
            {
                class: '充放电保护恢复电压',
                name: 'AU14',
                vars: [
                    {
                        label: '充电保护恢复电压',
                        name: 'AU140',
                        type: 'number',
                        value: ''
                    },
                    {
                        label: '放电保护恢复电压',
                        name: 'AU141',
                        type: 'number',
                        value: ''
                    }
                ]
            },
            {
                class: '高低温保护恢复值',
                name: 'AU15',
                vars: [
                    {
                        label: '低温保护恢复值',
                        name: 'AU150',
                        type: 'number',
                        value: ''
                    },
                    {
                        label: '高温保护恢复值',
                        name: 'AU151',
                        type: 'number',
                        value: ''
                    }
                ]
            },
            {
                class: '电池循环次数',
                name: 'AU16',
                vars: [
                    {
                        label: '循环次数',
                        name: 'AU160',
                        type: 'number',
                        value: ''
                    }
                ]
            },
            {
                class: 'BMS自动保护开关',
                name: 'AU17',
                vars: [
                    {
                        label: '自动保护',
                        name: 'AU170',
                        type: 'radio',
                        option: [
                            {
                                label: '关闭',
                                value: '0'
                            },
                            {
                                label: '开启',
                                value: '1'
                            }
                        ],
                        value: ''
                    }
                ]
            }
        ]
    };
}

function bmsSet(device, deviceId, name, vars) {
    var data = '';

    switch (name) {
        case 'AU10':
            if (
                vars['AU100'] &&
                !isNaN(parseInt(vars['AU100'])) &&
                Math.abs(parseInt(vars['AU100'])) < 1000 &&
                vars['AU101'] &&
                !isNaN(parseInt(vars['AU101'])) &&
                Math.abs(parseInt(vars['AU101'])) < 1000
            ) {
                data =
                    (parseInt(vars['AU100']) < 0 ? '-' : '+') +
                    ('000' + Math.abs(parseInt(vars['AU100']))).substr(String(Math.abs(parseInt(vars['AU100']))).length) +
                    (parseInt(vars['AU101']) < 0 ? '-' : '+') +
                    ('000' + Math.abs(parseInt(vars['AU101']))).substr(String(Math.abs(parseInt(vars['AU101']))).length);
            }

            break;

        case 'AU12':
            if (
                vars['AU120'] &&
                !isNaN(parseFloat(vars['AU120'])) &&
                parseFloat(vars['AU120']) >= 0 &&
                parseInt(parseFloat(vars['AU120']) * 100) < 0x10000 &&
                vars['AU121'] &&
                !isNaN(parseFloat(vars['AU121'])) &&
                parseFloat(vars['AU121']) >= 0 &&
                parseInt(parseFloat(vars['AU121']) * 100) < 0x10000
            ) {
                data = (
                    ('0000' + parseInt(parseFloat(vars['AU120']) * 100).toString(16)).substr(parseInt(parseFloat(vars['AU120']) * 100).toString(16).length) +
                    ('0000' + parseInt(parseFloat(vars['AU121']) * 100).toString(16)).substr(parseInt(parseFloat(vars['AU121']) * 100).toString(16).length)
                ).toUpperCase();
            }

            break;

        case 'AU13':
            if (
                vars['AU130'] &&
                (parseInt(vars['AU130']) == 0 || parseInt(vars['AU130']) == 1) &&
                vars['AU131'] &&
                (parseInt(vars['AU131']) == 0 || parseInt(vars['AU131']) == 1)
            ) {
                data = parseInt(vars['AU130']).toString() + parseInt(vars['AU131']).toString();
            }

            break;

        case 'AU14':
            if (
                vars['AU140'] &&
                !isNaN(parseFloat(vars['AU140'])) &&
                parseFloat(vars['AU140']) >= 0 &&
                parseInt(parseFloat(vars['AU140']) * 100) < 0x10000 &&
                vars['AU141'] &&
                !isNaN(parseFloat(vars['AU141'])) &&
                parseFloat(vars['AU141']) >= 0 &&
                parseInt(parseFloat(vars['AU141']) * 100) < 0x10000
            ) {
                data = (
                    ('0000' + parseInt(parseFloat(vars['AU140']) * 100).toString(16)).substr(parseInt(parseFloat(vars['AU140']) * 100).toString(16).length) +
                    ('0000' + parseInt(parseFloat(vars['AU141']) * 100).toString(16)).substr(parseInt(parseFloat(vars['AU141']) * 100).toString(16).length)
                ).toUpperCase();
            }

            break;

        case 'AU15':
            if (
                vars['AU150'] &&
                !isNaN(parseInt(vars['AU150'])) &&
                Math.abs(parseInt(vars['AU150'])) < 1000 &&
                vars['AU151'] &&
                !isNaN(parseInt(vars['AU151'])) &&
                Math.abs(parseInt(vars['AU151'])) < 1000
            ) {
                data =
                    (parseInt(vars['AU150']) < 0 ? '-' : '+') +
                    ('000' + Math.abs(parseInt(vars['AU150']))).substr(String(Math.abs(parseInt(vars['AU150']))).length) +
                    (parseInt(vars['AU151']) < 0 ? '-' : '+') +
                    ('000' + Math.abs(parseInt(vars['AU151']))).substr(String(Math.abs(parseInt(vars['AU151']))).length);
            }

            break;

        case 'AU16':
            if (vars['AU160'] && !isNaN(parseInt(vars['AU160'])) && parseInt(vars['AU160']) >= 0 && parseInt(vars['AU160']) < 0x10000) {
                data = ('0000' + parseInt(vars['AU160']).toString(16)).substr(parseInt(vars['AU160']).toString(16).length).toUpperCase();
            }

            break;

        case 'AU17':
            if (vars['AU170'] && (parseInt(vars['AU170']) == 0 || parseInt(vars['AU170']) == 1)) {
                data = parseInt(vars['AU170']).toString() + parseInt(vars['AU170']).toString();
            }

            break;
    }

    if (data) {
        data = '(' + device.mac_id + name + data + ')';
        console.log(data);
        return [data.split('').map((p) => p.charCodeAt(0))];
    }

    return false;
}

module.exports = {
    readServiceID: readServiceID,
    readID: readID,
    writeServiceID: writeServiceID,
    writeID: writeID,
    acceptDevice: acceptDevice,
    isDevice: isDevice,
    readData: readData,
    alterConnect: alterConnect,
    stateUpdate: stateUpdate,
    turnOn: turnOn,
    turnOff: turnOff,
    bmsInfo: bmsInfo,
    bmsSet: bmsSet
};
