<script setup lang="ts">
import type { Station, StationAlarmCounts, StationDevices } from '@/apis';
import { DeviceType } from '@/enums';
import { MoreOutlined, EllipsisOutlined } from '@vicons/antd';
import axios from 'axios';
import { NCard, NTag, NButton, NIcon, useThemeVars, NFlex, NText, NTooltip, NDropdown, type DropdownOption } 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 dropdownOptions: DropdownOption[] = [
  {
    label: '视频平台',
    key: 'video-platform',
    onClick: openVideoPlatform,
  },
  {
    label: '设备配置',
    key: 'device-config',
    onClick: openDeviceConfigModal,
  },
];

const selectDropdownOption = (key: string, option: DropdownOption) => {
  if (typeof option['onClick'] === 'function') {
    option['onClick']();
  }
};

const theme = useThemeVars();
</script>

<template>
  <NCard bordered hoverable size="medium" 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-medium">{{ station.name }}</span>
        </template>
        <span>{{ station.ip }}</span>
      </NTooltip>
      <span v-else class="font-medium">{{ station.name }}</span>
    </template>
    <template #header-extra>
      <NFlex :size="4">
        <NTag :type="station.online ? 'success' : 'error'" size="small">
          {{ station.online ? '在线' : '离线' }}
        </NTag>
        <NDropdown trigger="click" :options="dropdownOptions" @select="selectDropdownOption">
          <NButton quaternary size="tiny" :focusable="false">
            <NIcon :component="MoreOutlined" />
          </NButton>
        </NDropdown>
      </NFlex>
    </template>

    <template #default>
      <NFlex vertical :size="6" class="metrics" :style="{ opacity: station.online ? '1' : '0.5' }">
        <NFlex vertical :size="4" class="metric-item">
          <NFlex justify="end" align="center" class="metric-line">
            <span class="font-small">{{ deviceCount }} 台设备</span>
            <NButton quaternary size="tiny" :focusable="false" @click="openOfflineDeviceTreeModal">
              <NIcon :component="EllipsisOutlined" />
            </NButton>
          </NFlex>
          <NFlex justify="end" align="center" class="metric-line">
            <span class="font-small">
              <span :style="{ color: onlineDeviceCount > 0 ? theme.successColor : '' }">在线 {{ onlineDeviceCount }} 台</span>
              <NText depth="3" class="sep">·</NText>
              <span :style="{ color: offlineDeviceCount > 0 ? theme.errorColor : '' }">离线 {{ offlineDeviceCount }} 台</span>
            </span>
            <NButton quaternary size="tiny" :focusable="false" style="visibility: hidden">
              <NIcon :component="EllipsisOutlined" />
            </NButton>
          </NFlex>
        </NFlex>

        <NFlex justify="end" align="center" class="metric-item">
          <NFlex align="center" :size="8">
            <span class="font-small" :style="{ color: alarmCount > 0 ? theme.warningColor : '' }">今日 {{ alarmCount }} 条告警</span>
            <NButton quaternary size="tiny" :focusable="false" @click="openDeviceAlarmTreeModal">
              <NIcon :component="EllipsisOutlined" />
            </NButton>
          </NFlex>
        </NFlex>
      </NFlex>
    </template>
  </NCard>
</template>

<style scoped lang="scss">
.font-medium {
  font-size: medium;
}

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

.metrics {
  padding-top: 4px;
}

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

.metric-line .font-small {
  white-space: nowrap;
}
</style>
