<template>
  <EnterpriseListPage
    variant="digital-employee-list-panel"
    :panel="false"
    :loading="loading"
    :error="errorMessage"
    :empty="!visibleEmployees.length"
    :empty-state="emptyState"
    :show-pagination="!loading && !errorMessage && visibleEmployees.length > 0"
    :current-page="currentPage"
    :page-size="pageSize"
    :page-size-options="pageSizeOptions"
    :show-page-size="true"
    :summary="paginationSummary"
    :total="visibleEmployees.length"
    :total-pages="totalPages"
    loading-title="数字员工资产同步中"
    loading-message="正在加载数字员工资产"
    loading-icon="mdi mdi-view-list-outline"
    @update:current-page="currentPage = $event"
    @update:page-size="pageSize = $event"
    @page-size-change="changePageSize"
  >
    <template #filters>
      <label class="list-search">
        <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="skillCategory"
        title="选择技能类型"
        close-label="关闭技能类型选择"
        :active-filter-popover="activeFilterPopover"
        :label="selectedSkillCategoryLabel"
        :options="skillCategoryOptions"
        :selected-value="selectedSkillCategory"
        @toggle="emit('toggle-filter-popover', $event)"
        @close="emit('close-filter-popover')"
        @select="selectFilter('skillCategory', $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)"
      />
    </template>

    <template #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>
    </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="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="digital-skill-cell">
                <span class="digital-skill-avatar" :class="employee.badgeTone">{{ employee.short }}</span>
                <strong class="doc-id">{{ employee.name }}</strong>
              </div>
            </td>
            <td data-label="技能类型"><span class="doc-kind-tag application">{{ employee.skillCategory }}</span></td>
            <td data-label="维护归口">{{ employee.owner }}</td>
            <td data-label="执行计划"><span class="type-tag other">{{ employee.scope }}</span></td>
            <td data-label="触发方式">{{ employee.executionMode }}</td>
            <td data-label="资产状态">
              <span :class="['status-tag', employee.statusTone]">{{ employee.status }}</span>
            </td>
            <td data-label="启动状态"><span :class="['status-tag', employee.enabledTone]">{{ employee.enabledLabel }}</span></td>
            <td data-label="最近更新">{{ employee.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: 'DigitalEmployeeListPanel'
})

const props = defineProps({
  keyword: { type: String, default: '' },
  activeFilterPopover: { type: String, default: '' },
  selectedStatus: { type: String, default: '' },
  selectedStatusLabel: { type: String, default: '' },
  statusOptions: { type: Array, default: () => [] },
  selectedSkillCategory: { type: String, default: '' },
  selectedSkillCategoryLabel: { type: String, default: '' },
  skillCategoryOptions: { 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 = ref(10)
const pageSizeOptions = [
  { label: '10 条/页', value: 10 },
  { label: '20 条/页', value: 20 },
  { label: '50 条/页', value: 50 }
]
const totalPages = computed(() => Math.max(1, Math.ceil(props.visibleEmployees.length / pageSize.value)))
const pagedEmployees = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return props.visibleEmployees.slice(start, start + pageSize.value)
})
const paginationSummary = computed(() =>
  `共 ${props.visibleEmployees.length} 条，每页 ${pageSize.value} 条，目前第 ${currentPage.value} / ${totalPages.value} 页`
)
const emptyState = {
  eyebrow: '数字员工',
  title: '暂无匹配的数字员工',
  description: '当前没有符合搜索条件的后台执行技能。',
  icon: 'mdi mdi-account-cog-outline',
  tone: 'theme',
  artLabel: 'STAFF',
  tips: ['数字员工已从规则中心拆出为独立入口', '运行与定时操作统一进入详情后处理']
}

watch(
  () => [
    props.keyword,
    props.selectedStatus,
    props.selectedSkillCategory,
    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)
}

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

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

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

@media (max-width: 760px) {
  .digital-employee-list-panel {
    overflow: auto;
  }

  .digital-employee-list-panel :deep(.table-wrap) {
    flex: 0 0 auto;
    min-height: 0;
    display: block;
    overflow: visible;
  }

  .digital-employee-list-panel :deep(.list-foot) {
    flex: 0 0 auto;
    padding: 0 12px 12px;
  }
}
</style>
