<template>
  <div class="business-system-page">
    <a-row :gutter="16" class="summary-row">
      <a-col :xs="24" :sm="12" :lg="6">
        <a-card :bordered="false" class="summary-card">
          <div class="summary-label">业务系统</div>
          <div class="summary-value">{{ pagination.total }}</div>
        </a-card>
      </a-col>
      <a-col :xs="24" :sm="12" :lg="6">
        <a-card :bordered="false" class="summary-card">
          <div class="summary-label">健康业务</div>
          <div class="summary-value healthy">{{ healthyCount }}</div>
        </a-card>
      </a-col>
      <a-col :xs="24" :sm="12" :lg="6">
        <a-card :bordered="false" class="summary-card">
          <div class="summary-label">受影响业务</div>
          <div class="summary-value warning">{{ affectedCount }}</div>
        </a-card>
      </a-col>
      <a-col :xs="24" :sm="12" :lg="6">
        <a-card :bordered="false" class="summary-card">
          <div class="summary-label">活跃 Incident</div>
          <div class="summary-value danger">{{ activeIncidentTotal }}</div>
        </a-card>
      </a-col>
    </a-row>

    <a-card :bordered="false" title="业务系统视图">
      <template #extra>
        <a-button type="primary" :loading="loading" :disabled="pageUnauthorized" @click="fetchData">
          <template #icon><icon-refresh /></template>
          刷新
        </a-button>
      </template>

      <a-form :model="filters" layout="inline" class="filter-form">
        <a-form-item field="keyword" label="关键字">
          <a-input v-model="filters.keyword" allow-clear placeholder="编码 / 名称 / 类型" />
        </a-form-item>
        <a-form-item field="status" label="状态">
          <a-select v-model="filters.status" allow-clear placeholder="全部">
            <a-option value="active">启用</a-option>
            <a-option value="disabled">停用</a-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button @click="resetFilters">重置</a-button>
            <a-button type="primary" @click="handleSearch">
              <template #icon><icon-search /></template>
              查询
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <PageState :status="pageStatus" :error-text="errorMessage" :partial-text="partialMessage" @retry="fetchData">
      <a-table
        v-if="pageStatus !== 'empty' && pageStatus !== 'error' && pageStatus !== 'unauthorized'"
        row-key="id"
        :data="rows"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        :scroll="{ x: 'max-content' }"
        @page-change="handlePageChange"
        @page-size-change="handlePageSizeChange"
      >
        <template #code="{ record }">
          <a-typography-text copyable>{{ record.code }}</a-typography-text>
        </template>
        <template #status="{ record }">
          <a-tag :color="record.status === 'active' ? 'green' : 'gray'">{{ record.status === 'active' ? '启用' : '停用' }}</a-tag>
        </template>
        <template #health="{ record }">
          <div class="health-cell">
            <span class="health-score" :class="healthClass(record.health_score)">{{ scoreText(record.health_score) }}</span>
            <span class="health-bar">
              <span :class="healthClass(record.health_score)" :style="{ width: `${scoreValue(record.health_score)}%` }" />
            </span>
          </div>
        </template>
        <template #active_incident_count="{ record }">
          <a-badge :count="record.active_incident_count || 0" :dot="false" :max-count="99" />
        </template>
        <template #actions="{ record }">
          <a-button type="text" size="small" :disabled="pageUnauthorized" @click="openDetail(record.id)">
            <template #icon><icon-eye /></template>
            详情
          </a-button>
        </template>
      </a-table>
      </PageState>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import { IconEye, IconRefresh, IconSearch } from '@arco-design/web-vue/es/icon'
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface'
import { fetchBusinessHealth, fetchBusinessSystems, type BusinessSystemItem } from '@/api/ops/businessSystem'

const router = useRouter()
const loading = ref(false)
const rows = ref<BusinessSystemItem[]>([])
const errorMessage = ref('')
const partialMessage = ref('')
const pageUnauthorized = ref(false)

const filters = reactive({
  keyword: '',
  status: undefined as string | undefined,
})

const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  showTotal: true,
  showPageSize: true,
})

const columns: TableColumnData[] = [
  { title: '编码', dataIndex: 'code', slotName: 'code', width: 130 },
  { title: '名称', dataIndex: 'name', ellipsis: true, tooltip: true },
  { title: '类型', dataIndex: 'system_type', width: 120 },
  { title: '状态', dataIndex: 'status', slotName: 'status', width: 100 },
  { title: '资源数', dataIndex: 'resource_count', width: 100 },
  { title: '健康分', dataIndex: 'health_score', slotName: 'health', width: 180 },
  { title: '活跃 Incident', dataIndex: 'active_incident_count', slotName: 'active_incident_count', width: 130 },
  { title: '描述', dataIndex: 'description', ellipsis: true, tooltip: true },
  { title: '操作', dataIndex: 'actions', slotName: 'actions', fixed: 'right', width: 100 },
]

const healthyCount = computed(() => rows.value.filter((item) => scoreValue(item.health_score) >= 85).length)
const affectedCount = computed(() => rows.value.filter((item) => scoreValue(item.health_score) < 85).length)
const activeIncidentTotal = computed(() => rows.value.reduce((sum, item) => sum + (item.active_incident_count || 0), 0))

const pageStatus = computed(() => {
  if (pageUnauthorized.value) return 'unauthorized'
  if (loading.value) return 'loading'
  if (errorMessage.value && !rows.value.length) return 'error'
  if (partialMessage.value) return 'partial'
  if (!rows.value.length) return 'empty'
  return 'success'
})

const isForbidden = (error: any) => error?.response?.status === 403 || error?.code === 403 || error?.code === 401

const setLoadError = (error: any, fallback: string) => {
  if (isForbidden(error)) {
    pageUnauthorized.value = true
    errorMessage.value = '当前账号没有访问业务系统视图的权限。'
    return
  }
  errorMessage.value = error?.message || fallback
}

const scoreValue = (score?: number) => Math.max(0, Math.min(100, Number(score ?? 100)))
const scoreText = (score?: number) => `${scoreValue(score)}`

const healthClass = (score?: number) => {
  const value = scoreValue(score)
  if (value >= 85) return 'health-good'
  if (value >= 65) return 'health-warn'
  return 'health-bad'
}

const hydrateHealth = async (items: BusinessSystemItem[]) => {
  const settled = await Promise.allSettled(items.map((item) => fetchBusinessHealth(item.id)))
  partialMessage.value = settled.some((item) => item.status === 'rejected')
    ? '部分业务健康数据加载失败，列表已展示基础业务信息。'
    : ''
  return items.map((item, index) => {
    const result = settled[index]
    if (result.status !== 'fulfilled') return item
    const health = result.value.details
    if (!health) return item
    return {
      ...item,
      health_score: health.health.score,
      health_level: health.health.level,
      resource_count: health.signal_counts.resources,
      active_incident_count: health.signal_counts.active_incidents,
    }
  })
}

const fetchData = async () => {
  loading.value = true
  errorMessage.value = ''
  pageUnauthorized.value = false
  try {
    const response = await fetchBusinessSystems({
      page: pagination.current,
      size: pagination.pageSize,
      keyword: filters.keyword || undefined,
      status: filters.status,
    })
    const list = response.details?.data || []
    rows.value = await hydrateHealth(list)
    pagination.total = response.details?.total || 0
  } catch (error) {
    console.error('获取业务系统失败:', error)
    setLoadError(error, '获取业务系统失败')
    Message.error('获取业务系统失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

const resetFilters = () => {
  filters.keyword = ''
  filters.status = undefined
  handleSearch()
}

const handlePageChange = (page: number) => {
  pagination.current = page
  fetchData()
}

const handlePageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.current = 1
  fetchData()
}

const openDetail = (id: number) => {
  router.push({ path: '/business-system/detail', query: { id } })
}

onMounted(fetchData)
</script>

<script lang="ts">
export default {
  name: 'BusinessSystemView',
}
</script>

<style scoped lang="less">
.business-system-page {
  padding: 16px;
}

.summary-row {
  margin-bottom: 16px;
}

.summary-card {
  height: 100%;
}

.summary-label {
  color: var(--color-text-3);
  font-size: 13px;
  margin-bottom: 8px;
}

.summary-value {
  color: var(--color-text-1);
  font-size: 24px;
  font-weight: 600;
  line-height: 1.2;
}

.summary-value.healthy {
  color: rgb(var(--green-6));
}

.summary-value.warning {
  color: rgb(var(--orange-6));
}

.summary-value.danger {
  color: rgb(var(--red-6));
}

.filter-form {
  margin-bottom: 16px;
}

.health-cell {
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: 140px;
}

.health-score {
  width: 36px;
  font-weight: 600;
}

.health-bar {
  position: relative;
  flex: 1;
  height: 8px;
  overflow: hidden;
  background: var(--color-fill-3);
  border-radius: 4px;
}

.health-bar span {
  display: block;
  height: 100%;
  border-radius: 4px;
}

.health-good {
  color: rgb(var(--green-6));
  background: rgb(var(--green-6));
}

.health-warn {
  color: rgb(var(--orange-6));
  background: rgb(var(--orange-6));
}

.health-bad {
  color: rgb(var(--red-6));
  background: rgb(var(--red-6));
}

@media (max-width: 768px) {
  .business-system-page {
    padding: 12px;
  }

  .filter-form {
    display: block;
  }

  :deep(.arco-form-layout-inline .arco-form-item) {
    width: 100%;
    margin-right: 0;
  }

  :deep(.arco-card-header) {
    flex-wrap: wrap;
    gap: 8px;
  }

  :deep(.arco-card-extra) {
    width: 100%;
  }
}
</style>
