import {
  ElMessage
} from "element-plus";
const WEB_SOCKET_URL = "ws://127.0.0.1:36107"

const bl = async (L) => {
  var l = "";
  for (let i = 0; i < L; i++) {
    l = l + "0";
  }
  return l;
}

//计算body长度
const sendlen = async (str) => {
  var s = 0;
  for (var i = 0; i < str.length; i++) {
    if (str.charAt(i).match(/^[\u4e00-\u9fa5]+$/)) {
      s += 3;
    } else {
      s++;
    }
  }
  s = String(s);
  var l = s.length;
  var L = 10 - l;
  var bodylen = await bl(L) + s;
  return bodylen;
}

const xmlStrToXmlObj = async (xmlStr) => {
  var xmlObj = {};
  if (document.all) {
    var xmlDom = new ActiveXObject("Microsoft.XMLDOM");
    xmlDom.loadXML(xmlStr);
    xmlObj = xmlDom;
  } else {
    xmlObj = new DOMParser().parseFromString(xmlStr, "text/xml");
  }
  return xmlObj;
}

const xmlObjToJsonObj = (xmlNodes) => {
  var obj = {};
  if (xmlNodes.length == 0) {
    obj = "";
  } else {
    for (var i = 0; i < xmlNodes.length; i++) {
      var node = xmlNodes[i];
      if (typeof node.tagName == "undefined" || node.nodeName == "#text") {
        obj = node.nodeValue;
      } else {
        var key = node.tagName;
        var value = xmlObjToJsonObj(node.childNodes);
        obj[key] = value;
      }
    }
  }
  return obj;
}

// xml数据格式转换
const xmlStrToJsonObj = async (xmlStr) => {
  const xmlObj = await xmlStrToXmlObj(xmlStr);
  let jsonObj = {};
  if (xmlObj.childNodes.length > 0) {
    jsonObj = await xmlObjToJsonObj(xmlObj.childNodes);
  }
  return jsonObj;
}

// 建立webSokect连接
const webSokect = async (randSign, webSocketUrl) => {

  if (!randSign || !webSocketUrl) {
    return {
      result: false
    }
  }

  return new Promise(async (resolve, reject) => {

    const bodyx =
      `<body><plain><info><random>${randSign}</random></info></plain></body>`;
    const bodylen = await sendlen(bodyx);

    //套接字单点登录
    const ws = new WebSocket(webSocketUrl);

    ws.onopen = async function (event) {
      ws.send(
        "<head><bsid>   ml0305c</bsid><bodylen>" +
        bodylen +
        "</bodylen><digest_id>                    </digest_id><cipher_id>                    </cipher_id></head>" +
        bodyx +
        ""
      );
    };

    // websokect 错误处理
    ws.onerror = async (event) => {
      reject(new Error("websokect连接错误"))
    };


    ws.onmessage = async function (event) {
      let resStr = event.data;

      //在外面包了一层他反过来的结构不标准
      resStr = `<cush>${resStr}</cush>`;
      const jsonObj = await xmlStrToJsonObj(resStr);
      const {
        errcode,
        appendix,
        errstr
      } = jsonObj.cush.body.plain || {}

      if (errcode == "0") {
        resStr = appendix
      } else {
        ElMessage.error(errstr)
        reject(new Error("onmessage响应，errorCode命中"))
      }

      if ("generate random2 error" == resStr) {
        reject(new Error("generate random2 error"))

      } else {
        //要求后进行验证
        resolve({
          result: true,
          params: {
            challenge: randSign,
            ticket: resStr
          }
        })
      }
    };
  })
}



/**
 * 卫士通验证
 */
const wstVaildate = async (randSign) => {
  return webSokect(randSign, WEB_SOCKET_URL)

}

export default wstVaildate