<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, NTag, NButton, NIcon, useThemeVars, NSpace, NFlex, NText, NTooltip } from 'naive-ui';
import { toRefs, computed } from 'vue';

const props = defineProps<{
  station: Station;
  stationDevices?: StationDevices;
  stationAlarmCounts?: StationAlarmCounts;
}>();

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 onlineDeviceCount = computed(() => {
  let count = 0;
  Object.values(DeviceType).forEach((deviceType) => {
    const onlineDeviceList = stationDevices.value?.[deviceType].filter((device) => device.deviceStatus === '10') ?? [];
    count += onlineDeviceList.length;
  });
  return count;
});
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>
      <NTooltip v-if="station.ip" trigger="click">
        <template #trigger>
          <span class="font-smaller">{{ station.name }}</span>
        </template>
        <span>{{ station.ip }}</span>
      </NTooltip>
      <span v-else 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 vertical :size="8">
        <NFlex :justify="'flex-start'" class="actions">
          <NButton quaternary size="tiny" :focusable="false" :disabled="!station.online" @click="openVideoPlatform">
            <NIcon>
              <VideoIcon />
            </NIcon>
            <span class="btn-text">视频平台</span>
          </NButton>

          <NButton quaternary size="tiny" :focusable="false" :disabled="!station.online" @click="openDeviceConfigModal">
            <NIcon>
              <ControlOutlined />
            </NIcon>
            <span class="btn-text">设备配置</span>
          </NButton>
        </NFlex>

        <NFlex vertical :size="0" class="metrics" :style="{ opacity: station.online ? '1' : '0.5' }">
          <NFlex justify="space-between" align="baseline" class="metric-item">
            <NText depth="3" class="metric-label" :class="[station.online ? 'clickable' : '']" @click="station.online && openOfflineDeviceTreeModal()">设备统计</NText>
            <span class="metric-value">
              <span :style="{ color: onlineDeviceCount > 0 ? theme.successColor : '' }">{{ onlineDeviceCount }}</span>
              <NText depth="3" class="slash">/</NText>
              <span :style="{ color: offlineDeviceCount > 0 ? theme.errorColor : '' }">{{ offlineDeviceCount }}</span>
              <NText depth="3" class="slash">/</NText>
              <span>{{ deviceCount }}</span>
              <NText depth="3" class="unit">台</NText>
            </span>
          </NFlex>

          <NFlex justify="space-between" align="baseline" class="metric-item">
            <NText depth="3" class="metric-label" :class="[station.online ? 'clickable' : '']" @click="station.online && openDeviceAlarmTreeModal()">告警记录</NText>
            <span class="metric-value">
              <span>{{ alarmCount }}</span>
              <NText depth="3" class="unit">条</NText>
            </span>
          </NFlex>
        </NFlex>
      </NSpace>
    </template>
  </NCard>
</template>

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

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

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

.btn-text {
  margin-left: 6px;
  font-size: xx-small;
  color: v-bind('theme.textColor3');
}

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

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

.unit,
.slash {
  margin-left: 4px;
  font-size: xx-small;
}
</style>
