<template>
  <EnterpriseListPage
    variant="skill-list"
    :tabs="shellTabs"
    :active-tab="activeType"
    tabs-label="能力类型"
    :loading="loading"
    :error="errorMessage"
    :empty="!visibleSkills.length"
    :empty-state="auditEmptyState"
    :loading-title="`${activeTabLabel}资产同步中`"
    :loading-message="`正在加载${activeTabLabel}资产`"
    loading-icon="mdi mdi-view-list-outline"
    :hint="hintText"
    :show-pagination="!loading && !errorMessage && visibleSkills.length > 0"
    :current-page="currentPage"
    :page-size="pageSize"
    :page-size-options="pageSizeOptions"
    :show-page-size="true"
    :summary="paginationSummary"
    :total="visibleSkills.length"
    :total-pages="totalPages"
    @update:active-tab="emit('update:activeType', $event)"
    @update:current-page="currentPage = $event"
    @update:page-size="changePageSize"
    @empty-action="emit('empty-action')"
  >
    <template #filters>
      <label class="search-filter">
        <i class="mdi mdi-magnify"></i>
        <input
          :value="keyword"
          type="search"
          :placeholder="searchPlaceholder"
          @input="emit('update:keyword', $event.target.value)"
        />
      </label>

      <AuditPickerFilter
        id="domain"
        title="选择业务域"
        close-label="关闭业务域选择"
        :active-filter-popover="activeFilterPopover"
        :label="selectedDomainLabel"
        :options="domainOptions"
        :selected-value="selectedDomain"
        @toggle="emit('toggle-filter-popover', $event)"
        @close="emit('close-filter-popover')"
        @select="selectFilter('domain', $event)"
      />

      <AuditPickerFilter
        v-if="showOwnerFilter"
        id="owner"
        title="选择负责人"
        close-label="关闭负责人选择"
        :active-filter-popover="activeFilterPopover"
        :label="selectedOwnerLabel"
        :options="ownerOptions"
        :selected-value="selectedOwner"
        @toggle="emit('toggle-filter-popover', $event)"
        @close="emit('close-filter-popover')"
        @select="selectFilter('owner', $event)"
      />

      <AuditPickerFilter
        v-if="showRiskLevelFilter"
        id="riskLevel"
        title="选择风险等级"
        close-label="关闭风险等级选择"
        :active-filter-popover="activeFilterPopover"
        :label="selectedRiskLevelLabel"
        :options="riskLevelOptions"
        :selected-value="selectedRiskLevel"
        @toggle="emit('toggle-filter-popover', $event)"
        @close="emit('close-filter-popover')"
        @select="selectFilter('riskLevel', $event)"
      />

      <AuditPickerFilter
        v-if="showRiskScenarioFilter"
        id="riskScenario"
        title="选择使用场景"
        close-label="关闭使用场景选择"
        :active-filter-popover="activeFilterPopover"
        :label="selectedRiskScenarioLabel"
        :options="riskScenarioOptions"
        :selected-value="selectedRiskScenario"
        @toggle="emit('toggle-filter-popover', $event)"
        @close="emit('close-filter-popover')"
        @select="selectFilter('riskScenario', $event)"
      />

      <AuditPickerFilter
        v-if="showOnlineFilter"
        id="online"
        title="选择上线状态"
        close-label="关闭上线状态选择"
        :active-filter-popover="activeFilterPopover"
        :label="selectedOnlineStateLabel"
        :options="onlineStateOptions"
        :selected-value="selectedOnlineState"
        @toggle="emit('toggle-filter-popover', $event)"
        @close="emit('close-filter-popover')"
        @select="selectFilter('online', $event)"
      />

      <AuditPickerFilter
        v-if="showEnabledFilter"
        id="enabled"
        title="选择启用状态"
        close-label="关闭启用状态选择"
        :active-filter-popover="activeFilterPopover"
        :label="selectedEnabledStateLabel"
        :options="enabledStateOptions"
        :selected-value="selectedEnabledState"
        @toggle="emit('toggle-filter-popover', $event)"
        @close="emit('close-filter-popover')"
        @select="selectFilter('enabled', $event)"
      />

      <AuditPickerFilter
        v-if="showStatusFilter"
        id="status"
        title="选择状态"
        close-label="关闭状态选择"
        :active-filter-popover="activeFilterPopover"
        :label="selectedStatusLabel"
        :options="statusOptions"
        :selected-value="selectedStatus"
        @toggle="emit('toggle-filter-popover', $event)"
        @close="emit('close-filter-popover')"
        @select="selectFilter('status', $event)"
      />
    </template>

    <template #actions>
      <button
        v-if="activeFilterTokens.length"
        class="ghost-filter-btn"
        type="button"
        @click="emit('reset-filters')"
      >
        <i class="mdi mdi-filter-remove-outline"></i>
        <span>清空筛选</span>
      </button>

      <button
        class="create-btn"
        type="button"
        :disabled="!canCreateRiskRule"
        @click="emit('create-risk-rule')"
      >
        <i class="mdi mdi-plus"></i>
        <span>{{ createButtonLabel }}</span>
      </button>
    </template>

    <template #meta>
      <div v-if="activeFilterTokens.length" class="active-filter-strip">
        <span v-for="token in activeFilterTokens" :key="token" class="active-filter-chip">
          {{ token }}
        </span>
      </div>
    </template>

    <template #error>
      <i class="mdi mdi-alert-circle-outline"></i>
      <p>{{ errorMessage }}</p>
    </template>

    <template #table>
      <table class="audit-asset-table">
        <thead>
          <tr>
            <th>{{ tableColumns.name }}</th>
            <th>{{ tableColumns.category }}</th>
            <th>{{ tableColumns.owner }}</th>
            <th>{{ tableColumns.scope }}</th>
            <th v-if="showRuntimeColumn">{{ tableColumns.runtime }}</th>
            <th v-if="showVersionColumn">{{ tableColumns.version }}</th>
            <th v-if="showStatusColumn">{{ tableColumns.status || '状态' }}</th>
            <th v-if="showMetricColumn">{{ tableColumns.metric }}</th>
            <th v-if="showOnlineColumn">是否上线</th>
            <th v-if="showEnabledColumn">是否启用</th>
            <th>{{ tableColumns.updatedAt || '最近更新' }}</th>
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="skill in pagedSkills"
            :key="skill.id"
            :class="{ 'is-disabled': skill.usesJsonRiskRule && skill.statusValue === 'generating' }"
            @click="emit('open-asset-detail', skill)"
          >
            <td :data-label="tableColumns.name">
              <div class="skill-name-cell">
                <span class="skill-avatar" :class="skill.badgeTone">{{ skill.short }}</span>
                <div>
                  <strong>{{ skill.name }}</strong>
                  <span class="skill-list-subtitle">{{ skill.listSubtitle || skill.summary }}</span>
                </div>
              </div>
            </td>
            <td :data-label="tableColumns.category">{{ skill.category }}</td>
            <td :data-label="tableColumns.owner">
              <span
                v-if="skill.usesJsonRiskRule"
                class="json-risk-meta-badge"
                :class="skill.riskLevelTone"
              >
                {{ skill.riskLevelLabel || '-' }}
              </span>
              <template v-else>{{ skill.owner }}</template>
            </td>
            <td :data-label="tableColumns.scope"><span class="scope-pill">{{ skill.scope }}</span></td>
            <td v-if="showRuntimeColumn" :data-label="tableColumns.runtime">{{ skill.model }}</td>
            <td v-if="showVersionColumn" :data-label="tableColumns.version">{{ skill.versionDisplay || skill.version }}</td>
            <td v-if="showStatusColumn" :data-label="tableColumns.status || '状态'">
              <span class="status-pill" :class="skill.statusTone">{{ skill.status }}</span>
            </td>
            <td v-if="showMetricColumn" :data-label="tableColumns.metric">{{ skill.hitRate }}</td>
            <td v-if="showOnlineColumn" data-label="是否上线">
              <span class="status-pill" :class="skill.isOnlineTone">{{ skill.isOnlineLabel }}</span>
            </td>
            <td v-if="showEnabledColumn" data-label="是否启用">
              <span class="status-pill" :class="skill.isEnabledTone">{{ skill.isEnabledLabel }}</span>
            </td>
            <td :data-label="tableColumns.updatedAt || '最近更新'">{{ skill.updatedAt }}</td>
          </tr>
        </tbody>
      </table>
    </template>
  </EnterpriseListPage>
</template>

<script setup>
import { computed, ref, watch } from 'vue'

import AuditPickerFilter from './AuditPickerFilter.vue'
import EnterpriseListPage from '../shared/EnterpriseListPage.vue'

defineOptions({
  name: 'AuditAssetList'
})

const props = defineProps({
  tabs: { type: Array, default: () => [] },
  activeType: { type: String, default: '' },
  activeTabLabel: { type: String, default: '' },
  keyword: { type: String, default: '' },
  searchPlaceholder: { type: String, default: '' },
  createButtonLabel: { type: String, default: '' },
  hintText: { type: String, default: '' },
  tableColumns: { type: Object, default: () => ({}) },
  showRuntimeColumn: { type: Boolean, default: false },
  showVersionColumn: { type: Boolean, default: false },
  showMetricColumn: { type: Boolean, default: false },
  showStatusColumn: { type: Boolean, default: false },
  showOnlineColumn: { type: Boolean, default: false },
  showEnabledColumn: { type: Boolean, default: false },
  visibleSkills: { type: Array, default: () => [] },
  auditEmptyState: { type: Object, default: () => ({}) },
  loading: { type: Boolean, default: false },
  errorMessage: { type: String, default: '' },
  selectedDomain: { type: String, default: '' },
  selectedOwner: { type: String, default: '' },
  selectedRiskLevel: { type: String, default: '' },
  selectedStatus: { type: String, default: '' },
  selectedRiskScenario: { type: String, default: '' },
  selectedOnlineState: { type: String, default: '' },
  selectedEnabledState: { type: String, default: '' },
  selectedDomainLabel: { type: String, default: '' },
  selectedOwnerLabel: { type: String, default: '' },
  selectedRiskLevelLabel: { type: String, default: '' },
  selectedStatusLabel: { type: String, default: '' },
  selectedRiskScenarioLabel: { type: String, default: '' },
  selectedOnlineStateLabel: { type: String, default: '' },
  selectedEnabledStateLabel: { type: String, default: '' },
  showRiskScenarioFilter: { type: Boolean, default: false },
  showOwnerFilter: { type: Boolean, default: false },
  showRiskLevelFilter: { type: Boolean, default: false },
  showStatusFilter: { type: Boolean, default: false },
  showOnlineFilter: { type: Boolean, default: false },
  showEnabledFilter: { type: Boolean, default: false },
  domainOptions: { type: Array, default: () => [] },
  ownerOptions: { type: Array, default: () => [] },
  riskLevelOptions: { type: Array, default: () => [] },
  statusOptions: { type: Array, default: () => [] },
  riskScenarioOptions: { type: Array, default: () => [] },
  onlineStateOptions: { type: Array, default: () => [] },
  enabledStateOptions: { type: Array, default: () => [] },
  activeFilterPopover: { type: String, default: '' },
  activeFilterTokens: { type: Array, default: () => [] },
  canCreateRiskRule: { type: Boolean, default: false }
})

const emit = defineEmits([
  'update:activeType',
  'update:keyword',
  'toggle-filter-popover',
  'close-filter-popover',
  'select-filter',
  'reset-filters',
  'create-risk-rule',
  'empty-action',
  'open-asset-detail'
])

const shellTabs = computed(() =>
  props.tabs.map((tab) => ({
    value: tab.id,
    label: tab.label
  }))
)

const currentPage = ref(1)
const pageSize = ref(10)
const pageSizeOptions = [10, 20, 50].map((size) => ({
  label: `${size} 条/页`,
  value: size
}))
const totalPages = computed(() => Math.max(1, Math.ceil(props.visibleSkills.length / pageSize.value)))
const pagedSkills = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return props.visibleSkills.slice(start, start + pageSize.value)
})
const paginationSummary = computed(() =>
  `共 ${props.visibleSkills.length} 条，每页 ${pageSize.value} 条，当前第 ${currentPage.value} / ${totalPages.value} 页`
)

watch(
  () => [
    props.activeType,
    props.keyword,
    props.selectedDomain,
    props.selectedOwner,
    props.selectedRiskLevel,
    props.selectedStatus,
    props.selectedRiskScenario,
    props.selectedOnlineState,
    props.selectedEnabledState
  ],
  () => {
    currentPage.value = 1
  }
)

watch(
  () => props.visibleSkills.length,
  () => {
    currentPage.value = Math.min(currentPage.value, totalPages.value)
    if (currentPage.value < 1) {
      currentPage.value = 1
    }
  },
  { immediate: true }
)

function selectFilter(type, value) {
  emit('select-filter', type, value)
}

function changePageSize(size) {
  const nextSize = Number(size) || 10
  pageSize.value = nextSize
  currentPage.value = 1
}
</script>

<style scoped src="../../assets/styles/views/audit-view.css"></style>
<style scoped src="../../assets/styles/views/audit-view-part2.css"></style>
