<template>
  <view>
    <navbar-back title="天平状态"></navbar-back>
    <up-grid border :col="3">
      <up-grid-item v-for="(auncel, index) in auncelList" :index="index" :key="index">
        <view
          class="auncel-item"
          :style="{
            backgroundImage: `url(${require('@/static/images/auncel.png')})`
          }"
        >
          <view class="auncel-header">
            <view class="auncel-code">{{ auncel.code }}</view>
            <view class="auncel-name">{{ auncel.controlRealName }}</view>
          </view>
          <view class="weight">
            <view
              :class="{
                'weight-data-yellow': auncel.weightStable === 0,
                'weight-data': auncel.weightStable === 1,
                'weight-data-warning': auncel.weightStable === 2
              }"
            >
              {{ auncel.weightData || '' }}
            </view>
            <view class="weight-unit">{{ auncel.weightUnit }}</view>
          </view>
        </view>
      </up-grid-item>
    </up-grid>
  </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'

// refs
const auncelList = ref([])

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

// 页面加载
onMounted(() => {
  // getPageData()
  // #ifdef H5
  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.reOpen()
  // #endif

  // 监听 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({
      deviceType: 'auncel',
      status: '1',
      isEnable: '1',
      pageNo: 0,
      pageSize: -1
    })
    .then(res => {
      const dataList = res.records || []
      dataList.forEach(i => {
        i.weightData = ''
        i.weightUnit = ''
        i.isConnected = 0
        i.weightStable = 0
        i.temperature = 0
        i.humidity = 0
        i.controlRealName = ''
      })
      auncelList.value = dataList
    })
    .catch(err => {
      console.error('获取天平列表失败', err)
    })
}

// WebSocket 事件处理器
function handleDeviceData(res) {
  if (res.deviceType !== 'auncel') return
  auncelList.value = auncelList.value.map(item => {
    if (item.id === res.deviceId) {
      return {
        ...item,
        weightData: res.weightData,
        weightUnit: res.weightUnit,
        weightStable: res.weightStable,
        isConnected: 1,
        controlRealName: res.controlRealName
      }
    }
    return item
  })
}

function handleDeviceStatus(res) {
  auncelList.value = auncelList.value.map(item => {
    if (item.id === res.deviceId) {
      const updated = { ...item, isConnected: res.connected }
      if (res.connected === 0) {
        updated.weightData = '天平断开'
        updated.weightUnit = ''
        updated.weightStable = 0
      }
      return updated
    }
    return item
  })
}

function handleConnClose() {
  auncelList.value = auncelList.value.map(i => ({
    ...i,
    weightData: '',
    weightUnit: '',
    weightStable: 0,
    controlRealName: '',
    isConnected: 0
  }))
}
</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;
}

.auncel-header {
  height: 100px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

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

.auncel-name {
  margin-top: 5px;
  font-size: 14px;
  color: #666;
}

.weight {
  width: 100%;
  height: 40px;
  display: flex;
  flex-direction: row;
  box-sizing: border-box;
}

.weight-data,
.weight-data-yellow,
.weight-data-warning {
  flex-grow: 1;
  height: 100%;
  text-align: right;
  line-height: 40px;
  letter-spacing: 2px;
  font-size: 32px;
  font-family: zzjc-lcd;
}

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

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

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

.weight-unit {
  color: #ffffff;
  font-size: 24px;
  line-height: 40px;
  padding-left: 10px;
}
</style>
