<template>
  <div class="g-p20 content">
    <div class="head g-fx">
      <div class="head__first">
        <div class="first-info">
          <div class="info1">基本信息</div>
          <div class="info2">
            {{ equipmentInfo.name }}
          </div>
          <div class="info3">
            <span>设备序列号 </span> <span class="g-ml-20">{{ equipmentInfo.code }}</span>
          </div>
          <div class="info3">
            <span>监控编号</span> <span class="g-ml-20">{{ equipmentInfo.productNo }}</span>
          </div>
          <!-- <div class="info3"><span>设备分组</span> <span class="g-ml-20">5555</span></div> -->
          <div class="info3">
            <span>设备型号</span> <span class="g-ml-20">{{ equipmentInfo.model }}</span>
          </div>
        </div>
        <div class="first-bg" :class="{ isOnLine: !equipmentInfo?.isOnline }"></div>
      </div>
      <div class="head__second">
        <div class="second-info">
          <div class="second-name">
            {{ '报警 ' + alarmList.array.length }}
          </div>
          <div class="second-alarm"><live-message :list="alarmList.array"></live-message></div>
        </div>
        <div class="second-info">
          <div class="second-name bg2">
            {{ '预警 ' + warningList.array.length }}
          </div>
          <div class="second-warning"><live-message :list="warningList.array"></live-message></div>
        </div>
      </div>
    </div>
    <main class="main">
      <div class="main__item" v-for="(item, index) in dataSource.data" :key="item">
        <div class="item-box">
          <div class="item-title">{{ item.groupName }}</div>
          <div class="item-info" v-if="item?.stroke || item?.weight || item?.gear">
            <div class="item-info__el" v-if="item?.stroke">
              <div class="distance">
                {{ formatValue(item?.stroke?.value, item?.stroke?.translate) }}
                <span style="font-size: 12px">{{ item.stroke?.unit }}</span>
              </div>
              <div class="text">
                {{ item?.isHoist ? '高度' : '行程' }}
              </div>
            </div>
            <div class="item-info__el" v-if="item?.weight">
              <div class="distance">
                {{ formatValue(item?.weight?.value, item?.weight?.translate) }}
                <span style="font-size: 12px">{{ item.weight?.unit || item.weight?.unitName }}</span>
              </div>
              <div class="text">
                载荷
                <div class="weight-color" :style="{ background: formatWeightLight(item.weight?.light) }"></div>
              </div>
            </div>
            <div class="item-info__el" v-if="item?.gear">
              <el-tooltip class="box-item" effect="dark" :content="formatGears(item?.gear)" placement="top-start">
                <div class="distance g-no-warp">
                  {{ formatGears(item?.gear) }}
                </div>
              </el-tooltip>
              <div class="text">档位</div>
            </div>
          </div>
          <div class="item-info2">
            <div class="item-info2__el" v-for="son in item?.gridArray">
              <div class="line" :style="{ background: getColor(son) }"></div>
              <div class="text">{{ son.variableName }}</div>
            </div>
          </div>
          <el-divider border-style="dashed" />
          <div class="item-info3">
            <div class="item-info3__el" v-for="el in item.switchVariables">
              <div class="text">{{ el.variableName }}</div>
              <div class="g-fx" style="align-items: center">
                <div style="margin-left: 10px" class="line" :style="{ background: getColor(el) }"></div>
              </div>
            </div>
            <div class="item-info3__el" v-for="el in item?.matchVariables">
              <div class="text">{{ el.variableName }}</div>
              <div class="g-fx" style="align-items: center">
                <div>{{ formatValue(el.value, el.translate) + ' ' + el.unitName }}</div>
                <div style="margin-left: 10px" class="line" :style="{ background: getMatchBgColor(el) }"></div>
              </div>
            </div>
            <div class="item-info3__el" v-for="el in item?.valueVariables">
              <div class="text">{{ el.variableName }}</div>
              <div class="g-fx" style="align-items: center">
                <div>{{ formatValue(el.value, el.translate) + el.unitName }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script lang="ts" setup name="实时数据">
import { getGroupAndVariables } from '@/api'
import { fetchDeviceInfoAll } from '@/api/deviceAuthorize'
import { useSidebarStore } from '@/store/sidebar'
import { mqttMessageCallback } from '@/utils/hooks'
import { formatGears, formatWeightLight, formatValue } from '@/utils/tools'
import LiveMessage from './live-message.vue'
let deviceId: any = ref('')
let equipmentInfo: any = ref({})
const sidebar = useSidebarStore()

onUnmounted(() => {
  window.onUnsubscribe(`Json/${equipmentInfo?.value?.code}`)
})
/** 警告数组 */
const warningList: any = reactive({ array: [] })
/** 报警数组 */
const alarmList: any = reactive({ array: [] })

onMounted(async () => {
  const eId = useQuery('id')
  sidebar.setEquipmentId(eId)
  deviceId.value = eId
  getDeviceInfo(eId)
  await dataSource.getData()

  dataSource.data.forEach((group: any) => {
    group.gridArray = group.switchVariables.slice(0, 6)
    group.switchVariables = group.switchVariables.slice(6)

    var light = group.weight?.light
    if (light != null) {
      updateAlarm('red', group.groupName + '超载', light.value)
    }
    group.gridArray.forEach((g: any) => {
      updateAlarm(g.trueLight, group.groupName + g.variableName, g.value)
    })

    group.switchVariables.forEach((g: any) => {
      updateAlarm(g.trueLight, group.groupName + g.variableName, g.value)
    })
  })
})
const dataSource = useRequest(() => getGroupAndVariables({ deviceId: deviceId.value }), false)

const getDeviceInfo = async (id: string) => {
  const data = await fetchDeviceInfoAll(id)
  equipmentInfo.value = data
  window.onSubscribe?.(`Json/${equipmentInfo.value.code}`)
  mqttMessageCallback((topic: any, payload: any) => {
    parseData(payload)
  })
  
}

const parseData = (payload: any) => {
  
  const jsonArray = JSON.parse(payload).Items
  console.log(jsonArray)
  for (var i in jsonArray) {
    const mqttValue = jsonArray[i].Value
    const mqttCode = jsonArray[i].Code

    dataSource.data.forEach((group: any) => {
      if (parseGear(group.gear, mqttCode, mqttValue)) {
        return
      }
      var weight = group.weight
      if (weight?.code == mqttCode) {
        weight.value = mqttValue
        return
      }

      if (weight?.light?.code == mqttCode) {
        weight.light.value = weight.light.isReverse != mqttValue
        updateAlarm('red', group.groupName + '超载', weight.light.value)
        return
      }

      var stroke = group.stroke
      if (stroke?.code == mqttCode) {
        stroke.value = mqttValue
        return
      }

      var grid = group.gridArray.find((f: any) => f.code == mqttCode)
      if (grid != null) {
        grid.value = grid.isReverse != mqttValue
        updateAlarm(grid.trueLight, group.groupName + grid.variableName, grid.value)
        return
      }

      var switchs = group.switchVariables.find((f: any) => f.code == mqttCode)
      if (switchs != null) {
        switchs.value = switchs.isReverse != mqttValue
        updateAlarm(switchs.trueLight, group.groupName + switchs.variableName, switchs.value)
        return
      }

      var variable = group.valueVariables.find((f: any) => f.code == mqttCode)
      if (variable != null) {
        if (variable.variableType == 10) {
          variable.value = mqttValue == true ? '开启' : '闭合'
        } else {
          variable.value = mqttValue
        }
        return
      }
    })
  }
}

//解析档位
const parseGear = (gear: any, code: any, value: any) => {
  if (gear != null) {
    //取出当前档位
    let option = gear.options.find((f: any) => f.variableCode == code)
    if (option != null) {
      //当前档位
      let currentGearName = option.displayName

      if (value) {
        //不存在添加（加档）
        let g = gear.gears.find((f: any) => f == currentGearName)
        if (g == null) {
          gear.gears.push(currentGearName)
        }
      } else {
        //存在删除（减档）
        gear.gears = gear.gears.filter((f: any) => f != currentGearName)
      }
      return true
    }
  }
  return false
}

const updateAlarm = (trueLight: string, name: string, value: any) => {
  if (value == true || value == 'true') {
    if (trueLight == 'red') {
      var alarm = alarmList.array.find((f: any) => f == name)
      if (alarm == null) {
        alarmList.array.push(name)
      }
    }
    if (trueLight == 'yellow') {
      var warn = warningList.array.find((f: any) => f == name)
      if (warn == null) {
        warningList.array.push(name)
      }
    }
  } else {
    alarmList.array = alarmList.array.filter((f: any) => f != name)
    warningList.array = warningList.array.filter((f: any) => f != name)
  }
}

const getColor = (el: any) => {
  const obj: any = {
    green: '#6AD28C',
    red: '#FE5656',
    yellow: '#F49F51',
    gray: '#999999'
  }
  if (el.value || el.value === 'true') {
    return obj[el.trueLight]
  } else {
    return obj[el.falseLight]
  }
}

const getMatchBgColor = (el: any) => {
  const obj: any = {
    green: '#6AD28C',
    red: '#FE5656',
    yellow: '#F49F51',
    gray: '#999999'
  }
  if (el.sValue || el.sValue === 'true') {
    return obj[el.trueLight]
  } else {
    return obj[el.falseLight]
  }
}
</script>

<style lang="less" scoped>
.isOnLine {
  filter: grayscale(100%);
}

.content {
  background-color: #c8cfdf;
}

.head {
  height: 260px;
  position: relative;

  &__first {
    width: 100%;
    min-width: 850px;
    height: 100%;
    border-radius: 10px;
    background: linear-gradient(36deg, #5f7cd6, #86b0e9);
    position: relative;

    .first-info {
      padding: 40px;
      color: #fff;
    }

    .info1 {
      background-color: rgba(42, 55, 110, 0.4);
      font-weight: bold;
      font-size: 16px;
      width: 87px;
      padding: 5px;
      text-align: center;
      border-radius: 5px;
    }

    .info2 {
      margin: 15px 0;
      font-weight: bold;
      font-size: 24px;
    }

    .info3 {
      margin: 5px 0;
      font-size: 12px;

      span:first-child {
        display: inline-block;
        width: 60px;
      }
    }

    .first-bg {
      position: absolute;
      left: 42%;
      top: 50%;
      transform: translate(-20%, -55%);
      background-image: url(../../../assets/img/equipment1.png);
      background-size: 100% 100%;
      width: 40%;
      height: 138px;
      background-repeat: no-repeat;
    }
  }

  &__second {
    width: 260px;
    min-width: 260px;
    margin-left: 20px;
    border-radius: 10px;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    right: 15px;

    .second-info {
      height: 75px;
      display: flex;
      border-radius: 15px;
      background: RGBA(229, 193, 164, 0.5);
      border: 1px solid #c49159;
      align-items: center;
      padding-left: 20px;
    }

    ::v-deep(.second-info) {
      .el-carousel__indicator {
        display: none;
      }
    }

    .second-info:first-child {
      margin-bottom: 20px;
      background: RGBA(229, 163, 169, 0.5);
      border: 1px solid #cd524a;
    }

    .second-name {
      width: 70px;
      height: 45px;
      background: #cd524a;
      border-radius: 10px;
      color: #fff;
      text-align: center;
      line-height: 45px;
      font-size: 12px;
      margin-right: 10px;
    }

    .second-alarm {
      color: #c44b44;
      font-size: 12px;
      width: 120px;
    }

    .second-warning {
      color: #c57d31;
      font-size: 12px;
      width: 120px;
    }

    .bg2 {
      background: #d79146;
    }

    .second-time {
      text-align: center;
      font-size: 12px;
      margin: 3px;
    }

    .color2 {
      color: #c57d31;
    }

    .second-text {
      align-items: center;
      justify-content: center;
    }

    .icon-right {
      display: flex;
      align-items: center;

      .el-icon {
        font-size: 12px;
        transform: scale(0.9);
      }
    }

    .second-text {
      font-size: 12px;
    }
  }
}

.main {
  margin: 20px 0;
  display: flex;
  justify-content: flex-start;
  overflow-x: auto;
  margin-bottom: 40px;

  &__item {
    height: auto;
    width: calc(100% / 5.2);
    min-width: 308px;
    margin-left: 20px;
    margin-bottom: 20px;

    &:first-child {
      margin-left: 0px;
    }

    .item-box {
      min-height: 60px;
      background-color: #fff;
      padding: 30px;
      border-radius: 10px;
    }

    .item-title {
      font-weight: bold;
    }

    .item-info {
      background-color: rgba(214, 220, 239, 0.5);
      height: 90px;
      margin: 20px 0;
      border-radius: 5px;
      display: flex;
      padding: 15px 0;
      justify-content: center;

      .item-info__el {
        text-align: center;
        width: 50%;
        position: relative;
      }

      .distance {
        font-weight: bold;
        font-size: 18px;
        margin: 8px 0;
        height: 20px;
        line-height: 20px;
      }

      .weight-color {
        position: absolute;
        width: 20px;
        height: 4px;
        border-radius: 2px;
        position: absolute;
        right: 0%;
        top: 50%;
        transform: translate(-10%, -50%);
      }

      .text {
        color: rgba(74, 83, 115, 0.7);
        font-size: 14px;
        position: relative;
        width: 50ppx;
      }
    }

    .item-info2 {
      display: flex;
      flex-wrap: wrap;
      margin-top: 15px;

      &__el {
        width: calc(100% / 3);
        text-align: center;
        margin: 8px 0;
      }

      .line {
        width: 50px;
        height: 4px;
        background: rgb(2, 252, 67);
        margin: 0 auto;
        border-radius: 2px;
      }

      .text {
        color: #4a5373;
        font-size: 12px;
        margin: 8px 0;
        text-align: center;
      }
    }

    .item-info3 {
      &__el {
        margin: 25px 0;
        display: flex;
        justify-content: space-between;
        width: 100%;
      }

      .line {
        width: 30px;
        height: 4px;
        background: rgb(2, 252, 67);
        border-radius: 2px;
      }

      .text {
        color: rgba(74, 83, 115, 0.7);
        font-size: 14px;

        &:last-child {
          color: #333;
        }
      }
    }

    .item-info4 {
      margin: 25px 0;

      display: flex;
      justify-content: space-between;

      .text {
        color: #4a5373;
      }
    }
  }
}
</style>
