<template>
  <el-row :gutter="0" class="overview-row">
    <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
      <div class="overview-left">
        <div class="overview-left-title">
          <span>报警总览</span>
        </div>
        <div class="overview-left-content">
          <ul v-loading="alarm_loading">
            <li v-for="(item, index) in varDictData" :key="index">
              <div v-if="item.value" class="content-item" :class="getColor(item.switch_type?.toString() ?? '')">
                <IconAlarm />
                <span style="width:120px; margin-left: 15px;">{{ item.crane_name }}</span>
                <span style="width: 2px;height: 60%;margin: 0px 30px;" :class="getColorSpan(item.switch_type?.toString() ?? '')" />
                <span>{{ item.var_name }}</span>
              </div>
            </li>
          </ul>
          <div v-if="!alarm_loading && !hasActiveAlarms" class="el-table-empty">
            <el-image :src="emptybg"></el-image>
            <span>当前无数据</span>
          </div>
        </div>
      </div>
    </el-col>
    <el-col :xs="16" :sm="16" :md="16" :lg="16" :xl="16">
      <div class="overview-right">
        <div class="overview-right-title">
          <span>起重机总览</span>
        </div>
        <div class="overview-right-content">
          <pro-table :height="tabHeight" :loading="tab_loading" :data="craneData" :config="tableConfig">
            <template #default="{ row, label }">
              <div v-if="label === '操作'" style="width:100%;height:100%;display: flex;justify-content: center;">
                <div class="button-container" @click="handleClick(row)">
                  查看
                </div>
              </div>
              <div v-if="label === '在线状态'">
                <el-tag effect="dark" v-if="!row.work_status && row.work_status != '0'" type="warning">连接中</el-tag>
                <el-tag effect="dark" v-if="row.work_status == '0'" type="danger">离线</el-tag>
                <el-tag effect="dark" v-if="row.work_status == '1'" type="success">运行</el-tag>
                <el-tag effect="dark" v-if="row.work_status == '2'" type="info">停止</el-tag>
                <el-tag effect="dark" v-if="row.work_status == '3'" type="success">工作</el-tag>
                <el-tag effect="dark" v-if="row.work_status == '4'" type="primary">空闲</el-tag>
              </div>
            </template>
          </pro-table>
        </div>
      </div>
    </el-col>
  </el-row>
</template>

<script lang="ts" setup>
import BizCraneAPI, { BizCranePageQuery, BizCraneTable } from '@/api/module_business/crane'
import BizVarDictAPI, { BizVarDictPageQuery, BizVarDictTable } from '@/api/module_business/vardict'
import emptybgUrl from '@/assets/images/empty-bg.png';
import { onMounted, onUnmounted, ref, reactive, inject } from 'vue';
import { useRouter } from 'vue-router';
import MqttUtil, { MqttMessageCallback } from '@/utils/mqttUtil';

// 路由 & 全局注入
const router = useRouter()
const receiveData = inject<(data: { craneName: string; isShowHomeButton: boolean }) => void>('receiveData');

// 静态资源 & 样式相关
const emptybg = ref(emptybgUrl)
const tabHeight = ref('calc(100vh - 70px - 60px - 40px - 42px)')

// 数据加载状态
const alarm_loading = ref(true);
const tab_loading = ref(true)

// 业务数据
const craneData = ref<BizCraneTable[]>([]);
const varDictData = ref<BizVarDictTable[]>([])

const hasActiveAlarms = computed(() => {
  return varDictData.value.some(item => item.value);
});

const mqttConfig = {
  wsUrl: import.meta.env.VITE_APP_WS_ENDPOINT || 'ws://127.0.0.1:9001',
  topics: ['cdc/+/alarm/#', 'cdc/+/status']
};
const mqttUtil = new MqttUtil(mqttConfig);

// 表格配置
const tableConfig = ref([
  {
    prop: 'crane_no',
    label: '编号'
  },
  {
    prop: 'crane_name',
    label: '起重机名称'
  },
  {
    prop: 'crane_model',
    label: '型号'
  },
  {
    prop: 'ip_address',
    label: 'IP地址'
  },
  {
    prop: 'online_status',
    label: '在线状态',
    slot: true
  },
  {
    label: '操作',
    slot: true
  }
])

const queryFormCraneData = reactive<BizCranePageQuery>({
  page_no: 1,
  page_size: 100,
  crane_name: undefined,
  crane_no: undefined,
  crane_model: undefined,
  ip_address: undefined,
  status: undefined,
  created_time: undefined,
  updated_time: undefined,
  created_id: undefined,
  updated_id: undefined,
});

const queryFormVarDictData = reactive<BizVarDictPageQuery>({
  page_no: 1,
  page_size: 100,
  crane_no: undefined,
  var_code: undefined,
  var_name: undefined,
  mec_type: undefined,
  switch_type: '2',
  gateway_id: undefined,
  var_group: undefined,
  var_category: undefined,
  is_top_show: undefined,
  is_save: undefined,
  is_overview_top_show: undefined,
  is_home_page_show: undefined,
  status: undefined,
  created_time: undefined,
  updated_time: undefined,
  created_id: undefined,
  updated_id: undefined,
  is_api_request: 'True',
});

// 操作按钮点击事件
const handleClick = (item: BizCraneTable) => {
  if (receiveData) {
    receiveData({ craneName: item.crane_name ?? '', isShowHomeButton: true });
  }
  localStorage.setItem('craneInfo', JSON.stringify(item))
  router.push('/detail');
}

// 获取起重机列表数据
const getCraneListData = async () => {
  try {
    tab_loading.value = true
    const response = await BizCraneAPI.listBizCraneStatus(queryFormCraneData);
    craneData.value = response.data.data.items;
  } finally {
    tab_loading.value = false
  }
}

const getVarDictData = async () => {
  try {
    alarm_loading.value = true;
    const response = await BizVarDictAPI.listBizVarDictAlarms(queryFormVarDictData);
    varDictData.value = response.data.data.items;
  } finally {
    alarm_loading.value = false
  }
}

// 颜色样式处理
const getColor = (type: string) => {
  switch (type) {
    case '2':
      return 'content-item-yellow';
    case '3':
      return 'content-item-orange';
    case '4':
      return 'content-item-red';
  }
}
const getColorSpan = (type: string) => {
  switch (type) {
    case '2':
      return 'content-item-span-yellow';
    case '3':
      return 'content-item-span-orange';
    case '4':
      return 'content-item-span-red';
  }
}

// 初始化业务数据
const getData = () => {
  getCraneListData()
  getVarDictData()
}

const handleMqttMessage: MqttMessageCallback = (topic, payload) => {
  let topic_levels = topic.split('/')
  let crane_no = topic_levels[1]
  let suffix = topic_levels[2]
  if (suffix === 'alarm') {
    varDictData.value.forEach((item) => {
      if (item.crane_no === crane_no && item.var_code === payload.var_code) {
        item.value = payload.value
      }
    });
  } else if (suffix === 'status') {
    craneData.value.forEach((craneItem) => {
      if (craneItem.crane_no === crane_no) {
        craneItem.work_status = payload.status;
      }
    });
  }
}


onMounted(async () => {
  getData();
  mqttUtil.initConnect(handleMqttMessage);
  
  if (receiveData) {
    receiveData({ craneName: '', isShowHomeButton: false });
  }
});

onUnmounted(() => {
  mqttUtil.releaseResources();
});
</script>

<style lang="less" scoped>
.overview-row {
  padding: 20px 20px;
}

.overview-left {
  height: calc(100vh - 70px - 40px);
  margin-right: 20px;
  background: linear-gradient(to bottom, #14428C 0%, #121F34 12%);
  border: 1px solid #284988;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0px 20px;
}

.overview-left-title {
  width: 400px;
  height: 60px;
  background-image: url('../../../assets/images/overview-left-title.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #8ECAFF;
  font-size: 24px;
}

.overview-left-content {
  flex: 1;
  width: 100%;
  margin-top: 40px;
  overflow: auto;

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

.content-item {
  width: 100%;
  height: 40px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  padding: 0px 17px;
  font-size: 16px;
}

.content-item-red {
  background: linear-gradient(to right, rgba(249, 20, 61, 0.3) 0%, rgba(89, 105, 164, 0.3) 40%, rgba(23, 41, 68, 0.3) 80%);
  color: #F9143D;
}

.content-item-yellow {
  background: linear-gradient(to right, rgba(255, 216, 0, 0.3) 0%, rgba(89, 105, 164, 0.3) 40%, rgba(23, 41, 68, 0.3) 80%);
  color: #FFD800;
}

.content-item-orange {
  background: linear-gradient(to right, rgba(243, 153, 2, 0.3) 0%, rgba(89, 105, 164, 0.3) 40%, rgba(23, 41, 68, 0.3) 80%);
  color: #f39902;
}

.content-item-span-red {
  background-color: #F9143D;
}

.content-item-span-yellow {
  background-color: #FFD800;
}

.content-item-span-orange {
  background-color: #f39902;
}

.overview-right {
  height: calc(100vh - 70px - 40px);
  background: linear-gradient(to bottom, #14428C 0%, #121F34 12%);
  border: 1px solid #284988;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0px 20px;
}

.overview-right-title {
  width: 640px;
  height: 60px;
  background-image: url('../../../assets/images/overview-right-title.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #8ECAFF;
  font-size: 24px;
}

.overview-right-content {
  width: 100%;
  margin-top: 40px;
  overflow: auto;

  :deep(.el-table__header) {
    border-bottom: 1px solid #3E5487;
  }

  :deep(.el-table__body) {
    font-size: 16px;
  }

  .button-container {
    width: 80px;
    height: 35px;
    background: linear-gradient(to bottom, #0949C6, #0A8DD8);
    text-align: center;
    line-height: 35px;
    border-radius: 5px;
    font-size: 16px;
    cursor: pointer;
  }
}

.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>