<template>
  <view>
    <navbar-back title="天平状态"></navbar-back>
    <view class="p20">
      <up-grid :col="4" style="gap: 20px">
        <up-grid-item v-for="(auncel, index) in auncelList" :key="index">
          <view class="auncel-item" :style="{ backgroundImage: `url(${balanceBackground})` }">
            <view class="auncel-header">
              <view class="auncel-code">{{ auncel.deviceCode }}</view>
              <view class="auncel-name">{{ auncel.controlRealName }}</view>
            </view>
            <view class="weight">
              <view :class="getWeightClass(auncel)" :style="getWeightStyle(auncel)">
                {{ getWeightText(auncel) }}
              </view>
              <view v-if="auncel.isConnected === 1" class="weight-unit">{{ auncel.weightUnit }}</view>
            </view>
          </view>
          <view v-if="auncel.isConnected != 1" class="shade">天平断开</view>
        </up-grid-item>
      </up-grid>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { onUnload, onHide } from '@dcloudio/uni-app'
import { getTenantId } from '@/defaultBaseUrl'
import nx from '@/nx'
const balanceBackground = '/static/images/auncel.png'

// refs
const auncelList = ref([])

// computed
const userInfo = computed(() => nx.$store('user').userInfo)

// 页面加载
onMounted(() => {
  getPageData()

  const regData = {
    msgId: nx.$helper.uuid(),
    cmd: 'register',
    clientType: 'caaClient',
    data: {
      userId: userInfo.value.id,
      tenantId: getTenantId(),
      userRealName: userInfo.value.realname
    }
  }
  nx.$measure.setRegData(JSON.stringify(regData))

  nx.$measure.open()

  // 监听 WebSocket 数据
  uni.$on('deviceData', handleDeviceData)
  uni.$on('deviceStatus', handleDeviceStatus)
  uni.$on('connClose', handleConnClose)
})
onHide(() => {
  // #ifdef APP-PLUS
  cleanup()
  // #endif
})
onUnmounted(() => {
  // #ifdef H5
  cleanup()
  // #endif
})

function cleanup() {
  uni.$off('deviceData', handleDeviceData)
  uni.$off('deviceStatus', handleDeviceStatus)
  uni.$off('connClose', handleConnClose)
}

// 获取数据
function getPageData() {
  nx.$api.laboratory
    .getDeviceLaboratoryListBy({
      pageNo: 1,
      pageSize: 999,
      collectDeviceType: 'balance',
      deviceStatus: '0',
      isEnable: '1'
    })
    .then(res => {
      auncelList.value = res.list
    })
    .catch(err => {
      console.error('获取天平列表失败', err)
    })
}

// WebSocket 事件处理器
function handleDeviceData(res) {
  if (res.deviceType === 'balance') {
    auncelList.value.forEach(item => {
      if (item.id === res.deviceId) {
        item.weightData = res.weightData
        item.weightUnit = res.weightUnit
        item.weightStable = res.weightStable
        item.isConnected = 1
        item.controlRealName = res.controlRealName
      }
    })
  }
}

function handleDeviceStatus(res) {
  console.log(res)

  if (res.deviceType === 'balance') {
    auncelList.value.forEach(item => {
      if (item.id === res.deviceId) {
        item.isConnected = res.connected
        if (res.connected == 0) {
          item.weightData = ''
          item.weightUnit = ''
          item.weightStable = 0
        }
      }
    })
  }
}

function handleConnClose() {
  auncelList.value.forEach(item => {
    item.weightData = ''
    item.weightUnit = ''
    item.weightStable = 0
    item.controlRealName = ''
    item.isConnected = 0
  })
}

function getWeightText(auncel) {
  if (auncel.isConnected !== 1) {
    return ''
  }
  return auncel.weightData || ''
}

function getWeightClass(auncel) {
  if (auncel.weightStable === 0) return 'weight-data-yellow'
  if (auncel.weightStable === 1) return 'weight-data'
  if (auncel.weightStable === 2) return 'weight-data-warning'
  return 'weight-data-yellow'
}

function getWeightStyle(auncel) {
  if (auncel.isConnected !== 1) {
    return {
      textAlign: 'center',
      paddingTop: '0',
      fontSize: '28px'
    }
  }
  return {
    textAlign: 'right',
    paddingTop: '10px',
    fontSize: '32px'
  }
}
</script>

<style scoped>
.auncel-item {
  height: 180px;
  width: 180px;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 10px;
  box-sizing: border-box;
}
.shade {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(31, 41, 55, 0.55);
  color: #fff;
  font-weight: 500;
  z-index: 10;
  border-radius: 8px;
}
.auncel-header {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.auncel-code {
  font-size: 20px;
  font-weight: bold;
}

.auncel-name {
  margin-top: 5px;
}

.weight {
  width: 100%;
  height: 60px;
  position: relative;
  box-sizing: border-box;
  padding: 0 20px;
}
.weight-data,
.weight-data-yellow,
.weight-data-warning {
  font-family: zzjc-lcd;
}

.weight-data {
  color: #4cd964;
}

.weight-data-yellow {
  color: #ffff00;
}

.weight-data-warning {
  color: #ff3333;
}

.weight-unit {
  position: absolute;
  right: 3px;
  top: 8px;
  color: #ffffff;
  font-size: 24px;
}
</style>
