<template>
  <div class="resource-context-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">{{ resourcePagination.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">{{ businessSystems.length }}</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">{{ resourceTypes.length }}</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">{{ selectedMetricTotal }}</div>
        </a-card>
      </a-col>
    </a-row>

    <a-card :bordered="false">
      <template #title>资源库</template>
      <template #extra>
        <a-space>
          <a-button type="primary" :disabled="!canOperate || loading" @click="openCreateResource">
            <template #icon><icon-plus /></template>
            新增资源
          </a-button>
          <a-button :disabled="!canOperate || loading" @click="handleBackfill">
            <template #icon><icon-refresh /></template>
            回填资源
          </a-button>
          <a-button type="primary" :loading="loading" :disabled="pageUnauthorized" @click="fetchResources">
            <template #icon><icon-search /></template>
            查询
          </a-button>
        </a-space>
      </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="UID / 标识 / 名称" />
        </a-form-item>
        <a-form-item field="resource_category" label="资源分类">
          <a-select v-model="filters.resource_category" allow-clear placeholder="全部分类" :options="resourceTypeOptions" />
        </a-form-item>
        <a-form-item field="business_system_id" label="业务系统">
          <a-select v-model="filters.business_system_id" allow-clear placeholder="全部系统">
            <a-option v-for="item in businessSystems" :key="item.id" :value="item.id">{{ item.name }}</a-option>
          </a-select>
        </a-form-item>
      </a-form>

      <PageState :status="pageStatus" :error-text="errorMessage" :partial-text="partialMessage" @retry="fetchResources">
        <a-table
          v-if="pageStatus !== 'empty' && pageStatus !== 'error' && pageStatus !== 'unauthorized'"
          row-key="id"
          :data="resources"
          :columns="resourceColumns"
          :loading="loading"
          :pagination="resourcePagination"
          :scroll="{ x: 'max-content' }"
          @page-change="handlePageChange"
          @page-size-change="handlePageSizeChange"
        >
          <template #resource_uid="{ record }">
            <a-typography-text copyable>{{ record.resource_uid }}</a-typography-text>
          </template>
          <template #resource_category="{ record }">
            <a-tag color="arcoblue">{{ resourceTypeName(record.resource_category) }}</a-tag>
          </template>
          <template #business_system_id="{ record }">
            {{ businessSystemName(record.business_system_id) }}
          </template>
          <template #owner_user_id="{ record }">
            {{ record.owner_user_id || '-' }}
          </template>
          <template #asset_id="{ record }">
            {{ record.asset_id || '-' }}
          </template>
          <template #status="{ record }">
            <a-tag :color="statusColor(record.status)">{{ record.status || 'unknown' }}</a-tag>
          </template>
          <template #actions="{ record }">
            <a-space>
              <a-button type="text" size="small" :disabled="pageUnauthorized" @click="openDetail(record)">
                <template #icon><icon-eye /></template>
              </a-button>
              <a-button type="text" size="small" :disabled="!canOperate" @click="openEditResource(record)">
                <template #icon><icon-edit /></template>
              </a-button>
              <a-button type="text" status="danger" size="small" :disabled="!canOperate" @click="handleDeleteResource(record)">
                <template #icon><icon-delete /></template>
              </a-button>
            </a-space>
          </template>
        </a-table>
      </PageState>
    </a-card>

    <a-drawer v-model:visible="detailVisible" :width="920" title="资源详情" :footer="false" unmount-on-close>
      <a-descriptions v-if="currentResource" :column="2" bordered>
        <a-descriptions-item label="资源 UID">{{ currentResource.resource_uid }}</a-descriptions-item>
        <a-descriptions-item label="展示名称">{{ currentResource.display_name }}</a-descriptions-item>
        <a-descriptions-item label="资源分类">{{ resourceTypeName(currentResource.resource_category) }}</a-descriptions-item>
        <a-descriptions-item label="服务标识">{{ currentResource.service_identity }}</a-descriptions-item>
        <a-descriptions-item label="业务系统">{{ businessSystemName(currentResource.business_system_id) }}</a-descriptions-item>
        <a-descriptions-item label="责任人">{{ currentResource.owner_user_id || '-' }}</a-descriptions-item>
        <a-descriptions-item label="责任部门">{{ currentResource.department_id || '-' }}</a-descriptions-item>
        <a-descriptions-item label="资产绑定">{{ currentResource.asset_id || '-' }}</a-descriptions-item>
        <a-descriptions-item label="位置引用" :span="2">{{ locationText(currentResource) }}</a-descriptions-item>
        <a-descriptions-item label="关联告警" :span="2">等待 alert incident 接口接入后按 resource_uid 聚合展示</a-descriptions-item>
      </a-descriptions>

      <a-divider />
      <a-table
        row-key="id"
        :data="metricSeries"
        :columns="metricColumns"
        :loading="metricLoading"
        :pagination="false"
      />
    </a-drawer>

    <a-modal
      v-model:visible="resourceFormVisible"
      :title="resourceFormTitle"
      :confirm-loading="resourceFormSubmitting"
      :on-before-ok="submitResourceForm"
      unmount-on-close
      @cancel="resetResourceForm"
    >
      <a-form :model="resourceForm" layout="vertical">
        <a-form-item field="resource_category" label="资源分类" required>
          <a-select v-model="resourceForm.resource_category" allow-search placeholder="请选择资源分类" :options="resourceTypeOptions" />
        </a-form-item>
        <a-form-item field="service_identity" label="服务标识" required>
          <a-input v-model="resourceForm.service_identity" placeholder="例如 his-app-01" />
        </a-form-item>
        <a-form-item field="display_name" label="展示名称" required>
          <a-input v-model="resourceForm.display_name" placeholder="例如 HIS 应用服务 01" />
        </a-form-item>
        <a-form-item field="status" label="状态" required>
          <a-select v-model="resourceForm.status" placeholder="请选择状态">
            <a-option value="normal">normal</a-option>
            <a-option value="online">online</a-option>
            <a-option value="offline">offline</a-option>
            <a-option value="error">error</a-option>
            <a-option value="unknown">unknown</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="business_system_id" label="业务系统">
          <a-select v-model="resourceForm.business_system_id" allow-clear allow-search placeholder="可选">
            <a-option v-for="item in businessSystems" :key="item.id" :value="item.id">{{ item.name }}</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="asset_id" label="资产 ID">
          <a-input-number v-model="resourceForm.asset_id" :min="1" :precision="0" placeholder="可选" />
        </a-form-item>
        <a-form-item field="tags" label="标签">
          <a-input v-model="resourceForm.tags" placeholder="多个标签用逗号分隔" />
        </a-form-item>
        <a-form-item field="description" label="描述">
          <a-textarea v-model="resourceForm.description" :auto-size="{ minRows: 3, maxRows: 6 }" placeholder="请输入资源说明" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import { IconDelete, IconEdit, IconEye, IconPlus, IconRefresh, IconSearch } from '@arco-design/web-vue/es/icon'
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface'
import {
  backfillControlResources,
  createControlResource,
  deleteControlResource,
  fetchControlBusinessSystems,
  fetchControlMetricSeries,
  fetchControlResources,
  fetchControlResourceTypes,
  updateControlResource,
  type ControlBusinessSystem,
  type ControlMetricSeries,
  type ControlResource,
  type ControlResourcePayload,
  type ControlResourceType,
} from '@/api/ops/dcControl'

const loading = ref(false)
const metricLoading = ref(false)
const detailVisible = ref(false)
const errorMessage = ref('')
const partialMessage = ref('')
const pageUnauthorized = ref(false)
const resources = ref<ControlResource[]>([])
const metricSeries = ref<ControlMetricSeries[]>([])
const resourceTypes = ref<ControlResourceType[]>([])
const businessSystems = ref<ControlBusinessSystem[]>([])
const currentResource = ref<ControlResource | null>(null)
const selectedMetricTotal = ref(0)
const resourceFormVisible = ref(false)
const resourceFormSubmitting = ref(false)
const editingResource = ref<ControlResource | null>(null)

const resourceForm = reactive<ControlResourcePayload>({
  resource_category: '',
  service_identity: '',
  display_name: '',
  status: 'normal',
  business_system_id: undefined,
  owner_user_id: undefined,
  department_id: undefined,
  asset_id: undefined,
  datacenter_id: undefined,
  room_id: undefined,
  rack_id: undefined,
  unit_start: undefined,
  unit_end: undefined,
  location_ref: '',
  tags: '',
  description: '',
})

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

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

const resourceColumns: TableColumnData[] = [
  { title: '资源 UID', dataIndex: 'resource_uid', slotName: 'resource_uid', width: 220 },
  { title: '名称', dataIndex: 'display_name', width: 180, ellipsis: true, tooltip: true },
  { title: '分类', dataIndex: 'resource_category', slotName: 'resource_category', width: 120 },
  { title: '业务系统', dataIndex: 'business_system_id', slotName: 'business_system_id', width: 140 },
  { title: '责任人', dataIndex: 'owner_user_id', slotName: 'owner_user_id', width: 100 },
  { title: '资产', dataIndex: 'asset_id', slotName: 'asset_id', width: 100 },
  { title: '状态', dataIndex: 'status', slotName: 'status', width: 110 },
  { title: '操作', dataIndex: 'actions', slotName: 'actions', width: 150, fixed: 'right' },
]

const metricColumns: TableColumnData[] = [
  { title: '指标编码', dataIndex: 'metric_code', width: 180 },
  { title: '采集任务', dataIndex: 'collection_task_id', width: 160 },
  { title: '时序驱动', dataIndex: 'storage_driver', width: 120 },
  { title: '表名', dataIndex: 'table_name', width: 180 },
  { title: '序列键', dataIndex: 'series_key', ellipsis: true, tooltip: true },
  { title: '保留策略', dataIndex: 'retention_policy', width: 140 },
]

const resourceTypeOptions = computed(() =>
  resourceTypes.value.map((item) => ({
    label: item.display_name,
    value: item.resource_category,
  }))
)

const canOperate = computed(() => !pageUnauthorized.value)

const resourceFormTitle = computed(() => (editingResource.value ? '编辑资源' : '新增资源'))

const resetResourceForm = () => {
  editingResource.value = null
  Object.assign(resourceForm, {
    resource_category: '',
    service_identity: '',
    display_name: '',
    status: 'normal',
    business_system_id: undefined,
    owner_user_id: undefined,
    department_id: undefined,
    asset_id: undefined,
    datacenter_id: undefined,
    room_id: undefined,
    rack_id: undefined,
    unit_start: undefined,
    unit_end: undefined,
    location_ref: '',
    tags: '',
    description: '',
  })
}

const normalizeNullableNumber = (value: unknown) => {
  const numberValue = Number(value)
  return Number.isInteger(numberValue) && numberValue > 0 ? numberValue : null
}

const buildResourcePayload = (): ControlResourcePayload => {
  const locationRef = resourceForm.location_ref?.trim()
  const payload: ControlResourcePayload = {
    resource_category: resourceForm.resource_category?.trim(),
    service_identity: resourceForm.service_identity?.trim(),
    display_name: resourceForm.display_name?.trim(),
    status: resourceForm.status?.trim() || 'normal',
    business_system_id: normalizeNullableNumber(resourceForm.business_system_id),
    owner_user_id: normalizeNullableNumber(resourceForm.owner_user_id),
    department_id: normalizeNullableNumber(resourceForm.department_id),
    asset_id: normalizeNullableNumber(resourceForm.asset_id),
    datacenter_id: normalizeNullableNumber(resourceForm.datacenter_id),
    room_id: normalizeNullableNumber(resourceForm.room_id),
    rack_id: normalizeNullableNumber(resourceForm.rack_id),
    unit_start: normalizeNullableNumber(resourceForm.unit_start),
    unit_end: normalizeNullableNumber(resourceForm.unit_end),
    tags: resourceForm.tags?.trim(),
    description: resourceForm.description?.trim(),
  }

  if (locationRef) {
    payload.location_ref = locationRef
  }

  return payload
}

const pageStatus = computed(() => {
  if (pageUnauthorized.value) return 'unauthorized'
  if (loading.value) return 'loading'
  if (errorMessage.value && !resources.value.length) return 'error'
  if (partialMessage.value) return 'partial'
  if (!resources.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 resourceTypeName = (category?: string) => {
  const item = resourceTypes.value.find((type) => type.resource_category === category)
  return item?.display_name || category || '-'
}

const businessSystemName = (id?: number) => {
  if (!id) return '-'
  const item = businessSystems.value.find((system) => system.id === id)
  return item?.name || String(id)
}

const statusColor = (status?: string) => {
  const map: Record<string, string> = {
    online: 'green',
    active: 'green',
    offline: 'red',
    error: 'orange',
    unknown: 'gray',
  }
  return map[status || 'unknown'] || 'gray'
}

const locationText = (record: ControlResource) => {
  const parts = [
    record.datacenter_id ? `数据中心 ${record.datacenter_id}` : '',
    record.room_id ? `机房 ${record.room_id}` : '',
    record.rack_id ? `机柜 ${record.rack_id}` : '',
    record.unit_start ? `U${record.unit_start}-${record.unit_end || record.unit_start}` : '',
  ].filter(Boolean)
  if (parts.length) return parts.join(' / ')
  if (!record.location_ref) return '-'
  try {
    const parsed = JSON.parse(record.location_ref)
    return parsed.text || record.location_ref
  } catch {
    return record.location_ref
  }
}

const fetchResources = async () => {
  loading.value = true
  errorMessage.value = ''
  pageUnauthorized.value = false
  try {
    const response = await fetchControlResources({
      page: resourcePagination.current,
      size: resourcePagination.pageSize,
      keyword: filters.keyword,
      resource_category: filters.resource_category,
      business_system_id: filters.business_system_id,
    })
    resources.value = response.details?.data || []
    resourcePagination.total = response.details?.total || 0
  } catch (error) {
    console.error('获取统一资源失败:', error)
    setLoadError(error, '获取统一资源失败')
    Message.error('获取统一资源失败')
  } finally {
    loading.value = false
  }
}

const fetchDictionaries = async () => {
  partialMessage.value = ''
  const [typeResult, systemResult] = await Promise.allSettled([
    fetchControlResourceTypes({ page: 1, size: 100 }),
    fetchControlBusinessSystems({ page: 1, size: 100, status: 'active' }),
  ])
  if (typeResult.status === 'fulfilled') {
    resourceTypes.value = typeResult.value.details?.data || []
  }
  if (systemResult.status === 'fulfilled') {
    businessSystems.value = systemResult.value.details?.data || []
  }
  if (typeResult.status === 'rejected' || systemResult.status === 'rejected') {
    partialMessage.value = '字典数据部分加载失败，资源列表仍可继续使用。'
  }
}

const fetchMetricSeries = async (resourceUid: string) => {
  metricLoading.value = true
  try {
    const response = await fetchControlMetricSeries({ page: 1, size: 100, resource_uid: resourceUid })
    metricSeries.value = response.details?.data || []
    selectedMetricTotal.value = response.details?.total || 0
  } catch (error) {
    console.error('获取指标序列失败:', error)
    Message.error('获取指标序列失败')
  } finally {
    metricLoading.value = false
  }
}

const openDetail = (record: ControlResource) => {
  currentResource.value = record
  detailVisible.value = true
  fetchMetricSeries(record.resource_uid)
}

const openCreateResource = () => {
  resetResourceForm()
  resourceFormVisible.value = true
}

const openEditResource = (record: ControlResource) => {
  editingResource.value = record
  Object.assign(resourceForm, {
    resource_category: record.resource_category || '',
    service_identity: record.service_identity || '',
    display_name: record.display_name || '',
    status: record.status || 'normal',
    business_system_id: record.business_system_id,
    owner_user_id: record.owner_user_id,
    department_id: record.department_id,
    asset_id: record.asset_id,
    datacenter_id: record.datacenter_id,
    room_id: record.room_id,
    rack_id: record.rack_id,
    unit_start: record.unit_start,
    unit_end: record.unit_end,
    location_ref: record.location_ref || '',
    tags: record.tags || '',
    description: record.description || '',
  })
  resourceFormVisible.value = true
}

const submitResourceForm = async () => {
  const payload = buildResourcePayload()
  if (!payload.resource_category || !payload.service_identity || !payload.display_name) {
    Message.warning('请填写资源分类、服务标识和展示名称')
    return false
  }

  resourceFormSubmitting.value = true
  try {
    if (editingResource.value) {
      await updateControlResource(editingResource.value.id, payload)
      Message.success('资源已更新')
    } else {
      await createControlResource(payload)
      Message.success('资源已新增')
    }
    await fetchResources()
    return true
  } catch (error) {
    console.error('保存资源失败:', error)
    Message.error('保存资源失败')
    return false
  } finally {
    resourceFormSubmitting.value = false
  }
}

const handleDeleteResource = (record: ControlResource) => {
  Modal.warning({
    title: '删除资源',
    content: `确认删除资源「${record.display_name || '-'} / ${record.resource_uid} / ${resourceTypeName(record.resource_category)}」？这会删除资源库中的全局资源，可能影响业务拓扑、告警和指标序列。`,
    hideCancel: false,
    okText: '删除',
    cancelText: '取消',
    onOk: async () => {
      try {
        await deleteControlResource(record.id)
        Message.success('资源已删除')
        if (currentResource.value?.id === record.id) {
          detailVisible.value = false
          currentResource.value = null
        }
        await fetchResources()
      } catch (error) {
        console.error('删除资源失败:', error)
        Message.error('删除资源失败')
      }
    },
  })
}

const handleBackfill = async () => {
  try {
    await backfillControlResources()
    Message.success('资源回填已触发')
    fetchResources()
  } catch (error) {
    console.error('资源回填失败:', error)
    Message.error('资源回填失败')
  }
}

const handlePageChange = (page: number) => {
  resourcePagination.current = page
  fetchResources()
}

const handlePageSizeChange = (pageSize: number) => {
  resourcePagination.pageSize = pageSize
  resourcePagination.current = 1
  fetchResources()
}

onMounted(async () => {
  await fetchDictionaries()
  fetchResources()
})
</script>

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

<style scoped lang="less">
.resource-context-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;
}

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

@media (max-width: 768px) {
  .resource-context-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%;
  }

  :deep(.arco-card-extra .arco-space) {
    flex-wrap: wrap;
    justify-content: flex-start;
  }
}
</style>
