<template>
  <div class="container" v-loading="loading">

    <div class="left">

      <div class="left_top">

        <div class="device_name">{{ deviceData.deviceInfo?.deviceName }}</div>

        <div style="width: 60%;align-self: center;margin-top: 30px;">
          <img style="width: 100%;height: 100%;" src="../../assets/img/device_detail_hoists_cover_.png" />
        </div>

        <div style="display: flex;justify-content: space-between;margin-top: 30px;">
          <div style="width: 49%;">
            <div style="color: #999999;font-size: 14px;">设备型号</div>
            <div style="color: black;font-size: 14px;margin-top: 5px;">{{ deviceData.deviceInfo?.model }}</div>
          </div>
          <div style="width: 49%;">
            <div style="color: #999999;font-size: 14px;">分类</div>
            <div style="color: black;font-size: 14px;margin-top: 5px;">{{ deviceData.deviceInfo?.category }}</div>
          </div>
        </div>


        <div style="display: flex;justify-content: space-between;margin-top: 10px;">
          <div style="width: 49%;">
            <div style="color: #999999;font-size: 14px;">设备注册号</div>
            <div style="color: black;font-size: 14px;margin-top: 5px;">{{ deviceData.deviceInfo?.registrationNo }}</div>
          </div>
          <div style="width: 49%;">
            <div style="color: #999999;font-size: 14px;">使用证编号</div>
            <div style="color: black;font-size: 14px;margin-top: 5px;">{{ deviceData.deviceInfo?.useCertificateNo }}</div>
          </div>
        </div>


        <div class="gear_container" v-show="false">

          <div style="display: flex;flex-direction: column;flex: 1;">
            <div style="display: flex;width: 100%;">
              <div style="color: #407B51;font-size: 14px;">大车档位</div>
              <div style="color: black;font-size: 16px;width: 100px;text-align: center;">慢速</div>
            </div>

            <div style="display: flex;width: 100%;margin-top: 30px;">
              <div style="color: #407B51;font-size: 14px;">小车档位</div>
              <div style="color: black;font-size: 16px;width: 100px;text-align: center;">慢速</div>
            </div>
          </div>


          <div style="display: flex;flex-direction: column;flex: 1;">
            <div style="display: flex;width: 100%;justify-content: flex-end;">
              <div style="color: #407B51;font-size: 14px;">大车电流</div>
              <div style="color: black;font-size: 16px;width: 100px;text-align: center;">慢速</div>
            </div>

            <div style="display: flex;width: 100%;margin-top: 30px;justify-content: flex-end;">
              <div style="color: #407B51;font-size: 14px;">小车电流</div>
              <div style="color: black;font-size: 16px;width: 100px;text-align: center;">慢速</div>
            </div>
          </div>
        </div>

      </div>

      <div class="left_bottom">

        <div style="display: flex;align-items: center;">
          <img style="height: 40px;" src="../../assets/img/device_detail_alarm_msg.png" />
          <div style="color: black;font-weight: bold;font-size: 18px;margin-left: 10px;">报警消息</div>
        </div>

        <div class="alarm_scroll">
          <div style="align-self: center;margin-top: 50px;color: #999999;" v-if="alarmMessageArr.length == 0">暂无报警记录
          </div>
          <Vue3SeamlessScroll :list="alarmMessageArr" :step="0.3" :hover="true">
            <template v-for="item in alarmMessageArr">
              <div class="alarm_msg_item">
                <div style="color: #999999;font-size: 12px;">{{ item.triggerTime }}</div>
                <div style="color: black;font-size: 14px;margin-top: 10px;">{{ item.message }}</div>
              </div>
            </template>
          </Vue3SeamlessScroll>
        </div>

      </div>
    </div>


    <div class="right">

      <div style="height: 60px;background: white;padding: 0 40px;width: fit-content;border-radius: 10px;">
        <el-tabs v-model="tabName" @tab-click="tabClick">
          <template v-for="(item, index) in deviceData.groupAndVariables">
            <el-tab-pane :label="item.groupName" :name="index"></el-tab-pane>
          </template>
        </el-tabs>
      </div>

      <div class="data_list">


        <div class="data_list_left">


          <div class="gear_weight_container">
            <div style="display: flex;align-items: center;justify-content: center;margin: 0 25px;">
              <div style="min-width: 90px;">
                <div style="color: #7C7C7C;font-size: 16px;">档位</div>
                <div style="color: black;font-size: 24px;margin-top: 10px;">{{ formatGears(currentData.gear) }}</div>
              </div>
            </div>

            <div style="background: #9FBDA8;width: 1px;height: 88px;" v-if="currentData.weight"></div>

            <div style="display: flex;align-items: center;justify-content: center;margin: 0 25px;"
              v-if="currentData.weight">
              <div style="min-width: 90px;">
                <div style="color: #7C7C7C;font-size: 16px;">载荷</div>
                <div style="color: black;font-size: 24px;margin-top: 10px;font-family: OPPOSans, OPPOSans;">{{
                  currentData.weight.value ?? '--' }}{{ currentData.weight.unit }}</div>
              </div>

              <div class="overloading" :class="['overloading', getLight(currentData.weight.light)]"
                v-if="currentData.weight.light">{{ isTrue(currentData.weight.light.value) ? '超载' : '正常' }}</div>
            </div>
          </div>


          <div class="center_switch_list" v-if="currentData?.centerSwitchVariables?.length > 0">
            <template v-for="(item) in currentData.centerSwitchVariables">
              <div class="center_switch_list_item">
                <div :class="['switch_light', getLight(item)]"></div>
                <div class="variable_name" style="margin-top: 8px;">{{ item.variableName }}</div>
              </div>
            </template>
          </div>

          <div class="electric_current_container" ref="electricCurrentContainerRef">
            <div style="width: 100%;height: 100%;min-width: 200px;min-height: 200px;" ref="electricCurrentRef"></div>
          </div>

        </div>


        <div class="data_list_right"
          v-if="currentData?.matchVariables?.length > 0 || currentData?.switchVariables?.length > 0 || currentData?.valueVariables?.length > 0">


          <div class="switch_list" v-if="currentData?.matchVariables?.length > 0">
            <template v-for="(item) in currentData.matchVariables">
              <div class="value_variable_list_item">
                <div class="variable_name" style="margin-top: 10px;">{{ item.name }}</div>

                <div style="display: flex;align-items: center;">
                  <div class="variable_value" style="margin-right: 15px;">{{ item.vValue ?? '--' }}{{ item.unitName }}
                  </div>
                  <div :class="['switch_light', getLight(item)]"></div>
                </div>

              </div>
            </template>
          </div>


          <div class="switch_list" v-if="currentData?.switchVariables?.length > 0">
            <template v-for="(item2) in currentData.switchVariables">
              <div class="value_variable_list_item">
                <div class="variable_name" style="margin-top: 10px;">{{ item2.variableName }}</div>
                <div :class="['switch_light', getLight(item2)]"></div>
              </div>
            </template>
          </div>


          <div class="value_variable_list" v-if="currentData?.valueVariables?.length > 0">
            <template v-for="(item2) in currentData.valueVariables">
              <div class="value_variable_list_item">
                <div class="variable_name" style="margin-top: 10px;">{{ item2.variableName }}</div>

                <div class="variable_value">{{ item2.value ?? '--' }}{{ item2.unitName }}
                </div>
              </div>
            </template>
          </div>


        </div>

      </div>


    </div>
  </div>
</template>

<script setup lang="ts">
import { getDevicesRealData, getRealAlarm } from '@/api/device/index'
import { Vue3SeamlessScroll } from 'vue3-seamless-scroll';
import { formatGears, getLight, isTrue, parseGear } from '@/utils/tools'
import * as echarts from 'echarts'
import { base64StrToArray, byte2Boolen, toInt16, toUInt16, toUInt32 } from '@/utils/byteUtils';

const tabName = ref(0)
const props = defineProps({
  id: {
    type: Number,
    default: 0
  }
})
const electricCurrentContainerRef: any = ref(null)
const electricCurrentRef: any = ref(null)
const electricCurrentChart: any = markRaw({ value: null })

const deviceData: any = ref({})
const currentData: any = ref({})
const alarmMessageArr: any = ref([])

const tabClick = (tab: any) => {
  currentData.value = deviceData.value.groupAndVariables[tab.props.name]
  if (currentData.value.currents.length == 0) {
    electricCurrentContainerRef.value.style.display = "none"
  } else {
    const current = currentData.value.currents[0]
    option.series[0].data[0].value = current.value ?? '0'
    option.series[0].data[0].name = current.variableName
    electricCurrentChart.value.setOption(option)
  }
}


onMounted(async () => {
  electricCurrentChart.value = echarts.init(electricCurrentRef.value)

  window.addEventListener('resize', () => {
    electricCurrentChart.value.resize()
  })

  alarmRun()
})


const { loading } = useRequest(
  () => getDevicesRealData({ deviceId: props.id }),
  {
    onSuccess: (data: any) => {
      data.groupAndVariables.forEach(item => {
        item.centerSwitchVariables = item.switchVariables.slice(0, 9)
        item.switchVariables = item.switchVariables.slice(9)
      });
      deviceData.value = data
      currentData.value = data.groupAndVariables[0]
      if (currentData.value.currents.length == 0) {
        electricCurrentContainerRef.value.style.display = "none"
      } else {
        const current = currentData.value.currents[0]
        option.series[0].data[0].value = current.value ?? 0
        option.series[0].data[0].name = current.variableName
        option.series[0].max = current.formula ?? 100
        electricCurrentChart.value.setOption(option)
      }

      const deviceCode = data.deviceInfo.deviceCode
      const topics = [`Json/${deviceCode}`, `Byte/${deviceCode}`]
      onSubscribe(topics, (topic: string, payload: any) => {
        if (topic.includes('Byte')) {
          parseByteData(payload)
        }
        if (topic.includes('Json')) {
          parseJsonData(payload)
        }
      })

    }
  }
)

onUnmounted(() => {
  onUnsubscribe('Byte/' + deviceData.value.deviceInfo?.deviceCode)
  onUnsubscribe('Json/' + deviceData.value.deviceInfo?.deviceCode)
  clearTimeout(timer.value)
})


const parseByteData = (payload: any) => {
  const obj = JSON.parse(payload)
  //设备号
  const station = obj.Station
  //数据
  const byteArray = base64StrToArray(obj.Data);
  console.log(byteArray)
  for (let i = 0; i < deviceData.value.groupAndVariables.length; i++) {
    const item = deviceData.value.groupAndVariables[i]
    if (station != item.station) {
      continue
    }


    //载荷
    const weight = item.weight
    if (weight != null) {
      const value = toData(byteArray, weight.dataType, weight.address)
      weight.value = formatValue(value, weight.translate)
      const light = weight.light
      if (light != null) {
        light.value = light.isReverse != toData(byteArray, 1, light.address)
      }
    }



    //高度或者行程
    const stroke = item.stroke
    if (stroke != null) {
      const value = toData(byteArray, stroke.dataType, stroke.address)
      stroke.value = formatValue(value, stroke.translate)
    }


    //档位
    const gear = item.gear
    if (gear != null) {
      const array: any = []
      gear.options.forEach((option: any) => {
        var gearName = option.displayName
        var address = option.address
        var b = toData(byteArray, option.dataType, address)
        if (b) {
          array.push(gearName)
        }
      })
      gear.gears = array
    }


    //电流
    item.currents?.forEach(((e: any) => {
      const value = toData(byteArray, e.dataType, e.address)
      e.value = formatValue(value, e.translate)
    }))


    //开关量
    item.centerSwitchVariables?.forEach((e: any) => {
      e.value = e.isReverse != toData(byteArray, 1, e.address)
    })

    //开关量
    item.switchVariables?.forEach((e: any) => {
      e.value = e.isReverse != toData(byteArray, 1, e.address)
    })

    //模拟量
    item.valueVariables?.forEach((e: any) => {
      const value = toData(byteArray, e.dataType, e.address)
      e.value = formatValue(value, e.translate)
    })

    //开关量+模拟量
    item.matchVariables?.forEach((e: any) => {
      const value = toData(byteArray, e.dataType, e.vAddress)
      e.vValue = formatValue(value, e.translate)
      var sAddress = e.sAddress
      if (sAddress.indexOf(',') > 0) {
        var addressArray = sAddress.split(',')
        for (let index = 0; index < addressArray.length; index++) {
          const addr = addressArray[index]
          var b = e.isReverse != toData(byteArray, 1, addr)
          if (b) {
            e.sValue = true
            break
          }
          e.sValue = false
        }
      } else {
        e.sValue = e.isReverse != toData(byteArray, 1, sAddress)
      }
    })
  }
}



const parseJsonData = (payload: any) => {

  const jsonArray = JSON.parse(payload).Items
  for (let i in jsonArray) {
    const mqttValue = jsonArray[i].Value
    const mqttCode = jsonArray[i].Code

    deviceData.value.groupAndVariables.forEach((item: any) => {
      if (parseGear(item.gear, mqttCode, mqttValue)) {
        return
      }
      const weight = item.weight
      if (weight?.code == mqttCode) {
        weight.value = formatValue(mqttValue, weight.translate)
        return
      }

      if (weight?.light?.code == mqttCode) {
        weight.light.value = weight.light.isReverse != mqttValue
        return
      }


      const stroke = item.stroke
      if (stroke?.code == mqttCode) {
        stroke.value = formatValue(mqttValue, stroke.translate)
        return
      }

      const center = item.centerSwitchVariables?.find((f: any) => f.code == mqttCode)
      if (center != null) {
        center.value = center.isReverse != mqttValue
        return
      }

      const switchs = item.switchVariables?.find((f: any) => f.code == mqttCode)
      if (switchs != null) {
        switchs.value = switchs.isReverse != mqttValue
        return
      }

      const current = item.currents?.find((f: any) => f.code == mqttCode)
      if (current != null) {
        current.value = formatValue(mqttValue, current.translate)
      }


      const variable = item.valueVariables?.find((f: any) => f.code == mqttCode)
      if (variable != null) {
        if (variable.variableType === 10) {//制动
          variable.value = mqttValue === true ? '开启' : '闭合'
        } else {
          variable.value = formatValue(mqttValue, variable.translate)
        }
        return
      }
    })
  }

}




/**
 * 转换数据
 * @param bytes 字节数组
 * @param dataType 数据类型
 * @param address 字节地址
 */
const toData = (bytes: any, dataType: number, address: string) => {
  if (isNullOrEmpty(address)) {
    return ''
  }
  switch (dataType) {
    case 1: //布尔值
      var positionArray = address.split('.')
      if (positionArray.length > 0) {
        //字节位置
        var groupPosition = parseInt(positionArray[0])
        //值
        var childPosition = parseInt(positionArray[1])

        if (groupPosition <= bytes.length - 1) {
          return byte2Boolen(bytes[groupPosition])[childPosition]
        }
      }
      return false

    case 2: //16-bit Unsigned
      var position = parseInt(address)
      return toUInt16(bytes, position)

    case 3: //16-bit Signed
      var position = parseInt(address)
      return toInt16(bytes, position)

    case 4: //32-bit Unsigned
      var position = parseInt(address)
      var value = toUInt32(bytes, position)
      return value

    case 5: //32-bit signed
      var position = parseInt(address)
      var value = toUInt32(bytes, position) << 0
      return value

    default:
      return ''
  }
}

const option = {
  series: [
    {
      type: 'gauge',
      startAngle: 180,
      endAngle: 0,
      center: ['50%', '75%'],
      radius: '100%',
      min: 0,
      max: 100,
      splitNumber: 8,
      axisLine: {
        lineStyle: {
          width: 6,
          color: [
            [0.5, '#92D457'],
            [1, '#367B51']
          ]
        }
      },
      pointer: {
        icon: 'path://M12.8,0.7l12,40.1H0.7L12.8,0.7z',
        length: '12%',
        width: 20,
        offsetCenter: [0, '-60%'],
        itemStyle: {
          color: 'auto'
        }
      },
      axisTick: {
        length: 12,
        lineStyle: {
          color: 'auto',
          width: 1
        }
      },
      splitLine: {
        length: 20,
        lineStyle: {
          color: 'auto',
          width: 5
        }
      },
      axisLabel: {
        show: false
      },
      title: {
        offsetCenter: [0, '-10%'],
        fontSize: 16
      },
      detail: {
        fontSize: 30,
        offsetCenter: [0, '-35%'],
        valueAnimation: true,
        // formatter: function (value) {
        //   return Math.round(value * 100) + '';
        // },
        color: 'inherit'
      },
      data: [
        {
          value: 0,
          name: '电流'
        }
      ]
    }
  ]
};


const timer: any = ref('')

const { run: alarmRun } = useRequest(
  () => getRealAlarm({ deviceId: props.id }),
  {
    manual: true,
    onSuccess: (data: any) => {
      alarmMessageArr.value = data
      timer.value = setTimeout(() => {
        alarmRun()
      }, 1000);
    }
  }
)

</script>

<style lang="less" scoped>
.container {
  display: flex;
  width: 100%;
  height: 100%;
  padding: 20px;
}

.left {
  width: 25%;
  height: 100%;
}

.left_top {
  width: 100%;
  min-height: 300px;
  display: flex;
  flex-direction: column;
  background: #FFFFFF;
  border-radius: 10px;
  padding: 20px;
}

.device_name {
  color: black;
  font-size: 24px;
  font-weight: bold;
  margin-top: 10px;
}


.gear_container {
  margin-top: 30px;
  display: flex;
  padding: 20px;
  width: 100%;
  min-height: 60px;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-image: url(../../assets/img/device_detail_bg1_.png);
}


.left_bottom {
  width: 100%;
  min-height: 300px;
  max-height: 400px;
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  border-radius: 10px;
  padding: 20px;
  background: #FFFDFC linear-gradient(0deg, #FFFDFC, #FFE7ED);
}


.alarm_scroll {
  width: 100%;
  overflow: hidden;
  margin-top: 10px;
  display: flex;
  flex-direction: column;

  .alarm_msg_item {
    display: flex;
    flex-direction: column;
    margin-bottom: 20px;
  }
}

.right {
  margin-left: 20px;
  width: calc(75% - 20px);
  display: flex;
  flex-direction: column;
}

.data_list {
  margin-top: 20px;
  display: flex;
  width: 100%;
  max-height: calc(100% - 80px);
  background: #FFFFFF;
  border-radius: 10px;
  padding: 40px;
  justify-content: space-between;
}

.data_list_left {
  width: 40%;
  display: flex;
  flex-direction: column;
}

.data_list_right {
  width: 54%;
  display: flex;
  flex-direction: column;
  padding: 20px;
  overflow: auto;
  background: #FFFFFF;
  box-shadow: 0px 5px 0px 0px rgba(112, 172, 122, 0.1);
  border-radius: 5px;
  border: 1px solid rgba(64, 123, 81, 0.5);
}

.gear_weight_container {
  display: flex;
  background: #FFFFFF;
  min-height: 90px;
  box-shadow: 0px 5px 0px 0px rgba(112, 172, 122, 0.1);
  border-radius: 5px;
  border: 1px solid rgba(64, 123, 81, 0.5);
  justify-content: space-evenly;
  align-items: center;
}


.center_switch_list {
  margin-top: 30px;
  display: grid;
  background: #FFFFFF;
  box-shadow: 0px 5px 0px 0px rgba(112, 172, 122, 0.1);
  border-radius: 5px;
  align-items: center;
  border: 1px solid rgba(64, 123, 81, 0.5);
  grid-template-columns: 1fr 1fr 1fr;
  justify-content: center;


  .center_switch_list_item:nth-child(3n+3) {
    //3n三个一行，每行第三个元素
    border-right: none;
  }

  .center_switch_list_item:nth-last-child(-n+3) {
    //最后三个元素
    // border-bottom: none;
  }
}

.center_switch_list_item {
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  border-right: 1px solid rgba(64, 123, 81, 0.5);
  border-bottom: 1px solid rgba(64, 123, 81, 0.5);
}


.electric_current_container {
  margin-top: 30px;
  min-height: 300px;
  min-width: 200px;
  background: #FFFFFF;
  box-shadow: 0px 5px 0px 0px rgba(112, 172, 122, 0.1);
  border-radius: 5px;
  align-items: center;
  border: 1px solid rgba(64, 123, 81, 0.5);
  grid-template-columns: 1fr 1fr 1fr;
}



.switch_light {
  width: 60px;
  height: 5px;
  background: #6AD28C;
  border-radius: 3px;


  &.gray {
    background: #ACB1B8
  }

  &.green {
    background: #6AD28C
  }

  &.red {
    background: #D32E26
  }

  &.yellow {
    background: #F49F51
  }
}



.variable_name {
  color: #7C7C7C;
  font-size: 14px;
}

.variable_value {
  color: black;
  font-weight: bold;
  font-size: 14px;
}


.switch_list {
  display: flex;
  width: 100%;
  flex-direction: column;
  justify-content: space-between;
}

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

.value_variable_list_item {
  display: flex;
  align-items: center;
  width: 100%;
  justify-content: space-between;
  border-bottom: 1px solid #EEF0F3;
  padding-bottom: 15px;
  padding-top: 10px;
}

/* 去掉tabs标签栏下的下划线 */
::v-deep .el-tabs__nav-wrap::after {
  position: static !important;
  background-color: #fff;
}

/* 下划线切换高亮 */
::v-deep .el-tabs__active-bar {
  background-color: #367B51;
}

/* 鼠标选中时样式 */
::v-deep .el-tabs__item.is-active {
  color: #367B51;
}

/* 鼠标悬浮时样式 */
::v-deep .el-tabs__item:hover {
  color: #367B51;
  cursor: pointer;
}

::v-deep .el-tabs__item {
  color: #000000;
}

.overloading {
  background: #FFFFFF;
  border-radius: 3px;
  padding: 2px 5px;
  border: 1px solid rgba(64, 123, 81, 0.5);
  font-size: 12px;
  color: #6AD28C;
  margin-left: 15px;

  &.green {
    color: #6AD28C;
    border: 1px solid rgba(64, 123, 81, 0.5);
  }

  &.red {
    color: #D32E26;
    border: 1px solid #D32E26;
  }

}
</style>
