<template>
  <a-modal
    :visible="visible"
    title="指标采集"
    @ok="handleOk"
    @cancel="handleCancel"
    @update:visible="handleUpdateVisible"
    :confirm-loading="confirmLoading"
    width="600px"
  >
    <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical">
      <a-form-item field="ids" label="选择服务" required>
        <a-select v-model="formData.ids" placeholder="请选择要采集的服务（最多20个）" multiple :max-tag-count="5" allow-clear>
          <a-option
            v-for="item in serviceList"
            :key="item.id"
            :value="item.id"
            :label="item.name"
            :disabled="!item.enabled || !item.collect_on"
          >
            <div class="service-option">
              <span>{{ item.name }}</span>
              <a-tag size="small" :color="item.enabled && item.collect_on ? 'green' : 'red'" style="margin-left: 8px">
                {{ item.enabled && item.collect_on ? '可采集' : '不可采集' }}
              </a-tag>
            </div>
          </a-option>
        </a-select>
        <template #extra>
          <span style="color: rgb(var(--text-3))">仅 enabled=true 且 collect_on=true 的服务可执行采集</span>
        </template>
      </a-form-item>

      <a-form-item field="persist" label="持久化到时序库">
        <a-switch v-model="formData.persist" />
        <template #extra>
          <span style="color: rgb(var(--text-3))">开启后将采集结果写入时序库</span>
        </template>
      </a-form-item>
    </a-form>

    <!-- 采集结果展示 -->
    <div v-if="collectResults.length > 0" class="collect-results">
      <a-divider>采集结果</a-divider>
      <a-list :bordered="false">
        <a-list-item v-for="result in collectResults" :key="result.id">
          <a-list-item-meta :title="result.service_identity" :description="`ID: ${result.id}`" />
          <template #actions>
            <a-tag v-if="result.metrics && result.metrics.length > 0" color="green">成功</a-tag>
            <a-tag v-else color="red">失败</a-tag>
          </template>
          <div v-if="result.error" class="error-message">
            {{ result.error }}
          </div>
          <div v-if="result.metrics && result.metrics.length > 0" class="metrics-display">
            <div class="metrics-summary">共采集 {{ result.metrics.length }} 个指标</div>
            <a-button size="small" @click="toggleMetrics(result.id)">
              {{ expandedMetrics.includes(result.id) ? '隐藏' : '展开' }}详情
            </a-button>
            <div v-if="expandedMetrics.includes(result.id)" class="metrics-list">
              <div v-for="metric in result.metrics" :key="metric.metric_name" class="metric-item">
                <span class="metric-name">{{ metric.metric_name }}</span>
                <span class="metric-value">{{ metric.metric_value }}</span>
                <span v-if="metric.metric_unit" class="metric-unit">{{ metric.metric_unit }}</span>
                <span class="metric-time">{{ formatTime(metric.timestamp) }}</span>
              </div>
            </div>
          </div>
        </a-list-item>
      </a-list>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import type { FormInstance } from '@arco-design/web-vue'
import { collectDatabaseMetrics } from '@/api/ops/database'

interface MetricItem {
  metric_name: string
  metric_value: number
  metric_unit: string
  service_identity: string
  timestamp: string
  type: string
}

interface CollectResultItem {
  id: number
  service_identity: string
  metrics?: MetricItem[]
  error?: string
}

interface Props {
  visible: boolean
  serviceList?: any[]
}

const props = withDefaults(defineProps<Props>(), {
  serviceList: () => [],
})

const emit = defineEmits(['update:visible', 'success'])

const formRef = ref<FormInstance>()
const confirmLoading = ref(false)
const collectResults = ref<CollectResultItem[]>([])
const expandedMetrics = ref<number[]>([])

const formData = reactive({
  ids: [] as number[],
  persist: true,
})

const rules = {
  ids: [
    { required: true, message: '请选择要采集的服务' },
    {
      validator: (value: number[], callback: (error?: string) => void) => {
        if (value.length > 20) {
          callback('单次最多选择20个服务')
        } else {
          callback()
        }
      },
    },
  ],
}

// 格式化时间
const formatTime = (time: string) => {
  if (!time) return '-'
  if (time.startsWith('0001-01-01')) return '-'
  const date = new Date(time)
  if (Number.isNaN(date.getTime())) return '-'
  if (date.getFullYear() <= 1970) return '-'
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

watch(
  () => props.visible,
  (val) => {
    if (val) {
      formData.ids = []
      formData.persist = true
      collectResults.value = []
      expandedMetrics.value = []
    }
  }
)

const toggleMetrics = (id: number) => {
  const index = expandedMetrics.value.indexOf(id)
  if (index > -1) {
    expandedMetrics.value.splice(index, 1)
  } else {
    expandedMetrics.value.push(id)
  }
}

const handleOk = async () => {
  try {
    await formRef.value?.validate()

    confirmLoading.value = true

    const res: any = await collectDatabaseMetrics({
      ids: formData.ids,
      persist: formData.persist,
    })

    collectResults.value = res?.details?.results || []

    const successCount = collectResults.value.filter((r) => r.metrics && r.metrics.length > 0).length
    const failCount = collectResults.value.filter((r) => r.error).length

    if (failCount === 0) {
      Message.success(`采集完成，成功 ${successCount} 个`)
    } else if (successCount === 0) {
      Message.error(`采集完成，失败 ${failCount} 个`)
    } else {
      Message.warning(`采集完成，成功 ${successCount} 个，失败 ${failCount} 个`)
    }

    emit('success')
  } catch (error: any) {
    console.error('采集失败:', error)
    if (error?.response?.data?.message) {
      Message.error(error.response.data.message)
    } else {
      Message.error('采集失败')
    }
  } finally {
    confirmLoading.value = false
  }
}

const handleUpdateVisible = (value: boolean) => {
  emit('update:visible', value)
}

const handleCancel = () => {
  emit('update:visible', false)
  formRef.value?.resetFields()
}
</script>

<style scoped lang="less">
.service-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.collect-results {
  margin-top: 16px;

  .error-message {
    color: rgb(var(--danger-6));
    font-size: 12px;
    margin-top: 4px;
  }

  .metrics-display {
    margin-top: 4px;

    .metrics-summary {
      font-size: 12px;
      color: rgb(var(--text-3));
      margin-bottom: 4px;
    }

    .metrics-list {
      margin-top: 8px;
      padding: 8px;
      background: rgb(var(--gray-2));
      border-radius: 4px;
      max-height: 200px;
      overflow-y: auto;

      .metric-item {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 4px 0;
        font-size: 12px;

        .metric-name {
          color: rgb(var(--text-1));
          font-weight: 500;
        }

        .metric-value {
          color: rgb(var(--success-6));
        }

        .metric-unit {
          color: rgb(var(--text-3));
        }

        .metric-time {
          color: rgb(var(--text-3));
          margin-left: auto;
        }
      }
    }
  }
}
</style>
