<template>
  <div class="xt-right-summary-panel">
    <!-- 统计卡片 -->
    <div class="stats-card card">
      <div class="card-header">
        <h3 class="card-title">配置摘要</h3>
        <div class="last-test-time" v-if="stats.lastTestAt">
          <i class="el-icon-time"></i>
          <span>{{ formatLastTestTime(stats.lastTestAt) }}</span>
        </div>
      </div>
      
      <div class="stats-grid">
        <div class="stat-item changed">
          <div class="stat-icon">
            <i class="el-icon-edit-outline"></i>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ stats.changed || 0 }}</div>
            <div class="stat-label">已变更</div>
          </div>
        </div>

        <div class="stat-item passed">
          <div class="stat-icon">
            <i class="el-icon-circle-check"></i>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ stats.passed || 0 }}</div>
            <div class="stat-label">已通过</div>
          </div>
        </div>

        <div class="stat-item risk">
          <div class="stat-icon">
            <i class="el-icon-warning-outline"></i>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ stats.risk || 0 }}</div>
            <div class="stat-label">有风险</div>
          </div>
        </div>

        <div class="stat-item total">
          <div class="stat-icon">
            <i class="el-icon-files"></i>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ totalItems }}</div>
            <div class="stat-label">总配置</div>
          </div>
        </div>
      </div>

      <!-- 进度条 -->
      <div class="progress-section" v-if="totalItems > 0">
        <div class="progress-label">
          <span>测试进度</span>
          <span class="progress-text">{{ passedPercent }}%</span>
        </div>
        <el-progress
          :percentage="passedPercent"
          :stroke-width="8"
          :show-text="false"
          :status="getProgressStatus()"
          class="custom-progress"
        />
      </div>
    </div>

    <!-- 配置项列表 -->
    <div class="items-card card">
      <div class="card-header">
        <h3 class="card-title">配置项状态</h3>
        <div class="header-actions">
          <el-dropdown trigger="click" @command="handleFilter">
            <el-button type="text" size="small" class="filter-btn">
              <i class="el-icon-filter"></i>
              {{ filterText }}
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="all">全部</el-dropdown-item>
              <el-dropdown-item command="changed">仅变更</el-dropdown-item>
              <el-dropdown-item command="passed">仅通过</el-dropdown-item>
              <el-dropdown-item command="risk">仅风险</el-dropdown-item>
              <el-dropdown-item command="pending">仅待测</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>

      <div class="items-list" v-loading="loading">
        <!-- 搜索框 -->
        <div class="search-section" v-if="filteredItems.length > 10">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索配置项..."
            size="small"
            prefix-icon="el-icon-search"
            clearable
            class="search-input"
          />
        </div>

        <!-- 配置项列表 -->
        <div class="items-container">
          <div
            v-for="item in displayItems"
            :key="item.key"
            class="item-row"
            :class="[`status-${item.status}`, { 'is-active': item.key === activeItemKey }]"
            @click="handleItemClick(item)"
          >
            <div class="item-icon">
              <i :class="getStatusIcon(item.status)" :style="{ color: getStatusColor(item.status) }"></i>
            </div>
            
            <div class="item-content">
              <div class="item-name">{{ item.name || item.key }}</div>
              <div class="item-meta" v-if="item.path || item.group">
                <span class="item-path" v-if="item.path">{{ item.path }}</span>
                <el-tag size="mini" v-if="item.group" class="item-group">{{ item.group }}</el-tag>
              </div>
            </div>

            <div class="item-actions">
              <el-tooltip :content="getStatusTooltip(item.status)" placement="left">
                <div class="status-indicator" :class="`status-${item.status}`"></div>
              </el-tooltip>
              
              <!-- 变更标识 -->
              <el-badge is-dot v-if="item.isChanged" class="change-badge">
              </el-badge>
            </div>
          </div>

          <!-- 加载更多 -->
          <div class="load-more" v-if="hasMore && !loading">
            <el-button type="text" @click="loadMore" size="small">
              加载更多 ({{ remainingCount }} 项)
            </el-button>
          </div>
        </div>

        <!-- 空状态 -->
        <div class="empty-state" v-if="filteredItems.length === 0 && !loading">
          <div class="empty-icon">
            <i class="el-icon-document-copy"></i>
          </div>
          <div class="empty-text">
            <p class="empty-title">{{ getEmptyTitle() }}</p>
            <p class="empty-desc">{{ getEmptyDesc() }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 快速操作 -->
    <div class="quick-actions card" v-if="stats.changed > 0 || stats.risk > 0">
      <div class="card-header">
        <h3 class="card-title">快速操作</h3>
      </div>
      
      <div class="action-buttons">
        <el-button
          type="primary"
          size="small"
          :disabled="stats.changed === 0"
          @click="$emit('publish-changes')"
          class="action-btn"
        >
          <i class="el-icon-upload2"></i>
          发布变更 ({{ stats.changed }})
        </el-button>
        
        <el-button
          type="warning"
          size="small"
          :disabled="stats.risk === 0"
          @click="$emit('fix-risks')"
          class="action-btn"
        >
          <i class="el-icon-warning"></i>
          修复风险 ({{ stats.risk }})
        </el-button>
        
        <el-button
          type="info"
          size="small"
          @click="$emit('test-all')"
          class="action-btn"
        >
          <i class="el-icon-refresh"></i>
          重新测试
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'XtRightSummaryPanel',
  
  props: {
    // 统计数据
    stats: {
      type: Object,
      default: () => ({
        changed: 0,
        passed: 0,
        risk: 0,
        lastTestAt: null
      })
    },
    
    // 配置项列表
    items: {
      type: Array,
      default: () => []
      // 格式: { key, name, path, group, status: 'passed'|'risk'|'pending'|'changed', isChanged }
    },
    
    // 加载状态
    loading: {
      type: Boolean,
      default: false
    },
    
    // 当前激活的配置项
    activeItemKey: {
      type: String,
      default: ''
    }
  },

  data() {
    return {
      searchKeyword: '',
      currentFilter: 'all',
      pageSize: 20,
      currentPage: 1
    }
  },

  computed: {
    // 总配置项数
    totalItems() {
      return this.items.length
    },

    // 通过率百分比
    passedPercent() {
      if (this.totalItems === 0) return 0
      return Math.round((this.stats.passed / this.totalItems) * 100)
    },

    // 过滤文本
    filterText() {
      const filterMap = {
        all: '全部',
        changed: '仅变更',
        passed: '仅通过',
        risk: '仅风险',
        pending: '仅待测'
      }
      return filterMap[this.currentFilter] || '全部'
    },

    // 过滤后的配置项
    filteredItems() {
      let filtered = this.items

      // 状态过滤
      if (this.currentFilter !== 'all') {
        filtered = filtered.filter(item => {
          switch (this.currentFilter) {
            case 'changed':
              return item.isChanged
            case 'passed':
              return item.status === 'passed'
            case 'risk':
              return item.status === 'risk'
            case 'pending':
              return item.status === 'pending'
            default:
              return true
          }
        })
      }

      // 搜索过滤
      if (this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.toLowerCase()
        filtered = filtered.filter(item =>
          (item.name || item.key).toLowerCase().includes(keyword) ||
          (item.path || '').toLowerCase().includes(keyword) ||
          (item.group || '').toLowerCase().includes(keyword)
        )
      }

      return filtered
    },

    // 显示的配置项（分页）
    displayItems() {
      const endIndex = this.currentPage * this.pageSize
      return this.filteredItems.slice(0, endIndex)
    },

    // 是否有更多数据
    hasMore() {
      return this.displayItems.length < this.filteredItems.length
    },

    // 剩余数量
    remainingCount() {
      return this.filteredItems.length - this.displayItems.length
    }
  },

  watch: {
    // 重置分页当过滤条件变化时
    currentFilter() {
      this.currentPage = 1
    },
    
    searchKeyword() {
      this.currentPage = 1
    }
  },

  methods: {
    // 处理过滤
    handleFilter(command) {
      this.currentFilter = command
    },

    // 加载更多
    loadMore() {
      this.currentPage++
    },

    // 处理配置项点击
    handleItemClick(item) {
      this.$emit('item-click', item)
    },

    // 获取进度条状态
    getProgressStatus() {
      if (this.stats.risk > 0) return 'exception'
      if (this.passedPercent === 100) return 'success'
      return null
    },

    // 获取状态图标
    getStatusIcon(status) {
      const iconMap = {
        passed: 'el-icon-circle-check',
        risk: 'el-icon-warning-outline',
        pending: 'el-icon-time',
        changed: 'el-icon-edit-outline'
      }
      return iconMap[status] || 'el-icon-info'
    },

    // 获取状态颜色
    getStatusColor(status) {
      const colorMap = {
        passed: 'var(--color-success)',
        risk: 'var(--color-danger)',
        pending: 'var(--color-text-tertiary)',
        changed: 'var(--color-warning)'
      }
      return colorMap[status] || 'var(--color-text-tertiary)'
    },

    // 获取状态提示
    getStatusTooltip(status) {
      const tooltipMap = {
        passed: '测试通过',
        risk: '存在风险',
        pending: '等待测试',
        changed: '已变更'
      }
      return tooltipMap[status] || '未知状态'
    },

    // 格式化最后测试时间
    formatLastTestTime(timestamp) {
      if (!timestamp) return ''
      
      const now = Date.now()
      const diff = now - timestamp
      const minutes = Math.floor(diff / 60000)
      const hours = Math.floor(diff / 3600000)
      const days = Math.floor(diff / 86400000)

      if (minutes < 1) return '刚刚'
      if (minutes < 60) return `${minutes}分钟前`
      if (hours < 24) return `${hours}小时前`
      if (days < 7) return `${days}天前`
      
      return new Date(timestamp).toLocaleDateString('zh-CN')
    },

    // 获取空状态标题
    getEmptyTitle() {
      if (this.searchKeyword) return '未找到匹配的配置项'
      if (this.currentFilter !== 'all') return '暂无符合条件的配置项'
      return '暂无配置项'
    },

    // 获取空状态描述
    getEmptyDesc() {
      if (this.searchKeyword) return '请尝试其他搜索关键词'
      if (this.currentFilter !== 'all') return '请尝试调整筛选条件'
      return '请先添加配置项'
    }
  }
}
</script>

<style lang="scss" scoped>
.xt-right-summary-panel {
  width: 320px;
  padding: var(--spacing-4);
  background: var(--color-bg-secondary);
  border-left: 1px solid var(--color-border-primary);
  height: 100vh;
  overflow-y: auto;
  flex-shrink: 0;

  .card {
    margin-bottom: var(--spacing-4);

    &:last-child {
      margin-bottom: 0;
    }

    .card-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: var(--spacing-4);

      .card-title {
        color: var(--color-text-primary);
        font-size: var(--font-size-base);
        font-weight: var(--font-weight-semibold);
        margin: 0;
      }

      .last-test-time {
        display: flex;
        align-items: center;
        gap: var(--spacing-1);
        color: var(--color-text-tertiary);
        font-size: var(--font-size-xs);

        i {
          font-size: var(--font-size-sm);
        }
      }

      .header-actions {
        .filter-btn {
          color: var(--color-text-tertiary);
          padding: var(--spacing-1) var(--spacing-2);
          border-radius: var(--radius-md);
          font-size: var(--font-size-sm);

          &:hover {
            background: var(--color-bg-tertiary);
            color: var(--color-primary);
          }
        }
      }
    }
  }

  .stats-card {
    .stats-grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: var(--spacing-3);
      margin-bottom: var(--spacing-4);

      .stat-item {
        display: flex;
        align-items: center;
        gap: var(--spacing-2);
        padding: var(--spacing-3);
        background: var(--color-bg-tertiary);
        border-radius: var(--radius-md);
        transition: all var(--duration-200) var(--ease-out);

        &:hover {
          transform: translateY(-1px);
          box-shadow: var(--shadow-sm);
        }

        .stat-icon {
          width: 24px;
          height: 24px;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: var(--radius-full);
          font-size: var(--font-size-sm);

          i {
            font-size: inherit;
          }
        }

        .stat-content {
          flex: 1;

          .stat-value {
            color: var(--color-text-primary);
            font-size: var(--font-size-lg);
            font-weight: var(--font-weight-bold);
            line-height: var(--line-height-tight);
          }

          .stat-label {
            color: var(--color-text-tertiary);
            font-size: var(--font-size-xs);
            font-weight: var(--font-weight-medium);
          }
        }

        &.changed {
          .stat-icon {
            background: var(--color-warning-100);
            color: var(--color-warning);
          }
        }

        &.passed {
          .stat-icon {
            background: var(--color-success-100);
            color: var(--color-success);
          }
        }

        &.risk {
          .stat-icon {
            background: var(--color-danger-100);
            color: var(--color-danger);
          }
        }

        &.total {
          .stat-icon {
            background: var(--color-primary-100);
            color: var(--color-primary);
          }
        }
      }
    }

    .progress-section {
      .progress-label {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: var(--spacing-2);
        font-size: var(--font-size-sm);

        .progress-text {
          color: var(--color-text-tertiary);
          font-weight: var(--font-weight-medium);
        }
      }

      .custom-progress {
        ::v-deep .el-progress-bar__outer {
          background: var(--color-bg-tertiary);
          border-radius: var(--radius-full);
        }

        ::v-deep .el-progress-bar__inner {
          border-radius: var(--radius-full);
          transition: width var(--duration-300) var(--ease-out);
        }
      }
    }
  }

  .items-card {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;

    .items-list {
      flex: 1;
      display: flex;
      flex-direction: column;
      min-height: 0;

      .search-section {
        margin-bottom: var(--spacing-3);

        .search-input {
          ::v-deep .el-input__inner {
            background: var(--color-bg-tertiary);
            border-radius: var(--radius-lg);
            font-size: var(--font-size-sm);
          }
        }
      }

      .items-container {
        flex: 1;
        overflow-y: auto;

        .item-row {
          display: flex;
          align-items: center;
          gap: var(--spacing-3);
          padding: var(--spacing-3);
          background: var(--color-bg-card);
          border: 1px solid var(--color-border-secondary);
          border-radius: var(--radius-md);
          margin-bottom: var(--spacing-2);
          cursor: pointer;
          transition: all var(--duration-200) var(--ease-out);
          position: relative;

          &:hover {
            background: var(--color-bg-tertiary);
            border-color: var(--color-primary);
            transform: translateX(2px);
          }

          &.is-active {
            background: var(--color-primary-50);
            border-color: var(--color-primary);
            box-shadow: 0 0 0 1px var(--color-primary-100);
          }

          .item-icon {
            width: 20px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;

            i {
              font-size: var(--font-size-sm);
            }
          }

          .item-content {
            flex: 1;
            min-width: 0;

            .item-name {
              color: var(--color-text-primary);
              font-size: var(--font-size-sm);
              font-weight: var(--font-weight-medium);
              line-height: var(--line-height-tight);
              margin-bottom: var(--spacing-1);
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }

            .item-meta {
              display: flex;
              align-items: center;
              gap: var(--spacing-2);

              .item-path {
                color: var(--color-text-quaternary);
                font-size: var(--font-size-xs);
                font-family: var(--font-family-mono);
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                flex: 1;
              }

              .item-group {
                flex-shrink: 0;
              }
            }
          }

          .item-actions {
            display: flex;
            align-items: center;
            gap: var(--spacing-1);
            flex-shrink: 0;
            position: relative;

            .status-indicator {
              width: 8px;
              height: 8px;
              border-radius: var(--radius-full);
              
              &.status-passed {
                background: var(--color-success);
              }
              
              &.status-risk {
                background: var(--color-danger);
              }
              
              &.status-pending {
                background: var(--color-text-tertiary);
              }
              
              &.status-changed {
                background: var(--color-warning);
              }
            }

            .change-badge {
              position: absolute;
              top: -4px;
              right: -4px;

              ::v-deep .el-badge__content {
                background: var(--color-warning);
                border: 1px solid var(--color-bg-card);
              }
            }
          }
        }

        .load-more {
          text-align: center;
          padding: var(--spacing-3);

          .el-button {
            color: var(--color-text-tertiary);
            font-size: var(--font-size-sm);

            &:hover {
              color: var(--color-primary);
            }
          }
        }
      }

      .empty-state {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: var(--spacing-8) var(--spacing-4);
        text-align: center;

        .empty-icon {
          font-size: 48px;
          color: var(--color-text-quaternary);
          margin-bottom: var(--spacing-3);
        }

        .empty-text {
          .empty-title {
            color: var(--color-text-secondary);
            font-size: var(--font-size-base);
            font-weight: var(--font-weight-medium);
            margin: 0 0 var(--spacing-1) 0;
          }

          .empty-desc {
            color: var(--color-text-tertiary);
            font-size: var(--font-size-sm);
            margin: 0;
          }
        }
      }
    }
  }

  .quick-actions {
    .action-buttons {
      display: flex;
      flex-direction: column;
      gap: var(--spacing-2);

      .action-btn {
        justify-content: flex-start;
        border-radius: var(--radius-md);
        font-weight: var(--font-weight-medium);
        text-align: left;

        i {
          margin-right: var(--spacing-2);
        }

        &:not(:disabled):hover {
          transform: translateY(-1px);
          box-shadow: var(--shadow-sm);
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 1024px) {
  .xt-right-summary-panel {
    width: 280px;

    .stats-card {
      .stats-grid {
        .stat-item {
          .stat-content {
            .stat-value {
              font-size: var(--font-size-base);
            }
          }
        }
      }
    }
  }
}

// 滚动条样式
.xt-right-summary-panel {
  &::-webkit-scrollbar {
    width: 4px;
  }

  &::-webkit-scrollbar-track {
    background: var(--color-bg-tertiary);
  }

  &::-webkit-scrollbar-thumb {
    background: var(--color-border-primary);
    border-radius: var(--radius-full);

    &:hover {
      background: var(--color-text-quaternary);
    }
  }

  .items-container {
    &::-webkit-scrollbar {
      width: 4px;
    }

    &::-webkit-scrollbar-track {
      background: transparent;
    }

    &::-webkit-scrollbar-thumb {
      background: var(--color-border-primary);
      border-radius: var(--radius-full);

      &:hover {
        background: var(--color-text-quaternary);
      }
    }
  }
}
</style>
