<template>
  <view class="contai_warp">
    <view class="top_mimicry" :style="{ height: statusBarHeight + 45 + 'px' }"></view>
    <view class="top_fixed_warp">
      <view style="width: 100%" :style="{ height: statusBarHeight + 'px' }"></view>

      <view class="top_warp">
        <image class="company_logo_css" src="https://online.totustec.com/upload/indexPage/company_logo1.png"></image>
      </view>
    </view>

    <image class="nav_warp" src="https://online.totustec.com/upload/indexPage/nav_img.png"></image>

    <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 class="device_area_warp" style="margin-top: 56rpx">
        <view class="device_top">
          <view class="device_top_left">
            <image class="top_left_img1" src="https://online.totustec.com/upload/indexPage/top_left_img2.png"></image>
            <view class="top_left_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="flex: 1">报警状态</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="flex: 1">
                    <view class="label_warp2">
                      <view class="label_icon" :style="{ background: getStatusColor(item.errorStatus) }"></view>
                      <view class="label_text label_text2" :style="{ color: getStatusColor(item.errorStatus) }">
                        {{ getStatusText(item.errorStatus) }}
                      </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_img2.png">
              </image>
              <view class="table_nodata_text">暂无设备预警</view>
            </view>
          </view>
        </view>
      </view> -->


      <!-- 轮播图 -->
      <view class="carousel_image_warp">
        <!-- 轮播图组件 -->
        <swiper class="carousel_swiper" indicator-dots indicator-active-color="#0095de" autoplay interval="3000"
          duration="500" circular>

          <swiper-item class="carousel_item" v-for="(item, index) in carouselimageList" :key="index">
            <image class="carousel_img" :src="'https://online.totustec.com/upload' + item" mode="widthFix"></image>
          </swiper-item>
        </swiper>
      </view>

      <view class="use_wizard_warp">
        <image class="use_wizard_img" src="https://online.totustec.com/upload/indexPage/use_wizard_img.png"></image>
      </view>
      <!-- <view style="height: 100rpx"></view> -->
    </view>
  </view>
</template>

<script>
import {
  BASE_STOKECT_URL, BASE_IMG_URL, BASE_API_URL
} from "@/config.js";

export default {
  data () {
    return {
      title: "Hello",
      statusBarHeight: 0,
      searchList: {
        page: 1,
        size: 10000,
      },
      deviceList: [],
      statusMap: {
        0: { text: '正常', color: '#00d195' },  // 绿色
        1: { text: '文件校验失败', color: '#ff0000' },  // 红色
        2: { text: '设备或加密错误', color: '#ff0000' },
        3: { text: '打印准备过程出错', color: '#ff0000' },
        4: { text: '打印出错', color: '#ff0000' },
        5: { text: '加液失败', color: '#ff9800' },
        6: { text: '铲件失败', color: '#ff9800' },
        7: { text: '图片异物', color: '#ff0000' }
      },
      carouselimageList: [],

      // WebSocket 相关状态
      socketTask: null, // uni-app 的 WebSocket 任务实例
      isSocketConnected: false, // 连接状态
      reconnectTimer: null, // 重连定时器
      reconnectInterval: 5000 // 重连间隔（5秒）
    };
  },
  onShareAppMessage () {
    return {
      title: '欢迎使用Totustec',
      path: '/pages/index/index',
      imageUrl: 'https://online.totustec.com/upload/indexPage/logo.png'
    }
  },
  onLoad () {
    const systemInfo = wx.getSystemInfoSync();
    const {
      statusBarHeight, // 状态栏高度（单位：px）
    } = systemInfo;
    this.statusBarHeight = statusBarHeight;
    this.connectWebSocket(); // 初始化 WebSocket 连接
    this.getCarouselimageList();
  },
  onShow () {
    this.getDeviceList(); // 每次显示页面时调用
  },
  onUnload () {
    this.closeWebSocket(); // 页面卸载时关闭连接
  },
  methods: {
    // ---------------------- WebSocket 核心方法 ----------------------
    connectWebSocket () {
      const wsUrl = BASE_STOKECT_URL;

      // 初始化 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('实时消息');
    },
    // 获取状态文字
    getStatusText (status) {
      if (status == -1) {
        return '断开'
      }
      return this.statusMap[status]?.text || '';
    },
    // 获取状态颜色
    getStatusColor (status) {
      if (status == -1) {
        return '#999999'
      }
      return this.statusMap[status]?.color; // 默认灰色
    },
    toPage () {
      uni.navigateTo({
        url: "/pages/deviceBind/index",
      });
    },
    async getDeviceList () {
      try {
        // 从本地缓存获取用户信息
        const userInfo = uni.getStorageSync("userInfo") || {};
        const res = await uni.request({
          url: BASE_API_URL + "/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);

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

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

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

      }
    },
  },
};
</script>
<!-- 临时样式 -->
<style scoped>
.use_wizard_img {
  width: 100%;
  height: 172rpx;
}

.use_wizard_warp {
  padding: 24rpx;
}

.carousel_swiper {
  width: 100%;
  height: 100%;
}

.carousel_item {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.carousel_img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  /* 图片自适应填充，保持比例不拉伸 */
  border-radius: 16rpx;
  /* 轻微圆角，提升美观度 */
}

.carousel_image_warp {
  width: 100%;
  height: 820rpx;
}

.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;
}

.top_mimicry {
  width: 100%;
}

.top_fixed_warp {
  position: fixed;
  top: 0;
  left: 0;
  display: flex;
  flex-direction: column;
  width: 100%;
  background-color: white;
}
</style>

<style scoped>
.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;
  min-height: 75vh;
}

.nav_warp {
  width: 100%;
  height: 224rpx;
  display: block;
}

.top_warp {
  height: 88rpx;
  display: flex;
  align-items: center;
  padding-left: 40rpx;
}

.company_logo_css {
  width: 175rpx;
  height: 71rpx;
}
</style>
