<template>
  <div>
    <a-table
      :columns="columns"
      :data-source="data"
      :scroll="{ x: 1500, y: 300 }"
    >
    </a-table>
  </div>
</template>
<script>
const columns = [
  {
    title: "报警日期",
    width: 150,
    dataIndex: "date",
    key: "name",
    fixed: "left",
  },
  {
    title: "报警时间",
    width: 100,
    dataIndex: "time",
    key: "age",
    fixed: "left",
  },
  { title: "报警类型", dataIndex: "alarmType", key: "1", width: 150 },
  { title: "报警信息", dataIndex: "message", key: "2", width: 150 },
  { title: "报警值", dataIndex: "alarmValue", key: "3", width: 150 },
  { title: "解决时间", dataIndex: "solvedTime", key: "4", width: 150 },
  { title: "备注", dataIndex: "remark", key: "5", width: 150 },
];

export default {
  name: "AlarmMsg",
  data() {
    return {
      data: [],
      alarmStatisticWebsocketUrl: "ws://106.12.123.152:8080/ws/alarmstati",
      getHistroyUrl: "https://service-j79v4brc-1301774019.gz.apigw.tencentcs.com/release/helloworld-1640223752",
      columns,
    };
  },
  methods: {
    alarmSocket() {
      if (typeof WebSocket === "undefined") {
        alert("您的浏览器不支持socket");
      } else {
        this.socket = new WebSocket(this.alarmStatisticWebsocketUrl);
        this.socket.onopen = this.open;
        this.socket.onerror = this.error;
        this.socket.onmessage = this.getAlarmMessage;
      }
    },
    open() {
      console.log("socket连接成功");
    },
    error() {
      console.log("连接错误");
    },
    getAlarmMessage(msg) {
      let item = JSON.parse(msg.data);
      console.log("接收到来自服务器的消息：", item.data);
      if (item.error_code === 0) {
        console.log(item.data);
        let date = new Date();
        this.data.unshift({
          date: `${date.getFullYear()}年${
            date.getMonth() + 1
          }月${date.getDate()}日`,
          time: `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`,
          alarmType: this.getAlarmType(item.data.alarm_type_code),
          message: item.data.message,
          alarmValue: item.data.alarm_value,
          solvedTime: item.data.solved_time || "未解决",
          remark: item.data.remark,
        });
      }
    },
    getAlarmType(code) {
      const TYPES = [
        "业务-一般",
        "业务-中等",
        "业务-严重",
        "系统-一般",
        "系统-中等",
        "系统-严重",
      ];
      let i;
      if (typeof code === "number") {
        i = code;
      } else if (typeof code === "string") {
        i = parseInt(code);
      }
      return TYPES[code] || "未知错误";
    },
    close() {
      console.log("socket已经关闭");
    },
    async setHistory() {
      await fetch(this.getHistroyUrl)
        .then((result) => result.json())
        .then((result) => {
          if(result.error_code === 0){
            this.data = result.data;
          }
        })
    },
  },
  mounted() {
    this.setHistory();
    this.alarmSocket();
  },
};
</script>
<style scoped>
</style>