<template>
  <div class="device-run-starts-wrap">
    <!-- <el-button @click="closeDevcieData" type="danger">清空设备所有数据</el-button> -->
    <div class="cmd-list" v-for="(doct, index) in cmdList" :key="index">
      <div class="cmd-title-wrap">
        <svg-icon
          icon-class="A_product1"
          style="margin-right: 2px; height: 20px; width: 20px"
        />分组名称：
        <span class="cmd-title">{{ doct.cmdName }}</span>
      </div>
      <div
        class="param-item2"
        v-for="(doctItem, indexs) in doct.children"
        :key="indexs"
      >
        <div class="title-top">
          <span class="name-wr">{{ doctItem.funName }}</span>
          <span class="type-wr" @click="handleShowData(doctItem)">查看</span>
        </div>
        <div class="value-info">
          <div class="value-wrap">
            <span
              class="val-span"
              v-text="
                doctItem.lastValue === null || doctItem.lastValue === undefined
                  ? '--'
                  : doctItem.lastValue
              "
            >
            </span>
          </div>
        </div>
        <div class="time-w">
          <span class="time-warp">{{ doctItem.unitName }}</span>
          <span
            class="time"
            v-text="doctItem.lastTime ? parseTime(doctItem.lastTime) : '--'"
          ></span>
        </div>
      </div>
    </div>

    <dialog-template
      title="查看数据"
      :visible="dialogShow"
      width="700px"
      :close-on-click-modal="false"
      @close="dialogCloseCell"
      @opened="dialogOpen"
    >
      <run-state-table
        slot="dialog-center"
        :dialogData="dialogData"
        :prodId="prodId"
        :pro_type="dialogData.funDataType"
        :dialogShow="dialogShow"
        :deviceKey="deviceInfo.deviceKey"
        ref="showChart"
      />
      <div slot="dialog-footer" class="dialog-footer">
        <el-button size="small" @click="dialogShow = false">关 闭</el-button>
      </div>
    </dialog-template>
  </div>
</template>
<script>
import { getDeviceFunList, getDeviceCmdList } from "@/api/iot/device";
import DialogTemplate from "@/components/DialogTemplate";
import { iotWebSocketBaseUrl } from "@/config/env";
import RunStateTable from "./runStateTable";
export default {
  name: "RunStartsWrap",
  props: ["prodId", "sourceId", "deviceInfo"],
  components: {
    RunStateTable,
    DialogTemplate
  },
  data() {
    return {
      cmdList: [],
      cmdObject: {},
      stompClient: null,
      deviceKey: "",
      socket_flag: true,
      dialogData: {},
      dialogShow: false,
      firstWsMassage: true,
    };
  },
  created() {
    this.getCmdList();
    // this.connection();
  },
  methods: {
    // 查看数据
    handleShowData(row) {
      row.chartDate = new Date();
      this.dialogData = row;
      this.dialogShow = true;
    },
    dialogOpen() {
      this.$refs.showChart.initDialog(this.dialogData);
    },
    dialogCloseCell() {
      this.dialogShow = false;
      this.$refs.showChart.close();
    },
    // 创建ws
    connection() {
      if (this.stompClient) {
        return;
      }
      if (!iotWebSocketBaseUrl) {
        return;
      }
      // let locahostUrl = 'ws://192.168.18.138/device/ws/dev/send/'
      let headers = {
        clientid: this.deviceInfo.wsClientId,
        username: this.deviceInfo.wsUsername,
        sign: this.deviceInfo.wsSign,
      };
      this.stompClient = new WebSocket(
        `${iotWebSocketBaseUrl}${headers.clientid}/${headers.username}/${headers.sign}`
      );
      this.stompClient.onmessage = this.socket_onmsg;
      this.stompClient.onclose = this.socket_onclose;
    },
    socket_onmsg(evt) {
      this.setListData(evt.data);
    },
    setListData(data) {
      this.recursionSet(this.cmdList, JSON.parse(data));
      this.firstWsMassage = false;
      this.$forceUpdate();
    },
    recursionSet(list, result) {
      for (var i = 0; i < list.length; i++) {
        if (this.firstWsMassage) {
          // result["cmd"] && list[i]['cmdKey'] === result["cmd"]
          // if (result["cmd"] && list[i]['cmdKey'] === result["cmd"]) {
          for (var v = 0; v < list[i].children.length; v++) {
            if (
              result.params[list[i].children[v]["funKey"]] !== null &&
              result.params[list[i].children[v]["funKey"]] !== undefined
            ) {
              list[i].children[v]["lastValue"] =
                result.params[list[i].children[v]["funKey"]];
              list[i].children[v]["lastTime"] = result.params["timestamp"]
                ? result.params["timestamp"]
                : "";
            }
          }
          // }
        } else {
          if (result["cmd"] && list[i]["cmdKey"] === result["cmd"]) {
            for (var v = 0; v < list[i].children.length; v++) {
              if (
                result.params[list[i].children[v]["funKey"]] !== null &&
                result.params[list[i].children[v]["funKey"]] !== undefined
              ) {
                (list[i].children[v]["lastValue"] =
                  result.params[list[i].children[v]["funKey"]]),
                  (list[i].children[v]["lastTime"] = result.params["timestamp"]
                    ? result.params["timestamp"]
                    : "");
              }
            }
            break;
          }
        }
      }
    },
    socket_onclose(e) {
      this.stompClient = null;
      if (this.socket_flag) {
        this.socket_flag = false;
        let self = this;
        setTimeout(function () {
          self.socket_flag = true;
          self.connection();
        }, 10000);
      }
    },
    forGetParmas(row, index) {
      const param = {
        cmdId: row.cmdId,
        deviceId: this.deviceInfo.deviceId,
        cmdKey: row.cmdKey,
        deviceKey: this.deviceInfo.deviceKey,
      };
      getDeviceFunList(param).then((res) => {
        row["children"] = res.data || [];
        this.$forceUpdate();
      });
    },
    lengthReSize(str) {
      if (str.toString().length < 18 && str.toString().length > 12) {
        return "font-size: 18px;";
      } else if (str.toString().length > 18) {
        return "font-size: 18px; white-space: nowrap; display: inline-block;width: 80%; overflow: hidden; text-overflow: ellipsis;";
      } else {
        return "";
      }
    },
    getCmdList() {
      const params = {
        deviceId: this.deviceInfo.deviceId,
        cmdType: "1",
      };
      getDeviceCmdList(params).then((response) => {
        this.cmdList = response.data;
      });
    },
    closeWebscoket() {
      this.stompClient = null;
    },
  },
  destroyed() {
    this.closeWebscoket();
  },
  watch: {
    cmdList(val) {
      if (val) {
        val.forEach((v, index) => {
          this.forGetParmas(v, index);
        });
        setTimeout(this.connection, 3000);
        // this.connection()
      }
    },
  },
};
</script>-
<style lang="scss">
.device-run-starts-wrap {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  overflow: auto;
  padding: 10px;
  .el-button--medium {
    position: absolute;
    right: 30px;
  }
  .cmd-list {
    width: 100%;
    /* height: auto; */
    display: flex;
    flex-wrap: wrap;
    cursor: default;
    padding: 10px;
    .cmd-title-wrap {
      width: 100%;
      display: flex;
      // border-bottom: 1px solid #bdb7b7;
      height: 35px;
      font-size: 16px;
      align-items: center;
      .cmd-title {
        font-size: 14px;
        color: #a9a6a6;
        font-size: 16px;
        color: #f35151;
        letter-spacing: 1px;
      }
    }
    .param-item {
      height: 130px;
      // border: 1px solid #777474;
      width: 250px;
      display: flex;
      flex-wrap: wrap;
      margin-right: 10px;
      margin-top: 10px;
      border-radius: 2px;
      padding: 10px;
      justify-content: start;
      align-items: start;
      margin: 0;
      margin-left: 15px;
      margin-top: 15px;
      box-shadow: 0px 0px 3px 0px #b7b4b4;
      .title-top {
        height: 30px;
        display: flex;
        align-items: flex-end;
        width: 100%;
        border-bottom: 1px dotted #c5c3c3;
        padding-bottom: 3px;
        justify-content: space-between;
        .name-wr {
          font-size: 18px;
          color: #1890ff;
        }
        .type-wr {
          font-size: 14px;
          color: #1890ff;
        }
      }
      .value-info {
        height: 55px;
        display: flex;
        margin-top: 5px;
        align-items: center;
        width: 100%;
        .value-wrap {
        }
        .val-span {
          color: #03a9f4;
          font-size: 20px;
          width: 280px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          display: inline-block;
        }
      }

      .time-w {
        margin-top: 5px;
        font-size: 14px;
        width: 100%;
        display: flex;
        justify-content: space-between;
        color: #908c8c;
      }
    }
    .param-item2 {
      height: 150px;
      width: 300px;
      display: flex;
      flex-wrap: wrap;
      border-radius: 0px;
      padding: 10px;
      justify-content: start;
      align-items: start;
      margin: 0;
      border: 1px solid #b7b4b4;
      margin-left: -1px;
      margin-top: -1px;
      .title-top {
        height: 30px;
        display: flex;
        align-items: flex-end;
        width: 100%;
        border-bottom: 1px dotted #c5c3c3;
        padding-bottom: 3px;
        justify-content: space-between;
        .name-wr {
          font-size: 18px;
          // color: #1890ff;
        }
        .type-wr {
          font-size: 14px;
          // color: #606266;
          color: #1890ff;
        }
        .type-wr:hover {
          color: #1890ff;
          cursor: pointer;
        }
      }
      .value-info {
        height: 55px;
        display: flex;
        margin-top: 5px;
        align-items: center;
        width: 100%;
        .value-wrap {
        }
        .val-span {
          color: #03a9f4;
          font-size: 20px;
          width: 280px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          display: inline-block;
        }
      }

      .time-w {
        margin-top: 5px;
        font-size: 14px;
        width: 100%;
        display: flex;
        justify-content: space-between;
        color: #908c8c;
      }
    }
  }
}
.device-run-state-dailog {
  .el-dialog__header {
    border-bottom: 1px solid #b6b6b6;
  }
  .el-dialog__footer {
    border-top: 1px solid #b6b6b6;
    padding-bottom: 10px;
  }
}
</style>
