<template>
  <div class="realtimeData-content">

    <div v-loading="loading" class="mec-content">
      <div class="mec-item" v-for="(item, index) in varDictMecGroupData" :key="index">
        <div class="mec-title">
          {{ (item.mec_type 
                  ? (dictStore.getDictLabel("mec_type", item.mec_type) as any)
                  : undefined
                )?.dict_label || item.mec_type }}
        </div>
        <div class="mec-content-item">
          <div class="number-type-content" v-for="(temp, index1) in item.number_type_list" :key="index1">
            <span>{{ temp.var_name }}</span>
            <div>
              <span style="font-size: 22px;">{{ temp.value }}</span>
            </div>
          </div>
          <div style="margin-top: 30px;">
            <div class="bool-type-content" v-for="(temp, index1) in item.bool_type_list" :key="index1">
              <span>{{ temp.var_name }}</span>
              <span :class="getBgColor(temp.value, temp.switch_type)"></span>
            </div>
          </div>
        </div>
      </div>
      <div v-if="varDictMecGroupData.length === 0" class="el-table-empty">
        <el-image :src="emptybg"></el-image>
        <span>当前无数据</span>
      </div>
    </div>
  </div>

</template>
<script setup lang="ts">
import BizVarDictAPI, { BizVarDictTable,VarDictMecGroupData,MecDataItem } from '@/api/module_business/vardict'
import { useRoute } from 'vue-router'
import { useDictStore } from "@/store";
import emptybgUrl from '@/assets/images/empty-bg.png';
import MqttUtil, { MqttMessageCallback } from '@/utils/mqttUtil';
import { reactive, onMounted, onUnmounted, inject } from 'vue';
import { gearCalculation } from '@/utils/common';
import { S } from 'vue-router/dist/router-CWoNjPRp.mjs';

const route = useRoute()
const receiveData = inject<(data: { craneName: string; isShowHomeButton: boolean }) => void>('receiveData');
const craneInfo = JSON.parse(localStorage.getItem('craneInfo') || '{}')
const varDictMecGroupData = ref<VarDictMecGroupData[]>([])
const loading = ref(true);
const emptybg = ref(emptybgUrl)

const mqttConfig = {
  wsUrl: import.meta.env.VITE_APP_WS_ENDPOINT || 'ws://127.0.0.1:9001',
  topics: ['cdc/'+craneInfo.crane_no+'/analog/batch/#','cdc/'+craneInfo.crane_no+'/digital/#']
};

const mqttUtil = new MqttUtil(mqttConfig);


const getCraneMecTreeData = async () => {
  const response = await BizVarDictAPI.varDictMecGroup(craneInfo.crane_no);
  varDictMecGroupData.value = mecDataFormat(response.data.data)
  //挡位计算
  gearCalculation(varDictMecGroupData.value)
  loading.value = false;
  //localStorage.setItem('varDict', JSON.stringify(deviceStateData.value))
}

const mecDataFormat = (mecData: MecDataItem[]) => {
  const resultData: VarDictMecGroupData[] = []
  if (mecData) {
    mecData.forEach((item) => {
      let numberTypelist: BizVarDictTable[] = []
      let boolTypeList: BizVarDictTable[] = []
      let gearList: BizVarDictTable[] = []
      numberTypelist = [...item.analog_varList]
      boolTypeList = [...item.digital_varList]
      if(item.mec_type != '0' && item.mec_type != '6'){
        numberTypelist.push({
          var_code: 'G00'+item.mec_type,
          var_name: '挡位',
          value: '0'
        })
      }
      boolTypeList.forEach((boolItem) => {
        if (boolItem.var_category == "1") {
          gearList.push(boolItem) 
        }
      })
      resultData.push({
        mec_type: item.mec_type,
        bool_type_list: boolTypeList,
        gear_list: gearList,
        number_type_list: numberTypelist
      })
    })
  }
  return reactive(resultData);
}

// 字典仓库与需要加载的字典类型
const dictStore = useDictStore()
const dictTypes: any = [
  'mec_type'
]

const getData = () => {
  getCraneMecTreeData()
}
const getBgColor = (bool: string | undefined, type: string | undefined) => {
  
  const validType = type || '0';

  const falseColorMap: Record<string, string> = {
    '0': 'pilot-lamp-bg-grey',
    '1': 'pilot-lamp-bg-grey',
    '2': 'pilot-lamp-bg-green',
    '3': 'pilot-lamp-bg-green',
    '4': 'pilot-lamp-bg-green'
  };

  const trueColorMap: Record<string, string> = {
    '0': 'pilot-lamp-bg-green',
    '1': 'pilot-lamp-bg-green',
    '2': 'pilot-lamp-bg-yellow',
    '3': 'pilot-lamp-bg-orange',
    '4': 'pilot-lamp-bg-red'
  };

  const class_name = bool 
    ? trueColorMap[validType]
    : falseColorMap[validType] || 'pilot-lamp-bg-grey';

  return class_name;
};

const handleMqttMessage: MqttMessageCallback = (topic, payload) => {
  let topic_levels = topic.split('/')
  let crane_no = topic_levels[1]
  let type = topic_levels[2]
  let var_code = topic_levels[3]
  varDictMecGroupData.value.forEach(item => {
    if(type == 'analog' && item.number_type_list && Array(item.number_type_list)){
      item.number_type_list.forEach(numberItem => {
        const targetItem = payload.data.find(
          (payloadItem: any) => numberItem.var_code === payloadItem.var_code
        )
        if (targetItem) numberItem.value = targetItem.value
      })
    }else if(type == 'digital' && item.bool_type_list && Array(item.bool_type_list)){
      const targetItem = item.bool_type_list.find(
        (boolItem: any) => boolItem.var_code === var_code
      )
      if (targetItem) targetItem.value = payload.value
    }
  })
  //挡位计算
  gearCalculation(varDictMecGroupData.value)
}


onMounted(async () => {
  if (dictTypes.length > 0) {
    await dictStore.getDict(dictTypes)
  }
  if (receiveData) {
    receiveData({ craneName: craneInfo.crane_name ?? '', isShowHomeButton: true });
  }
  getData()
  mqttUtil.initConnect(handleMqttMessage);
});

onUnmounted(() => {
  mqttUtil.releaseResources();
});

</script>
<style lang="less" scoped>
.realtimeData-content {
  width: 100%;

  :deep(.el-loading-parent--relative) {
    --el-mask-color: rgba(255, 255, 255, 0.1);
  }
}

.text-style {
  color: #7BA8FF;
  font-size: 18px;
}

.mec-content {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(calc((100% - 4 * 10px) / 5), 1fr));
  gap: 10px;
  height: calc(100vh - 70px - 5px - 50px - 10px);
  overflow: auto;
}

.mec-item {
  height: calc(100vh - 70px - 5px - 50px - 10px);
  color: #ffffff;
  background: linear-gradient(to bottom, #14428C 0%, #121F34 15%);
  border: 2px solid rgba(53, 110, 219, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.mec-title {
  width: 200px;
  height: 50px;
  background-image: url('../../assets/img/mec-title-bg.png');
  text-align: center;
  line-height: 50px;
  color: #8ECAFF;
  font-size: 24px;
}

.number-type-content {
  height: 55px;
  padding: 0px 15px;
  margin-top: 10px;
  background-color: #112648;
  color: #ffffff;
  font-size: 18px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.bool-type-content {
  height: 40px;
  color: #ffffff;
  font-size: 18px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #223555;
  border-bottom: 1px solid #223555;
}

.mec-content-item {
  overflow: auto;
  width: 100%;
  padding: 20px 20px 0px 20px;
}

.pilot-lamp-bg-red {
  width: 20px;
  height: 20px;
  background: #F9143D;
  border-radius: 50%;
}

.pilot-lamp-bg-green {
  width: 20px;
  height: 20px;
  background: #0EED52;
  border-radius: 50%;
}

.pilot-lamp-bg-grey {
  width: 20px;
  height: 20px;
  background: #4A4F5D;
  border-radius: 50%;
}

.pilot-lamp-bg-yellow {
  width: 20px;
  height: 20px;
  background: #FFD800;
  border-radius: 50%;
}

.pilot-lamp-bg-orange {
  width: 20px;
  height: 20px;
  background: #f39902;
  border-radius: 50%;
}

.el-table-empty {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #8ECAFF;

  img {
    width: 200px;
    height: auto;
    margin-bottom: 20px;
  }
}

::-webkit-scrollbar {
  width: 5px;
  height: 5px;
}

::-webkit-scrollbar-track {
  border-radius: 10px;
}

::-webkit-scrollbar-thumb {
  border-radius: 7px;
  background-color: #798DAE;
}
</style>