<template>
  <div class="health-check">
    <m-card :no-title="true" :no-elevation="false" :px5="false">
      <template #autoTitle>
        <span>n8n 服务状态</span>
        <v-spacer />
        <v-btn color="primary" small @click="checkHealth">
          <v-icon left>mdi-refresh</v-icon>
          检查
        </v-btn>
      </template>

      <v-row justify="center" class="py-8">
        <v-col cols="12" md="8">
          <m-card :no-title="true" :no-elevation="false" :px5="false" :min-height="0" body-style="padding: 0;">
            <div
              :class="`text-center pa-8 elevation-4 ${health.connected ? 'success' : 'error'} white--text`"
              style="border-radius: 4px;"
            >
              <v-icon size="64" class="mb-4">
                {{ health.connected ? 'mdi-check-circle' : 'mdi-alert-circle' }}
              </v-icon>
              <div class="text-h4 mb-4">
                {{ health.connected ? '服务正常' : '服务异常' }}
              </div>
              <div class="text-body-1 mb-2">
                API地址: {{ health.api_url || '-' }}
              </div>
              <div v-if="health.error" class="text-body-1 error--text">
                错误: {{ health.error }}
              </div>
            </div>
          </m-card>
        </v-col>
      </v-row>
    </m-card>

    <v-overlay :value="overlay" z-index="9">
      <div class="d-flex flex-column align-center justify-center" style="width: 300px;">
        <div class="mb-3">正在检查</div>
        <v-progress-linear
          color="primary"
          indeterminate
          rounded
          height="6"
        ></v-progress-linear>
      </div>
    </v-overlay>
  </div>
</template>

<script>
import { healthCheck } from '@/api/dataFactory'
import MCard from '@/components/MCard'

export default {
  name: 'HealthCheck',
  components: {
    MCard
  },
  data () {
    return {
      overlay: false,
      health: {
        connected: false,
        api_url: '',
        error: ''
      }
    }
  },
  mounted () {
    this.checkHealth()
  },
  methods: {
    async checkHealth () {
      this.overlay = true
      try {
        const response = await healthCheck()
        this.health = response.data || {
          connected: false,
          api_url: '',
          error: ''
        }
      } catch (error) {
        this.health = {
          connected: false,
          api_url: '',
          error: '无法连接到服务'
        }
      } finally {
        this.overlay = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.health-check {
  padding: 20px 0;
}
</style>
