/* eslint-disable no-unused-vars */
import { Message } from "element-ui";
import { encryptDes, getUuid, sha1_to_base64 } from "./des.js";
import { getToken, setToken } from "@/utils/auth";
class socketClient {
  wsUrl = "";
  wsAuto = {};
  websocket = null;
  heartBeatTimer = null;
  lockReconnect = false;
  errTimer = null;
  isLoad = true;
  constructor(wsUrl, wsAuto) {
    this.wsUrl = wsUrl;
    this.wsAuto = wsAuto;
  }
  // 初始化socket
  initWebSocket () {
    console.log("========= 初始化socket ===========");
    return new Promise((resolve, reject) => {
      this.websocket = new WebSocket(this.wsUrl);
      console.log("========= create websocket ===========");
      this.wsOpen().then((res) => {
        this.isLoad = true;
        console.log("========= onopen websocket ===========", res);
        this.wsSend(this.wsAuto);
        console.log("========= 授权完成 ===========");
        this.lockReconnect = true;
        resolve(true)
        if (this.isLoad == true) {
          Message({
            message: "客户端连接成功",
            type: "success",
            duration: 5 * 1000,
          });
        }
        // this.heartBeat();
      });
      this.websocket.onerror = (evt) => {
        console.log("========= 连接错误 ===========", evt);
        this.wsReconnect();
      };

      this.websocket.onclose = (evt) => {
        if (this.isLoad == true) {
          Message({
            message: "客户端断开连接",
            type: "error",
            center: true,
            duration: 5 * 1000,
          });
        }
        this.isLoad = false;
        this.lockReconnect = false;
        console.log("========= 客户端断开连接 ===========", evt);
        this.wsReconnect();
      };

    })
  }
  // 重新连接
  wsReconnect () {
    console.log("========= 客户重新连接 ===========");
    if (this.heartBeatTimer) clearInterval(this.heartBeatTimer);
    if (this.errTimer) clearTimeout(this.errTimer);
    if (this.lockReconnect) return;
    let that = this;
    this.errTimer = setTimeout(() => {
      that.initWebSocket();
    }, 1000);
  }
  heartBeat () {
    this.lockReconnect = false;
    if (this.heartBeatTimer) clearInterval(this.heartBeatTimer);
    const wsToken = getToken();
    // if (wsToken) {
    //   this.heartBeatTimer = setInterval(() => {
    //     const heatBeat = `{ MN: "Heart", Token: wsToken }`;
    //     this.wsSend(heatBeat);
    //   }, 20000);
    // }
  }
  // 打开连接
  wsOpen () {
    if (this.websocket) {
      return new Promise((resolve, reject) => {
        try {
          this.websocket.onopen = (evt) => {
            resolve(evt);
          };
        } catch (err) {
          this.$message.error('连接已经关闭，正在重新连接中...');
          reject(err);
        }
      });
    }
  }
  // 关闭连接
  wsClose () {
    if (this.websocket) {
      this.websocket.close();
      return new Promise((resolve, reject) => {
        try {
          this.websocket.onclose = (evt) => {
            this.$message.error('客户端断开连接');
            console.log("========= 客户端断开连接 ===========", evt);
            resolve(evt);
          };
        } catch (err) {
          reject(err);
        }
      });
    }
  }
  // 监听消息
  wsMessage (callback) {
    // 需要监听的消息路径
    if (this.websocket) {
      try {
        this.websocket.onmessage = (evt) => {
          // 判断是否有 data 数据
          if (evt.data) {
            let data = evt.data;
            if (this.isJsonString(data)) {
              callback(JSON.parse(data));
            }
          }
        };
      } catch (err) {
        callback(err);
      }
    }
  }
  // 发送消息
  wsSend (options, isFile = false) {
    if (this.websocket && this.websocket.readyState === 1) {
      try {
        if (isFile) {
          let params = { ...options };
          params.RequestId = getUuid();
          this.websocket.send(params);
        } else {
          this.websocket.send(JSON.stringify(options));
        }
      } catch (e) {
        Message({
          message: e.message,
          type: "error",
          duration: 5 * 1000,
        });
      }
    }
  }
  // 连接因错误而关闭时触发
  wsOnerror () {
    if (this.websocket) {
      return new Promise((resolve, reject) => {
        try {
          this.websocket.onerror = (evt) => {
            resolve(evt);
          };
        } catch (err) {
          reject(err);
        }
      });
    }
  }
  // 判断是否是json字符串
  isJsonString (str) {
    try {
      if (typeof JSON.parse(str) == "object") {
        return true;
      }
    } catch (e) {
      console.log("isJsonString:错误捕获");
    }
    return false;
  }
}

export { socketClient };
