<script setup lang="ts">
import type { Station } from '@/apis/domains';
import { DeviceType } from '@/enums/device-type';
import { type StationAlarmCounts, type StationDevices } from '@/composables/query';
import { ControlOutlined } from '@vicons/antd';
import { Video as VideoIcon } from '@vicons/carbon';
import axios from 'axios';
import { NCard, NStatistic, NTag, NGrid, NGi, NButton, NIcon, useThemeVars, NSpace, NTooltip } from 'naive-ui';
import { toRefs, computed } from 'vue';

interface Props {
  station: Station;
  stationDevices?: StationDevices;
  stationAlarmCounts?: StationAlarmCounts;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  'open-offline-device-detail-modal': [station: Station];
  'open-device-alarm-detail-modal': [station: Station];
  'open-device-params-config-modal': [station: Station];
}>();

const { station, stationDevices, stationAlarmCounts } = toRefs(props);

// 计算总离线设备数量
const offlineDeviceCount = computed(() => {
  let count = 0;
  Object.values(DeviceType).forEach((deviceType) => {
    const offlineDeviceList = stationDevices.value?.[deviceType].filter((device) => device.deviceStatus === '20') ?? [];
    count += offlineDeviceList.length;
  });
  return count;
});
const deviceCount = computed(() => {
  let count = 0;
  Object.values(DeviceType).forEach((deviceType) => {
    count += stationDevices.value?.[deviceType].length ?? 0;
  });
  return count;
});
const alarmCount = computed(() => {
  return stationAlarmCounts.value?.unclassified ?? 0;
});

// 打开对话框
const openOfflineDeviceTreeModal = () => {
  if (station.value.online) {
    emit('open-offline-device-detail-modal', station.value);
  } else {
    window.$message.error('当前车站离线，无法查看');
  }
};
const openDeviceAlarmTreeModal = () => {
  if (station.value.online) {
    emit('open-device-alarm-detail-modal', station.value);
  } else {
    window.$message.error('当前车站离线，无法查看');
  }
};
const openDeviceConfigModal = () => {
  if (station.value.online) {
    emit('open-device-params-config-modal', station.value);
  } else {
    window.$message.error('当前车站离线，无法查看');
  }
};

// 打开视频平台
const openVideoPlatform = async () => {
  try {
    const response = await axios.get<Record<string, string>>('/minio/ndm/ndm-vimps.json');
    const vimpUrl = response.data[station.value.code];
    if (vimpUrl) {
      window.open(vimpUrl, '_blank');
    } else {
      window.$message.warning(`未找到车站编码 ${station.value.code} 对应的视频平台URL`);
      return;
    }
  } catch (error) {
    console.error('获取视频平台URL失败:', error);
    window.$message.error('获取视频平台URL失败');
  }
};

const theme = useThemeVars();
</script>

<template>
  <NCard bordered hoverable size="small" class="station-card" :header-style="{ padding: `6px` }" :content-style="{ padding: `0px 6px 6px 6px` }">
    <template #header>
      <span class="font-smaller">{{ station.name }}</span>
    </template>
    <template #header-extra>
      <NTag :type="station.online ? 'success' : 'error'" size="small">
        {{ station.online ? '在线' : '离线' }}
      </NTag>
    </template>
    <template #default>
      <NSpace>
        <NTooltip trigger="hover">
          <template #trigger>
            <NButton text @click="openVideoPlatform">
              <NIcon>
                <VideoIcon />
              </NIcon>
            </NButton>
          </template>
          <template #default>
            <span style="font-size: xx-small">打开视频平台</span>
          </template>
        </NTooltip>
        <NTooltip trigger="hover">
          <template #trigger>
            <NButton text @click="openDeviceConfigModal">
              <NIcon>
                <ControlOutlined />
              </NIcon>
            </NButton>
          </template>
          <template #default>
            <span style="font-size: xx-small">打开设备配置</span>
          </template>
        </NTooltip>
      </NSpace>
      <NGrid :cols="2" :style="{ opacity: station.online ? '1' : '0.3' }">
        <NGi>
          <NStatistic tabular-nums>
            <template #label>
              <span class="font-xx-small" :class="[station.online ? 'clickable' : '']" @click="openOfflineDeviceTreeModal">离线设备</span>
            </template>
            <template #default>
              <span class="font-small">{{ offlineDeviceCount }}/{{ deviceCount }}</span>
            </template>
            <template #suffix>
              <span class="font-xx-small">台</span>
            </template>
          </NStatistic>
        </NGi>
        <NGi>
          <NStatistic tabular-nums>
            <template #label>
              <span class="font-xx-small" :class="[station.online ? 'clickable' : '']" @click="openDeviceAlarmTreeModal">告警记录</span>
            </template>
            <template #default>
              <span class="font-small">{{ alarmCount }}</span>
            </template>
            <template #suffix>
              <span class="font-xx-small">条</span>
            </template>
          </NStatistic>
        </NGi>
      </NGrid>
    </template>
  </NCard>
</template>

<style scoped lang="scss">
.clickable {
  text-decoration: underline dashed;
  cursor: pointer;
  transition: color 0.2s ease;

  &:hover {
    color: v-bind('theme.primaryColorHover');
  }
}

.font-xx-small {
  font-size: xx-small;
}

.font-medium {
  font-size: medium;
}

.font-small {
  font-size: small;
}

.font-smaller {
  font-size: smaller;
}
</style>
