<template>
  <div class="e-object-device-children-table">
    <div class="device-children-header">
      <div class="left-link-home" @click="handleLinkToHome">
        <icon class="iconfont iconfanhui_1"></icon>
        <span class="link-bt-title">返回</span>
      </div>
      <div class="lift-gateway-info">
        <span class="gateway-label">位置：</span>
        <span class="gateway-adders">{{
          gatewayDevice.deviceAddress || "--"
        }}</span>
        <span class="gateway-label">设备号：</span>
        <span class="gateway-did">{{ gatewayDevice.deviceId || "--" }}</span>
        <span class="gateway-label">在线状态：</span>
        <span
          :class="
            gatewayDevice.deviceState === 'ONLINE'
              ? 'gateway-stu'
              : 'gateway-stu off-line'
          "
        >
          {{ gatewayDevice.deviceState === "ONLINE" ? "在线" : "离线" }}
        </span>
      </div>
      <div class="right-operate">
        <div class="operate-refresh" @click="handleRefresh">
          刷新
        </div>
        <div :class="tableSelectList && tableSelectList.length > 0 ? 'operate-onekey-on' : 'operate-onekey-on but-disable'" @click="handleChildStatus('true')">
          一键合闸
        </div>
        <div :class="tableSelectList && tableSelectList.length > 0 ? 'operate-onekey-on' : 'operate-onekey-on but-disable'" @click="handleChildStatus('false')">
          一键分闸
        </div>
        <el-select v-model="queryParams.prodKey" style="margin-left: 5xp; width: 120px;" placeholder="请选择项目类型" size="small">
          <el-option
            v-for="dict in projectModelList"
            :key="dict.prodKey"
            :label="dict.modelName"
            :value="dict.prodKey"
            @change="getTableFilterList"
          ></el-option>
        </el-select>

      </div>
    </div>
    <div class="device-children-center">
      <e-dynamic-table
        :border="false"
        :loading="tableLoading"
        :tableTotal="0"
        :queryParams="queryParams"
        :tableList="tableList"
        :filterList="[...defaultFilterList, ...filterList]"
        :isIndex="true"
        :isSelect="true"
        rowKey="deviceId"
        @tableSelectionChange="handleTableChange"
        @handleQuery="handleQuery"
      >
        <template v-slot:operate="operate">
          <div>
            <span>{{ operate }}</span>
          </div>
        </template>
      </e-dynamic-table>
    </div>
  </div>
</template>
<script>
import EDynamicTable from "./EDynamicTable";
import { listProjectDevice, listProjectModel, listProjectTableFilter } from '@/api/iot/project_new'
import { setSwitchControl } from "@/api/iot/device";
import { webSocketProjectGatewayUrl } from "@/config/env";
export default {
  name: "EDeviceChildren",
  components: {
    EDynamicTable,
  },
  props: {
    gatewayDevice: {
      type: Object,
      require: true,
    },
    sourceId: {
      type: [String, Number],
      require: true,
    },
    deviceType: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      queryParams: {
        prodKey: undefined,
        pageNum: 1,
        pageSize: 10,
      },
      tableLoading: true,
      tableList: [],
      defaultFilterList: [
        {
          label: "线路名称",
          align: "center",
          prop: "deviceName",
          width: "150px"
        },
        {
          label: "型号",
          align: "center",
          prop: "modelName",
          width: "150px",
        },
      ],

      filterList: [],
      operate: {
        label: "操作",
        align: "left",
        prop: "operate",
        width: "200px",
        slot: true,
        slotName: "operate",
      },
      projectModelList: [],
      tableSelectList: [],
      stompClient: null,
      socket_flag: true,
      timeout_flag: null
    };
  },
  created() {
    this.tableLoading = true
    this.getProjectModelList()
  },
  methods: {
    handleLinkToHome() {
      this.$emit("handleLinkToHome");
    },
    // 处理数据 成为表格可用 列数据
    handleTableFilter(list) {
      var resultList = [];
      if (list && list.length > 0) {
        list.forEach(v => {
            resultList.push({
              label: v['unitName'] ? `${v['name']}(${v['unitName']})` : v['name'],
              align: "center",
              prop: v['key'],
              width: list.length > 5 ? '200px' : '',
            })
        });
      };
      return resultList;
    },
    // 获取 项目 型号列表
    getProjectModelList() {
      listProjectModel({
        projectId: this.sourceId,
        deviceTags: this.deviceType || '',
        pid: this.gatewayDevice.deviceId || ''
      }).then(res => {
        this.projectModelList = res.data
        if (this.projectModelList && this.projectModelList.length > 0) {
          this.queryParams.prodKey = this.projectModelList[0]['prodKey']
          this.getTableFilterList()
        };
      })
    },
    // 获取 子设备列表
    getTableFilterList() {
      this.filterList = []
      this.getChildrenDeviceList()
      listProjectTableFilter({
        prodKey: this.queryParams.prodKey
      }).then(res => {
        this.filterList = this.handleTableFilter(res.data)
        this.$forceUpdate()
        this.tableLoading = false
      })
    },
    // 查询 子设备列表数据---需要考虑到型号的问题
    getChildrenDeviceList() {
      this.tableList = []
      listProjectDevice(Object.assign({
        projectId: this.sourceId || '',
        deviceTags: this.deviceType || '',
        pid: this.gatewayDevice.deviceId || ''
      }, this.queryParams)).then(res => {
        this.tableList = res.data
        if (this.stompClient) {
          this.closeSocket()
        }
        this.connection()
      })
    },
    // 动态表格 返回的 勾选数据
    handleTableChange(e) {
      if (e && e.length > 0) {
        this.tableSelectList = e.map(v => v['deviceId'])
      } else {
        this.tableSelectList = []
      }
    },
    // 点击子设备 线路开关
    handleChildStatus(type) {
      this.$prompt("请输入登录密码", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^[a-z A-z 0-9 $.]+/,
        inputType: "password",
        inputErrorMessage: "登录密码不能为空",
      }).then(({ value }) => {
        let params = {
          data: {
            cmd: "set_switch",
            params: {
              switch: 1
            },
          },
          deviceId: '',
          verifyKey: value,
        };

        switch(type) {
          case 'true':
            params.data.params.switch = 1;
            params.deviceId = this.tableSelectList.toString();
            break;

          case 'false':
            params.data.params.switch = 0;
            params.deviceId = this.tableSelectList.toString();
            break;
        }

        setSwitchControl(params).then((res) => {
          this.msgSuccess("修改成功");
        });
      });
    },
    handleRefresh() {
      this.queryParams.pageNum = 1;
      this.getChildrenDeviceList()
    },
    // 表格 分页查询
    handleQuery(e) {
      this.queryParams = Object.assign(this.queryParams, e)
      this.getChildrenDeviceList()
    },
    // 处理 socket 数据返回 赋值问题
    handleDeviceInfo(param) {
      if (this.tableList && this.tableList.length > 0) {
        this.tableList = this.tableList.map(v => {
          if (v['deviceId'] === param['deviceId']) {
            return Object.assign(v, param)
          } else {
            return v
          }
         })
      }
    },
    // 创建一个ws 监听获取报警实时数据
    connection() {
      if (this.stompClient) {
        return;
      }
      if (!webSocketProjectGatewayUrl) {
        return;
      }
      if (!this.tableList || this.length <= 0) {
        return;
      }
      let deviceIds = this.tableList.map(v => v['deviceId'])
      this.stompClient = new WebSocket(
        `${webSocketProjectGatewayUrl}/${this.getGuid()}/${ deviceIds.toString() }`
      );
      this.stompClient.onmessage = this.socket_message;
      this.stompClient.onclose = this.socket_onclose;
    },
    socket_message(evt) {
      console.log("wsljcg:=", evt);
      const data = JSON.parse(evt.data);
      // this.actualEnergyCensus = data.params || {};
      console.log('socket-message:', data)
      this.handleDeviceInfo(data)
      this.$forceUpdate();
    },
    socket_onclose(e) {
      this.stompClient = null;
      if (this.socket_flag) {
        this.socket_flag = false;
        let _this = this;
        this.timeout_flag = setTimeout(function () {
          _this.socket_flag = true;
          _this.connection();
        }, 10000);
      }
    },
    closeSocket() {
      if (this.stompClient) {
        this.stompClient.close();
      }
      this.socket_flag = false;
      this.stompClient = null;
      clearTimeout(this.timeout_flag);
    },
    getGuid() {
      return "xxxxxxx_xxxxx_4xxx_yxxx_xxxxxxxxxxxx".replace(/[xy]/g, function(
        c
      ) {
        var r = (Math.random() * 16) | 0,
          v = c == "x" ? r : (r & 0x3) | 0x8;
        return v.toString(16);
      });
    },
  },
  destroyed() {
    this.closeSocket()
  }
};
</script>
<style lang="scss">
.e-object-device-children-table {
  width: 100%;
  height: 100%;
  .device-children-header {
    width: 100%;
    height: 50px;
    display: flex;
    align-items: center;
    .left-link-home {
      width: 60px;
      height: 30px;
      background: #f4f5f7;
      border-radius: 5px;
      font-size: 12px;
      font-family: Source Han Sans CN;
      font-weight: 400;
      color: #6b778c;
      display: flex;
      align-items: center;
      justify-content: center;
      .link-bt-title {
        margin-left: 5px;
      }
    }
    .lift-gateway-info {
      width: calc(100% - 420px);
      height: 100%;
      display: flex;
      align-items: center;
      padding-left: 10px;
      justify-content: space-around;
      .gateway-label {
        font-size: 14px;
        font-family: Source Han Sans CN;
        font-weight: 300;
        color: #6b778c;
        text-overflow: ellipsis;
        display: inline-block;
        white-space: nowrap;
        overflow: hidden;
      }
      .gateway-adders {
        font-size: 14px;
        font-family: Source Han Sans CN;
        font-weight: 300;
        color: #344567;
        width: calc(45% - 60px);
        text-overflow: ellipsis;
        display: inline-block;
        white-space: nowrap;
        overflow: hidden;
      }
      .gateway-did {
        font-size: 14px;
        font-family: Source Han Sans CN;
        font-weight: 300;
        color: #344567;
        width: calc(55% - 20% - 80px);
        text-overflow: ellipsis;
        display: inline-block;
        white-space: nowrap;
        overflow: hidden;
      }
      .gateway-stu {
        font-size: 14px;
        font-family: Source Han Sans CN;
        font-weight: 300;
        color: #009003;
        width: calc(18% - 80px);
        text-overflow: ellipsis;
        display: inline-block;
        white-space: nowrap;
        overflow: hidden;
      }
      .off-line {
        color: #ff0000;
      }
    }
    .right-operate {
      width: 350px;
      display: flex;
      justify-content: flex-end;
      font-weight: 400;
      color: #344567;
      font-size: 12px;
      font-family: Source Han Sans CN;
      cursor: default;
      .operate-refresh {
        width: 60px;
        height: 30px;
        background: #F4F5F7;
        border-radius: 5px;
        display: flex;
        justify-content: center;
        align-items: center;
        margin: 0 5px;
      }
      .operate-onekey-on {
        width: 75px;
        height: 30px;
        background: #F4F5F7;
        border-radius: 5px;
        display: flex;
        justify-content: center;
        align-items: center;
        margin: 0 5px;
        font-weight: 400;
        color: #344567;
      }
      .but-disable {
        color: #6B778C;
        opacity: 0.5;
      }
    }
  }
}
</style>
