<template>
  <view class="page">
    <u-navbar
      title="化学分析天平"
      :is-back="false"
      :border-bottom="false"
      title-color="#fff"
      :background="{ 'background-image': 'linear-gradient(45deg, rgb(54, 138, 217), rgb(64, 160, 255))' }"
    ></u-navbar>
    <view style="text-align: center"><u-loading mode="flower" :show="showLoading" size="48"></u-loading></view>
    <view class="container">
      <view class="auncel" v-for="(item, index) in deviceLaboratoryList" :key="item.id">
        <view class="title">
          <u-row style="width: 100%; padding-bottom: 18rpx" gutter="16">
            <u-col span="8">
              <text class="measurePointName"
                >{{ item.name }} {{ item.controlUserName ? '[' + item.controlUserName + ']远程控制' : '' }}</text
              >
            </u-col>
            <u-col span="4">
              <!--
                            <view style="width: 100%; display: flex; flex-direction: row; justify-content: flex-end;">
								<text class="measurePointName" >{{item.isAutoWork ? '自动计量' : '集控接管'}}</text>
                                <u-icon style="padding: 0 20rpx;" name="file-text" label-pos="bottom"  color="#2979ff" size="40" @click="goto(item.measurePointId)"></u-icon>
                                <u-icon style="padding: 0 20rpx;" name="setting" label-pos="bottom" label="设置" color="#2979ff" size="40" @click="goto(item.measurePointId)"></u-icon> 
                            </view>
                            -->
            </u-col>
          </u-row>
        </view>
        <view :class="item.isConnected == 1 ? 'title-line-green' : 'title-line-gray'"></view>
        <view class="weight-container">
          <!-- <view class="infrared-container">
                        <view :class="item.infraredLeft == 0 ? 'infrared-line-gray' : item.infraredLeft == 1 ? 'infrared-line-green':'infrared-line-red'"></view>
                    </view>
                     -->
          <block v-if="item.deviceType == 'auncel'">
            <view class="weight">
              <view
                :class="
                  item.weightStable == 0
                    ? 'weight-data-yellow'
                    : item.weightStable == 1
                    ? 'weight-data'
                    : 'weight-data-warning'
                "
              >
                {{ item.weightData }}
              </view>
              <view class="weight-unit">{{ item.weightUnit }}</view>
            </view>
          </block>
          <block v-if="item.deviceType == 'temp'">
            <view class="temp">
              <view class="charts-box"
                ><qiun-data-charts
                  type="gauge"
                  :opts="temperatureOpts"
                  :chartData="temperatureChartData"
                  background="none"
              /></view>
              <view class="charts-box"
                ><qiun-data-charts type="gauge" :opts="humidityOpts" :chartData="humidityChartData" background="none"
              /></view>
            </view>
          </block>
          <!-- 
                    <view class="infrared-container">
						<view :class="item.infraredRight == 0 ? 'infrared-line-gray' : item.infraredRight == 1 ? 'infrared-line-green':'infrared-line-red'"></view>
                    </view>
                     -->
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      showLoading: false,
      runLogMaxLength: 8,
      deviceLaboratoryList: [],
      temperatureOpts: {},
      temperatureChartData: {
        categories: [
          {
            value: 0.2,
            color: '#1890ff'
          },
          {
            value: 1,
            color: '#2fc25b'
          }
        ],
        series: [
          {
            name: '温度',
            data: 0.66
          }
        ]
      },
      humidityOpts: {},
      humidityChartData: {
        categories: [
          {
            value: 1,
            color: '#1890ff'
          }
        ],
        series: [
          {
            name: '湿度',
            data: 0.66
          }
        ]
      }
    }
  },
  onLoad() {
    //获取数据
    this.getPageData()

    //监听websocket返回来的数据
    //设备数据
    uni.$on('deviceData', res => {
      switch (res.deviceType) {
        case 'weighbridge':
          this.mearsuPointList.forEach((item, index) => {
            if (item.measurePointId === res.measurePointId) {
              //item.weightData = (index + Number(res.deviceValue)).toFixed(2) + " "+ res.deviceUnit;
              item.weightData = res.deviceValue
              item.weightUnit = res.deviceUnit
              item.weightStable = res.deviceStable
              item.measureIsConnected = 1
              item.isAutoWork = res.isAutoWork
            }
          })
          break
        case 'auncel':
          this.deviceLaboratoryList.forEach((item, index) => {
            if (item.id === res.deviceId) {
              //item.weightData = (index + Number(res.deviceValue)).toFixed(2) + " "+ res.deviceUnit;
              item.weightData = res.weightData
              item.weightUnit = res.weightUnit
              item.weightStable = 1
              item.isConnected = 1
            }
          })
          break
        default:
          break
      }

      // this.weight = res.weighbridge;
      // this.infraredLeft = res.infrared;
      // this.infraredRight = res.infrared;
    })

    //设备状态
    uni.$on('deviceStatus', res => {
      this.mearsuPointList.forEach((item, index) => {
        if (item.measurePointId === res.measurePointId) {
          item.devices.forEach((d, i) => {
            if (d.id === res.deviceId) {
              d.isConnected = res.connected
            }
          })
        }
      })
    })

    //日志数据
    uni.$on('logData', res => {
      this.mearsuPointList.forEach((item, index) => {
        if (item.measurePointId === res.measurePointId) {
          if (item.runLogs.length >= this.runLogMaxLength) {
            //删除并返回数组的第一个元素
            //item.runLogs.shift();
            //删除并返回数组的最后一个元素
            item.runLogs.pop()
          }
          //向数组的末尾添加
          //item.runLogs.push(res);
          //向数组的开头添
          item.runLogs.unshift(res)

          //滚动
          // this.$nextTick(function() {
          //     item.scrollTop = 20*item.runLogs.length;
          // });
        }
      })
    })

    //监听控制
    uni.$on('controlMeasurePoint', res => {
      console.log(res)
      let data = res.data
      this.mearsuPointList.forEach(i => {
        if (i.measurePointId === data.measurePointId) {
          if (data.success && data.isControl) {
            i.controlUserName = data.controlUserName
          } else {
            i.controlUserName = ''
          }
          console.log(i)
        }
      })
    })

    //计量点状态
    uni.$on('measurePointStatus', res => {
      //断开
      this.mearsuPointList.forEach(i => {
        if (i.measurePointId === res.measurePointId) {
          if (res.measureIsConnected != 1) {
            i.weightData = ''
            i.weightUnit = ''
            i.weightStable = 0
            i.infraredLeft = 0
            i.infraredRight = 0
            i.measureIsConnected = 0
            if (i.runLogs.length >= this.runLogMaxLength) {
              i.runLogs.pop()
            }
            i.runLogs.unshift({
              id: this.$helper.uuid(),
              content: '计量点连接断开！',
              measurePointId: i.measurePointId,
              time: this.$helper.dateFormat(new Date(), 'yy-MM-dd hh:mm:ss')
            })
            i.devices.forEach(d => {
              d.isConnected = 0
            })
          } else {
            i.measureIsConnected = 1
            /* if(i.runLogs.length >= 8) {
                                i.runLogs.shift();
                            }
                            i.runLogs.push({
                                id: this.$helper.uuid(),
                                content: "计量点连接成功！",
                                measurePointId: i.measurePointId,
                                time: this.$helper.dateFormat(new Date(), "yy-MM-dd hh:mm:ss")
                            }); */
          }
        }
      })
    })

    //连接断开
    uni.$on('connClose', res => {
      //重置
      this.mearsuPointList.forEach(i => {
        i.weightData = ''
        i.weightUnit = ''
        i.weightStable = 0
        i.controlUserName = ''
        i.measureIsConnected = 0
        if (i.runLogs.length >= this.runLogMaxLength) {
          i.runLogs.pop()
        }
        let lastLog = i.runLogs[i.runLogs.length - 1]
        if (lastLog && lastLog.content !== '控制中心连接断开！') {
          i.runLogs.unshift({
            id: this.$helper.uuid(),
            content: '控制中心连接断开！',
            measurePointId: i.measurePointId,
            time: this.$helper.dateFormat(new Date(), 'yy-MM-dd hh:mm:ss')
          })
        }
        i.devices.forEach(d => {
          d.isConnected = 0
        })
      })
    })
  },
  onUnload() {
    //移除监听websocket返回来的数据
    uni.$off('deviceData')
    uni.$off('deviceStatus')
    uni.$off('logData')
    uni.$off('controlMeasurePoint')

    uni.$off('measurePointStatus')
    uni.$off('connClose')
  },
  filters: {
    numFilter(value) {
      // 截取当前数据到小数点后两位
      let realVal = value.toFixed(2)
      return realVal
    }
  },
  computed: {},
  methods: {
    getPageData() {
      //显示loading
      this.showLoading = true
      //获取计量点数量
      this.$u.api
        .getDeviceLaboratoryListBy()
        .then(res => {
          let dataList = res.data
          dataList.forEach(i => {
            i.weightData = ''
            i.weightUnit = ''
            i.isConnected = 0
            i.weightStable = 0
            i.temperature = 0
            i.humidity = 0
            i.controlUserName = ''
          })
          this.deviceLaboratoryList = dataList
          this.showLoading = false

          //打开websocket
          this.openLaboratoryWs()

          //发送检查计量点控制情况
          let checkControl = {
            msgId: this.$helper.uuid(),
            cmd: 'checkControl',
            clientType: 'consoleClient'
          }
          if (this.$measure.isOpen) {
            this.$measure.send(JSON.stringify(checkControl))
          }
        })
        .catch(err => {
          this.showLoading = false
          console.log(err)
        })
    },
    openLaboratoryWs() {
      //注册websocket
      let regData = {
        msgId: this.$helper.uuid(),
        cmd: 'register',
        clientType: 'caaClient',
        data: {
          userId: this.userInfo.user_id,
          tenantId: this.userInfo.tenant_id,
          userRealName: this.userInfo.real_name
        }
      }
      this.$measure.setRegData(JSON.stringify(regData))
      this.$measure.open()
    },
    scroll(e) {
      // console.log(e);
      // this.mearsuPointList.forEach((i) => {
      //     if(i.measurepointid === e.currentTarget.dataset.measurepointid) {
      //         i.oldScrollTop = e.detail.scrollTop;
      //     }
      // });
    },
    goto(measurePointId) {
      uni.reLaunch({
        url: '/pages/measure/measure?measurePointId=' + measurePointId
      })
    }
  }
}
</script>

<style>
.container {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
}
/* #ifdef H5 */
.auncel {
  width: 31.33%;
  display: flex;
  flex-direction: column;
  padding: 20rpx;
  margin: 1%;
  border-radius: 24rpx;
  box-shadow: 1px 1px 10px #909399;
}
@media only screen and (max-width: 1200px) {
  .auncel {
    width: 48%;
  }
}
@media only screen and (max-width: 600px) {
  .auncel {
    width: 100%;
  }
}
/* #endif */
/* #ifndef H5 */
.auncel {
  width: 98%;
  display: flex;
  flex-direction: column;
  padding: 20rpx;
  margin: 1%;
  border-radius: 24rpx;
  box-shadow: 1px 1px 10px #909399;
}
/* #endif */
.title-line-gray {
  width: 100%;
  height: 6rpx;
  top: 0;
  left: 0;
  background-color: rgb(128, 134, 149);
  border-radius: 4rpx 4rpx 0 0;
}
.title-line-green {
  width: 100%;
  height: 6rpx;
  top: 0;
  left: 0;
  background-color: rgb(27, 201, 142);
  border-radius: 4rpx 4rpx 0 0;
}
.title {
  display: flex;
  flex-direction: row;
  justify-content: center;
}
.temp {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: center;
}
.charts-box {
  width: 50%;
  height: 200px;
}
.measurePointName {
  font-size: 30rpx;
}
.weight-container {
  padding: 10rpx;
  display: flex;
  flex-direction: row;
}
.infrared-container {
  width: 30%;
  display: flex;
  justify-content: center;
}
.infrared-line-green {
  width: 8rpx;
  height: 90rpx;
  background-color: #18b566;
}
.infrared-line-red {
  width: 8rpx;
  height: 90rpx;
  background-color: #ff3333;
}
.infrared-line-gray {
  width: 8rpx;
  height: 90rpx;
  background-color: #909399;
}
.infrared-left {
  width: 8rpx;
  height: 90rpx;
  background-color: #18b566;
}
.infrared-left-warning {
  width: 8rpx;
  height: 90rpx;
  background-color: #ff3333;
}
.weight {
  width: 100%;
  min-width: 200px;
  height: 90rpx;
  padding: 0 8rpx;
  display: flex;
  flex-direction: row;
  background-color: #2c405a;
}
.weight-data {
  flex-grow: 1;
  height: 100%;
  color: #4cd964;
  text-align: right;
  line-height: 90rpx;
  letter-spacing: 4rpx;
  font-size: 90rpx;
  font-family: zzjc-lcd;
}
.weight-data-yellow {
  flex-grow: 1;
  height: 100%;
  color: #ffff00;
  text-align: right;
  line-height: 90rpx;
  letter-spacing: 4rpx;
  font-size: 90rpx;
  font-family: zzjc-lcd;
}
.weight-data-warning {
  flex-grow: 1;
  height: 100%;
  color: #ff3333;
  text-align: right;
  line-height: 90rpx;
  font-size: 90rpx;
  font-family: zzjc-lcd;
}
.weight-unit {
  color: #ffffff;
  font-size: 60rpx;
  line-height: 90rpx;
  padding-left: 20rpx;
}
.infrared-right {
  width: 8rpx;
  height: 90rpx;
  background-color: #18b566;
}
.infrared-right-warning {
  width: 8rpx;
  height: 90rpx;
  background-color: #ff3333;
}
.device-container {
  padding: 20rpx;
  width: 100%;
  height: 200rpx;
  display: flex;
  justify-content: space-evenly;
  flex-wrap: wrap;
  justify-content: flex-start;
}
.device {
  width: 25%;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.device-icon {
  width: 40rpx;
  height: 40rpx;
  background-color: #ff3333;
  border-radius: 50%;
}
.device-icon-green {
  width: 40rpx;
  height: 40rpx;
  background-color: #18b566;
  border-radius: 50%;
}
.device-icon-gray {
  width: 40rpx;
  height: 40rpx;
  background-color: rgb(128, 134, 149);
  border-radius: 50%;
}
.device-icon-red {
  width: 40rpx;
  height: 40rpx;
  background-color: #ff3333;
  border-radius: 50%;
}
.run-log {
  width: 100%;
  padding: 10rpx 20rpx;
  height: 400rpx;
  background-color: #ecf5ff;
  border-radius: 24rpx;
  --box-shadow: 1px 1px 10px #909399;
}
.log-content {
  font-size: 28rpx;
  font-weight: 200;
  margin-bottom: 10rpx;
}
</style>
