<template>
  <view class="contai_warp">
    <view class="top_area_warp">
      <view class="top_status_area" :style="{ height: statusBarHeight + 'px' }"></view>
      <view class="top_nav_warp">设备</view>
    </view>

    <view class="middle_area_warp">
      <!-- 设备状态 -->
      <view class="device_area_warp">
        <view class="device_top">
          <view class="device_top_left">
            <image class="top_left_img1" src="https://online.totustec.com/upload/indexPage/top_left_img1.png"></image>
            <view class="top_left_text">设备状态</view>
          </view>

          <view class="device_top_right" @click="toPage('绑定设备')">
            <image class="top_right_icon" src="https://online.totustec.com/upload/indexPage/top_right_icon.png"></image>
            <view class="top_right_text">绑定设备</view>
          </view>
        </view>

        <view class="device_table_warp">
          <view class="device_table_area">
            <view class="device_table_top">
              <view class="table_top_item" style="padding-left: 27rpx">机器序号</view>
              <view class="table_top_item" style="width: 301rpx">机器描述</view>
              <view class="table_top_item" style="width: 200rpx">设备运行状态</view>
            </view>
            <view class="table_data_warp" v-if="deviceList.length > 0">
              <view class="table_data_item" v-for="(item, index) in deviceList">
                <view class="data_display_warp">
                  <view class="data_item_line" style="padding-left: 27rpx">{{ item.deviceCode }}</view>
                  <view class="data_item_line" style="width: 301rpx">{{ item.brand }}</view>
                  <view class="data_item_line" style="width: 200rpx">
                    <view class="label_warp" v-if="item.status == 0">
                      <view class="label_icon"></view>
                      <view class="label_text">空闲</view>
                    </view>
                    <view class="label_warp" v-if="item.status == 2">
                      <view class="label_icon" style="background: #00abff"></view>
                      <view class="label_text" style="color: #00abff">准备中</view>
                    </view>
                    <view class="label_warp" v-if="item.status == 1">
                      <view class="label_icon" style="background: #00d195"></view>
                      <view class="label_text" style="color: #00d195">打印中</view>
                    </view>
                    <view class="label_warp" v-if="item.status == 3">
                      <view class="label_icon" style="background: #FDCB3B"></view>
                      <view class="label_text" style="color: #FDCB3B">铲件中</view>
                    </view>
                    <view class="label_warp" v-if="item.status == -1">
                      <view class="label_icon" style="background: #999999"></view>
                      <view class="label_text" style="color: #999999">断开</view>
                    </view>
                  </view>
                </view>

                <view class="data_dline_warp">
                  <view class="data_dline_css"></view>
                </view>
              </view>
            </view>
            <!-- 暂无数据 -->
            <view class="table_nodata_area" v-else>
              <image class="table_nodata_img" src="https://online.totustec.com/upload/indexPage/table_nodata_img1.png">
              </image>
              <view class="table_nodata_text">暂无设备，请绑定设备～</view>
            </view>
          </view>
        </view>
      </view>

      <view style="height: 100rpx"></view>
    </view>

    <image class="equipment_control_warp" src="https://online.totustec.com/upload/devicePage/equipment_control_warp.png"
      @click="toPage('设备控制')">
    </image>
  </view>
</template>

<script>
export default {
  data () {
    return {
      title: "Hello",
      statusBarHeight: 0,
      searchList: {
        page: 1,
        size: 10000,
      },
      deviceList: [],

      // WebSocket 相关状态
      socketTask: null, // uni-app 的 WebSocket 任务实例
      isSocketConnected: false, // 连接状态
      reconnectTimer: null, // 重连定时器
      reconnectInterval: 5000 // 重连间隔（5秒）
    };
  },
  onLoad () {
    const systemInfo = wx.getSystemInfoSync();
    const {
      statusBarHeight, // 状态栏高度（单位：px）
    } = systemInfo;

    this.statusBarHeight = statusBarHeight;

    this.connectWebSocket(); // 初始化 WebSocket 连接
  },
  onUnload () {
    this.closeWebSocket(); // 页面卸载时关闭连接
  },
  onShow () {
    this.getDeviceList(); // 每次显示页面时调用
  },
  methods: {
    // ---------------------- WebSocket 核心方法 ----------------------
    connectWebSocket () {
      const wsUrl = 'ws://e7eb22d8.natappfree.cc/webSocket/vue';

      // 初始化 WebSocket 连接（使用 uni-app 接口）
      this.socketTask = uni.connectSocket({
        url: wsUrl,
        success: () => {
          console.log('WebSocket 连接成功');
          this.isSocketConnected = true;
          this.listenSocketMessage(); // 监听消息
        },
        fail: (err) => {
          console.error('连接失败:', err);
          this.tryReconnect(); // 尝试重连
        }
      });
    },

    listenSocketMessage () {
      // 监听 WebSocket 消息
      uni.onSocketMessage((event) => {
        console.log('event', event);

        const message = JSON.parse(event.data);
        console.log('收到实时消息:', message);
        this.getDeviceList();
        // this.updateDeviceStatus(message); // 更新设备状态
      });
    },

    closeWebSocket () {
      // 关闭连接并清理资源
      if (this.socketTask) {
        uni.closeSocket();
        this.socketTask = null;
        this.isSocketConnected = false;
      }
      clearTimeout(this.reconnectTimer);
    },

    tryReconnect () {
      // 自动重连机制
      clearTimeout(this.reconnectTimer);
      this.reconnectTimer = setTimeout(() => {
        console.log('尝试重连 WebSocket...');
        this.connectWebSocket();
      }, this.reconnectInterval);
    },

    updateDeviceStatus (message) {
      console.log('实时消息');

    },


    toPage (type) {
      if (type == "设备控制") {
        uni.navigateTo({
          url: "/pages/selectDevice/index",
        });
      }
      if (type == "绑定设备") {
        uni.navigateTo({
          url: "/pages/deviceBind/index",
        });
      }
    },

    async getDeviceList () {
      try {
        // 从本地缓存获取用户信息
        const userInfo = uni.getStorageSync("userInfo") || {};
        const res = await uni.request({
          url: "https://online.totustec.com/api/api/front/user/myDevice",
          method: "GET",
          data: this.searchList,
          header: {
            "Content-Type": "application/x-www-form-urlencoded", // 关键配置
            "Authorization": userInfo.token || ""
          },
        });

        if (res.statusCode == 200) {
          this.deviceList = res.data.content
          console.log('this.deviceList', this.deviceList);

        }
      } catch (error) {
        console.log('请求接口失败', error);

      }
    },
  },
};
</script>
<!-- 临时样式 -->
<style scoped>
.label_icon {
  width: 18rpx;
  height: 18rpx;
  background: #cccccc;
  border-radius: 100%;
}

.label_text {
  font-family: PingFang SC, PingFang SC;
  font-weight: 400;
  font-size: 26rpx;
  color: #666666;
  margin-left: 8rpx;
}

.label_text2 {
  color: #ff0000;
}

.label_warp {
  display: flex;
  align-items: center;
  margin-left: 48rpx;
}

.label_warp2 {
  display: flex;
  align-items: center;
}

.data_item_line {
  width: 209rpx;
  min-height: 82rpx;
  display: flex;
  align-items: center;
  font-family: PingFang SC, PingFang SC;
  font-weight: 400;
  font-size: 26rpx;
  color: #666666;
}

.table_data_warp {
  width: 100%;
  display: flex;
  flex-direction: column;
  background-color: white;
}

.table_data_item {
  width: 100%;
  display: flex;
  flex-direction: column;
}

.data_display_warp {
  display: flex;
  align-items: center;
}

.data_dline_warp {
  padding: 0 22rpx;
}

.data_dline_css {
  width: 100%;
  border: 1rpx solid #ededed;
}
</style>

<style scoped>
.equipment_control_warp {
  position: fixed;
  right: 44rpx;
  bottom: 15%;
  width: 120rpx;
  height: 120rpx;
}

.contai_warp {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-family: PingFang SC, PingFang SC !important;
  min-height: 100vh;
  background-color: #f1f6fc;
}

.top_area_warp {
  width: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
}

.top_status_area {
  width: 100%;
}

.top_nav_warp {
  width: 100%;
  height: 88rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: PingFang SC, PingFang SC;
  font-weight: 500;
  font-size: 32rpx;
  color: #000000;
  position: relative;
  z-index: 5;
}

.container_warp {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-family: PingFang SC, PingFang SC !important;
}

.table_nodata_area {
  width: 100%;
  height: 429rpx;
  background-color: white;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.table_nodata_img {
  width: 316rpx;
  height: 262rpx;
}

.table_nodata_text {
  font-family: PingFang SC, PingFang SC;
  font-weight: 400;
  font-size: 22rpx;
  color: #666666;
}

.table_top_item {
  width: 209rpx;
  font-family: PingFang SC, PingFang SC;
  font-weight: 600;
  font-size: 28rpx;
  color: #333333;
}

.device_table_top {
  width: 100%;
  height: 73rpx;
  background: #f0f0f0;
  border-radius: 20rpx 20rpx 0rpx 0rpx;
  display: flex;
  align-items: center;
}

.device_table_area {
  width: 100%;
  display: flex;
  flex-direction: column;
}

.device_table_warp {
  padding: 0 20rpx;
}

.device_top_right {
  display: flex;
  width: 158rpx;
  height: 42rpx;
  background: #0095de;
  border-radius: 21rpx;
  align-items: center;
  margin-right: 18rpx;
}

.top_right_icon {
  display: flex;
  width: 31rpx;
  height: 31rpx;
  margin: 0 10rpx 0 14rpx;
}

.top_right_text {
  font-family: PingFang SC, PingFang SC;
  font-weight: 400;
  font-size: 24rpx;
  color: #ffffff;
}

.device_area_warp {
  display: flex;
  flex-direction: column;
}

.device_top {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin: 12rpx 0 29rpx 0;
}

.device_top_left {
  display: flex;
  margin-left: 20rpx;
}

.top_left_img1 {
  width: 46rpx;
  height: 46rpx;
  display: block;
}

.top_left_text {
  font-family: PingFang SC, PingFang SC !important;
  font-weight: 600;
  font-size: 32rpx;
  color: #000000;
  margin-left: 7rpx;
}

.middle_area_warp {
  width: 100%;
  background: #f1f6fc;
  border-radius: 30rpx 30rpx 0rpx 0rpx;
  display: flex;
  flex-direction: column;
  margin-top: -28rpx;
  padding-top: 28rpx;
}
</style>
