// #ifdef APP
import ecUI from '@/utils/ecUI.js'
import ecBLE from '@/utils/ecBLE/ecBLE.js'
// #endif
// #ifdef MP
const ecUI = require('@/utils/ecUI.js')
const ecBLE = require('@/utils/ecBLE/ecBLE.js')
// #endif
const deviceTool = {
    //
    startCharge(port){
        let arr = [85,104,3,1,80,195,127];
        if(port == 2){
            arr = [85,104,3,2,80,195,128];
        }
        sendData(arr)
    },
    stopCharge(port){
        let arr = [85,105,1,1,107];
        if(port == 2){
            arr = [85,105,1,2,108];
        }
        sendData(arr)
    },
    sendPortDetailCmd(){
        let arr = [85,103,1,0,104];
        sendData(arr)
    },

    sendMainboardCmd(){
        let arr = [85,96,1,0];
        addLast(arr);
        sendData(arr)
    },

    restart(){
        let arr = [85,117,1,0,118];
        sendData(arr)
    },
    reset(){
        let arr =  [85,98,1,0,99];
        sendData(arr)
    },
    plan(port,time){
        let moneyArr = decToCmd(500);
        let one = 0,two = 0;
        if(moneyArr.length == 1){
            one = 0;
            two = moneyArr[0];
        }else{
            one = moneyArr[0];
            two = moneyArr[1];
        }
        let first = 0,second = 0;
        let timeArr = decToCmd(time);
        if(timeArr.length == 1){
            first = 0;
            second = timeArr[0];
        }else{
            first = timeArr[0];
            second = timeArr[1];
        }
        let arr = [85,104,5,port,two,one,second,first];
        addLast(arr);
        sendData(arr)
    },
    cancelPlan(port){
        let cmdKey;
        if(port == 1){
            cmdKey = [85,115,2,1,0,118];
        }else if(port == 2){
            cmdKey = [85,115,2,2,0,119];
        }
        sendData(cmdKey);
    },
    setCurrent(current){
        let currentArr = decToCmd(current);
        let one = 0,two = 0;
        if(currentArr.length == 1){
            one = 0;
            two = currentArr[0];
        }else{
            one = currentArr[0];
            two = currentArr[1];
        }
        let arr = [85,97,19,1,8,244,1,231,3,0,208,32,7,9,5,22,8,5,one,two,1,1];
        addLast(arr)
        sendData(arr)
    },
    getPwd(){
        let arr =  [85,172,0,172];
        sendData(arr)
    },
    setPwd(pwd){
        let arr = [85,204,6];
        for (let i = 0; i < pwd.length; i++) {
            arr.push(parseInt(pwd[i],10));
        }
        addLast(arr)
        sendData(arr)
    },
    getUUID(){
        let arr =  [85,253,0,253];
        sendData(arr)
    }

}
function addLast(arr){
    let total = 0;
    for(let i =1;i<arr.length;i++){
        const data =arr[i];
        total += data;
    }
    total = total.toString(2);
    if(total.length>8){
        let valueStrLen = total.length;
        total = total.substring(valueStrLen-8,valueStrLen);
    }
    total = parseInt(total,2)
    arr.push(total);
}
function sendData(arr){
    arr = changeArr(arr);
    let str = arr.join(" ");
    sendBlueData(str);
}

function changeArr(arr){
    const hexArr = arr.map(num => {
       let str = num.toString(16); // 将每个数字转换为16进制字符串
        if(str.length == 1){
            return "0"+str.toUpperCase();
        }else{
            return str.toUpperCase();
        }
    });
    return hexArr;
}

const dataParser = {
/**
 *     "data":[170,96,33,1,8,244,1,231,3,1,208,32,7,9,5,22,8,0,0,0,5,128,12,0,0,0,0,12,15,18,8,7,8,7,8,7,120]
 *     "real_data":{"card_avail":1,"peak_price":8,"cost":500,"time_limit":999,"fee_type":1,"max_power":8400,"peak_service_price":7,"volume":9,"bottom_price":5,"botton_end":22,"bottom_start":8,"qr_id_low":0,"qr_id_middle":0,"qr_id_high":0,"bottom_service_price":5,"max_current":3200,"cp_check_off":0,"fee_show_off":0,"time1_end":12,"time2_end":15,"time3_end":18,"time1_price":8,"time1_price_service":7,"time2_price":8,"time2_sercie_price":7,"time3_price":8,"time3_service_price":7},"type":96}
 */
    mainboard:'CARD_AVAIL\n' +
        'PEAK_PRICE\n' +
        'COST 2\n' +
        'TIME_LIMIT 2\n' +
        'FEE_TYPE\n' +
        'MAX_POWER 2\n' +
        'PEAK_SERVICE_PRICE\n' +
        'VOLUME\n' +
        'BOTTOM_PRICE\n' +
        'BOTTON_END\n' +
        'BOTTOM_START\n' +
        'QR_ID_LOW\n' +
        'QR_ID_MIDDLE\n' +
        'QR_ID_HIGH\n' +
        'BOTTOM_SERVICE_PRICE\n' +
        'MAX_CURRENT 2\n' +
        'XXX\n' +
        'XXX\n' +
        'CP_CHECK_OFF\n' +
        'FEE_SHOW_OFF\n' +
        'TIME1_END\n' +
        'TIME2_END\n' +
        'TIME3_END\n' +
        'TIME1_PRICE\n' +
        'TIME1_PRICE_SERVICE\n' +
        'TIME2_PRICE\n' +
        'TIME2_SERCIE_PRICE\n' +
        'TIME3_PRICE\n' +
        'TIME3_SERVICE_PRICE',
    portdetail:{
        single:'PORT_FIRST_STATUS\n' +
            'POWER 2\n' +
            'ELEC 2\n' +
            'MONEY 2\n' +
            'TIME 2',
        morlsingle:'PORT_FIRST_STATUS\n' +
            'POWER 2\n' +
            'ELEC 2\n' +
            'MONEY 2\n' +
            'TIME 2\n' +
            'VOLTAGE\n' +
            'DEV_TEMPER\n' +
            'WIRE_TEMPER',
        double:'PORT_FIRST_STATUS\n' +
            'POWER 2\n' +
            'ELEC 2\n' +
            'MONEY 2\n' +
            'TIME 2\n' +
            'PORT_SECOND_STATUS\n' +
            'POWER 2\n' +
            'ELEC 2\n' +
            'MONEY 2\n' +
            'TIME 2'
    }
}
function parseData(arr){
    if(!arr){
        return
    }
    let type = arr[1];
    let str = "";
    if(type == 96){//主板
         str = dataParser.mainboard;
    }
    if(type == 103){
      let len =  arr[2];
        if(len == 18){
            str = dataParser.portdetail.double;
        }
        if(len == 9){
            str = dataParser.portdetail.single;
        }
        if(len == 13){
            str = dataParser.portdetail.morlsingle;
        }
    }
    let obj = parseProp(arr,str);
    let data = {};
    data.type = type;
    data.real_data = obj;
   return data;
}
function parseProp(arr,str){
    let obj = {};
    let keys = str.split("\n")
    let index = 3;
    for (let i = 0; i < keys.length; i++) {
        let key = keys[i];
        let keyProps = key.split(" ");
        let num = 1;
        if(keyProps.length == 2){
            num = parseInt(keyProps[1],10);
        }
        let integers = [index,index+num-1];
        let datas = [];
        for (let j = integers[0]; j <= integers[integers.length-1]; j++) {
            datas.push(arr[j]);
        }
        let aLong = cmdToDec(datas);
        obj[keyProps[0].toLowerCase()] =  aLong;
        index+=num;
    }
    return obj;
}
/**
 * 将命令字符串转成十进制
 * @param cmds
 * @return
 */
function cmdToDec(cmds) {
  if (!cmds) {
    return -1;
  }
  let len = cmds.length;
  if (len === 1) {
    return cmds[0];
  } else if (len === 2) {
    let first = cmds[0];
    let second = cmds[1];
    let firstStr = addZero(first.toString(2));
    let secondStr = addZero(second.toString(2));
    let allStr = secondStr + firstStr;
    let i = parseInt(allStr, 2);
    return i;
  } else if (len === 4) {
    let first = cmds[0];
    let second = cmds[1];
    let third = cmds[2];
    let forth = cmds[3];
    let firstStr = addZero(first.toString(2));
    let secondStr = addZero(second.toString(2));
    let thirdStr = addZero(third.toString(2));
    let forthStr = addZero(forth.toString(2));
    let allStr = forthStr + thirdStr + secondStr + firstStr;
    let i = parseInt(allStr, 2);
    return i;
  }
  return 0;
}
function sendBlueData(tempSendData){
    let data = tempSendData
        .replace(/\s*/g, '')
        .replace(/\n/g, '')
        .replace(/\r/g, '')
    console.log("写入数据："+data);
    ecBLE.writeBLECharacteristicValue(data, true)
}
/**
 * 二进制补0
 * @param value
 * @return
 */
function addZero(value) {
  let len = value.length;
  if (len < 8) {
    for (let i = 0; i < 8 - len; i++) {
      value = "0" + value;
    }
  }
  return value;
}

/**
 * 将十进制值转成cmd格式
 * @param value
 * @return
 */
function decToCmd(value) {
  let cmds = null;
  if (value <= 255) { //两位
    cmds = [value];
  } else if (value <= 65535) {
    cmds = new Array(2);
    let valueStr = value.toString(2);
    let len = valueStr.length;
    let lastEight = valueStr.substring(len - 8, len);
    let firstEight = valueStr.substring(0, len - 8);
    cmds[0] = parseInt(lastEight, 2);
    cmds[1] = parseInt(firstEight, 2);
  } else {
    cmds = new Array(4);
    let valueStr = value.toString(2);
    let len = valueStr.length;
    let lastEight = valueStr.substring(len - 8, len);
    let firstEight = valueStr.substring(len - 16, len - 8);
    let secondEight = valueStr.substring(len - 24, len - 16);
    let thirdEight = valueStr.substring(0, len - 24);
    cmds[0] = parseInt(lastEight, 2);
    cmds[1] = parseInt(firstEight, 2);
    cmds[2] = parseInt(secondEight, 2);
    cmds[3] = parseInt(thirdEight, 2);
  }
  return cmds;
}
//parseData([170,103,18,1,0,0,54,5,0,0,0,0,2,241,25,67,3,75,0,77,0,159])
export function sendPortDetailCmd(){
    deviceTool.sendPortDetailCmd()
    return new Promise(resolve => {
        resolve()
    });
}
export function getMainboardConfig(){
    deviceTool.getMainboardConfig()
    return new Promise(resolve => {
        resolve()
    });
}

export function parseDataObj(data){
    data = data.trim();
    data = data.split(" ");
    console.log(data)
    let arr = [];
    for (let i = 0; i < data.length; i++) {
        arr.push(parseInt(data[i],16)) ;
    }
    return parseData(arr)
}
export function parsePwd(data){
    data = data.trim();
    data = data.split(" ");
    console.log(data)
    let pwd = "";
    for (let i = 3; i < 9; i++) {
        pwd = pwd+""+parseInt(data[i],16) ;
    }
    return pwd;
}
export function startCharge(obj){
    deviceTool.startCharge(obj.port);
    return new Promise(resolve => {
        resolve()
    });
}

export function planCharge(port,min){
    deviceTool.plan(port,min);
    return new Promise(resolve => {
        resolve()
    });
}

export function cancelPlan(port,min){
    deviceTool.cancelPlan(port);
    return new Promise(resolve => {
        resolve()
    });
}


export function stopCharge(obj){
    deviceTool.stopCharge(obj.port);
    return new Promise(resolve => {
        resolve()
    });
}

export function sendMainboardCmd(){
    deviceTool.sendMainboardCmd();
    return new Promise(resolve => {
        resolve()
    });
}
export function setCurrent(current){
    deviceTool.setCurrent(current);
    return new Promise(resolve => {
        resolve()
    });
}

export function reset(){
    deviceTool.reset();
    return new Promise(resolve => {
        resolve()
    });
}

export function restart(){
    deviceTool.restart();
    return new Promise(resolve => {
        resolve()
    });
}

export function setPwd(pwd){
    deviceTool.setPwd(pwd);
    return new Promise(resolve => {
        resolve()
    });
}

export function getPwd(){
    deviceTool.getPwd();
    return new Promise(resolve => {
        resolve()
    });
}
export function getUUID(){
    deviceTool.getUUID();
    return new Promise(resolve => {
        resolve()
    });
}

function test(){
   console.log( parseDataObj("AA 67 0D 05 00 00 00 00 00 00 00 00 00 25 E2 00 80"))
}
// test()

