<template>
  <section class="digital-employee-list-panel">
    <div class="list-toolbar">
      <div class="filter-set">
        <label class="search-filter">
          <i class="mdi mdi-magnify"></i>
          <input
            :value="keyword"
            type="search"
            placeholder="搜索数字员工技能、编号、执行计划或维护人"
            @input="emit('update:keyword', $event.target.value)"
          />
        </label>

        <AuditPickerFilter
          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)"
        />

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

        <AuditPickerFilter
          id="executionMode"
          title="选择执行方式"
          close-label="关闭执行方式选择"
          :active-filter-popover="activeFilterPopover"
          :label="selectedExecutionModeLabel"
          :options="executionModeOptions"
          :selected-value="selectedExecutionMode"
          @toggle="emit('toggle-filter-popover', $event)"
          @close="emit('close-filter-popover')"
          @select="selectFilter('executionMode', $event)"
        />
      </div>

      <div class="toolbar-actions">
        <button
          v-if="keyword || 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 digital-refresh-action"
          type="button"
          :disabled="loading"
          @click="emit('load-employees')"
        >
          <i class="mdi mdi-refresh"></i>
          <span>{{ loading ? '刷新中...' : '刷新' }}</span>
        </button>
      </div>
    </div>

    <p class="hint">
      <i class="mdi mdi-information-outline"></i>
      归集后台自动执行的数字员工技能，可查看技能内容、执行计划、启动状态和最近版本。
    </p>

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

    <div
      class="table-wrap digital-table-wrap"
      :class="{ 'is-empty': !loading && !errorMessage && !visibleEmployees.length }"
    >
      <div v-if="loading" class="table-state">
        <TableLoadingState
          variant="panel"
          title="数字员工资产同步中"
          message="正在加载数字员工资产"
          icon="mdi mdi-view-list-outline"
        />
      </div>

      <div v-else-if="errorMessage" class="table-state error">
        <i class="mdi mdi-alert-circle-outline"></i>
        <p>{{ errorMessage }}</p>
      </div>

      <TableEmptyState
        v-else-if="!visibleEmployees.length"
        eyebrow="数字员工"
        title="暂无匹配的数字员工"
        description="当前没有符合搜索条件的后台执行技能。"
        icon="mdi mdi-account-cog-outline"
        tone="theme"
        art-label="STAFF"
        :tips="['数字员工已从规则中心拆出为独立入口', '运行与定时操作统一进入详情后处理']"
      />

      <table v-else class="digital-employees-table">
        <colgroup>
          <col class="col-skill">
          <col class="col-skill-type">
          <col class="col-owner">
          <col class="col-schedule">
          <col class="col-mode">
          <col class="col-status">
          <col class="col-enabled">
          <col class="col-updated">
        </colgroup>
        <thead>
          <tr>
            <th>技能名称</th>
            <th>技能类型</th>
            <th>维护归口</th>
            <th>执行计划</th>
            <th>触发方式</th>
            <th>资产状态</th>
            <th>启动状态</th>
            <th>最近更新</th>
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="employee in pagedEmployees"
            :key="employee.id"
            @click="emit('open-employee-detail', employee)"
          >
            <td>
              <div class="skill-name-cell">
                <span class="skill-avatar" :class="employee.badgeTone">{{ employee.short }}</span>
                <div>
                  <strong>{{ employee.name }}</strong>
                  <span class="skill-list-subtitle">{{ employee.summary || employee.code }}</span>
                </div>
              </div>
            </td>
            <td><span class="scope-pill skill-type-pill">{{ employee.skillCategory }}</span></td>
            <td>{{ employee.owner }}</td>
            <td><span class="scope-pill">{{ employee.scope }}</span></td>
            <td>{{ employee.executionMode }}</td>
            <td>
              <span :class="['status-pill', employee.statusTone]">{{ employee.status }}</span>
            </td>
            <td><span :class="['status-pill', employee.enabledTone]">{{ employee.enabledLabel }}</span></td>
            <td>{{ employee.updatedAt || '-' }}</td>
          </tr>
        </tbody>
      </table>
    </div>

    <footer v-if="!loading && !errorMessage && visibleEmployees.length" class="list-foot digital-employee-pagination">
      <span class="page-summary">共 {{ visibleEmployees.length }} 条，目前第 {{ currentPage }} / {{ totalPages }} 页</span>
      <div class="pager" aria-label="员工技能分页">
        <button class="page-nav" type="button" :disabled="currentPage === 1" @click="currentPage--">
          <i class="mdi mdi-chevron-left"></i>
        </button>
        <button
          v-for="page in pageNumbers"
          :key="page"
          class="page-number"
          :class="{ active: currentPage === page }"
          type="button"
          @click="currentPage = page"
        >
          {{ page }}
        </button>
        <button class="page-nav" type="button" :disabled="currentPage === totalPages" @click="currentPage++">
          <i class="mdi mdi-chevron-right"></i>
        </button>
      </div>
    </footer>
  </section>
</template>

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

import AuditPickerFilter from './AuditPickerFilter.vue'
import TableEmptyState from '../shared/TableEmptyState.vue'
import TableLoadingState from '../shared/TableLoadingState.vue'

defineOptions({
  name: 'DigitalEmployeeListPanel'
})

const props = defineProps({
  keyword: { type: String, default: '' },
  activeFilterPopover: { type: String, default: '' },
  selectedStatus: { type: String, default: '' },
  selectedStatusLabel: { type: String, default: '' },
  statusOptions: { type: Array, default: () => [] },
  selectedEnabledState: { type: String, default: '' },
  selectedEnabledLabel: { type: String, default: '' },
  enabledStateOptions: { type: Array, default: () => [] },
  selectedExecutionMode: { type: String, default: '' },
  selectedExecutionModeLabel: { type: String, default: '' },
  executionModeOptions: { type: Array, default: () => [] },
  activeFilterTokens: { type: Array, default: () => [] },
  loading: { type: Boolean, default: false },
  errorMessage: { type: String, default: '' },
  visibleEmployees: { type: Array, default: () => [] }
})

const emit = defineEmits([
  'update:keyword',
  'toggle-filter-popover',
  'close-filter-popover',
  'select-filter',
  'reset-filters',
  'load-employees',
  'open-employee-detail'
])

const currentPage = ref(1)
const pageSize = 20
const totalPages = computed(() => Math.max(1, Math.ceil(props.visibleEmployees.length / pageSize)))
const pagedEmployees = computed(() => {
  const start = (currentPage.value - 1) * pageSize
  return props.visibleEmployees.slice(start, start + pageSize)
})
const pageNumbers = computed(() => {
  const total = totalPages.value
  if (total <= 7) {
    return Array.from({ length: total }, (_, index) => index + 1)
  }
  const start = Math.max(1, Math.min(currentPage.value - 3, total - 6))
  return Array.from({ length: 7 }, (_, index) => start + index)
})

watch(
  () => [props.keyword, props.selectedStatus, props.selectedEnabledState, props.selectedExecutionMode],
  () => {
    currentPage.value = 1
  }
)

watch(
  () => props.visibleEmployees.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)
}
</script>

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

<style scoped>
.digital-employee-list-panel {
  flex: 1 1 0;
  min-height: 0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.digital-employee-list-panel .digital-table-wrap {
  flex: 1 1 0;
  min-height: 0;
}

.digital-employee-list-panel .digital-employee-pagination {
  flex: 0 0 auto;
  display: grid;
  grid-template-columns: 1fr auto 1fr;
  align-items: center;
  gap: 16px;
}

.digital-employee-list-panel .digital-employee-pagination .page-summary {
  justify-self: start;
}

.digital-employee-list-panel .pager {
  display: inline-flex;
  justify-content: center;
  gap: 6px;
  padding: 4px;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  background: #f8fafc;
}

.digital-employee-list-panel .pager button {
  width: 32px;
  height: 32px;
  border: 0;
  border-radius: 9px;
  background: transparent;
  color: #334155;
  font-size: 14px;
  font-weight: 800;
  cursor: pointer;
}

.digital-employee-list-panel .pager button:hover:not(.active):not(:disabled) {
  background: #fff;
  color: var(--theme-primary-active);
  box-shadow: 0 1px 4px rgba(15, 23, 42, .08);
}

.digital-employee-list-panel .pager button.active {
  background: var(--theme-primary-active);
  color: #fff;
  box-shadow: 0 8px 16px var(--theme-primary-shadow);
}

.digital-employee-list-panel .pager button:disabled {
  color: #cbd5e1;
  cursor: not-allowed;
}
</style>
