<template>
  <el-dialog
    v-model="visible"
    title="文档分段管理"
    width="1200px"
    :close-on-click-modal="false"
    class="segment-dialog"
  >
    <!-- 统计信息卡片 -->
    <div class="segment-stats">
      <div class="stat-item">
        <div class="stat-label">总分段数</div>
        <div class="stat-value">{{ totalSegments }}</div>
      </div>
      <div class="stat-item">
        <div class="stat-label">总字数</div>
        <div class="stat-value">{{ totalWords }}</div>
      </div>
      <div class="stat-item">
        <div class="stat-label">总 Tokens</div>
        <div class="stat-value">{{ totalTokens }}</div>
      </div>
    </div>

    <!-- 分段列表 -->
    <div class="segment-list" v-loading="loading">
      <div 
        v-for="segment in segments" 
        :key="segment.id"
        class="segment-item"
      >
        <div class="segment-header">
          <span class="segment-index">分段 {{ segment.position }}</span>
          <span class="segment-info">
            {{ segment.word_count }} 字 · {{ segment.tokens }} tokens
          </span>
          <div class="segment-status">
            <el-tag 
              :type="segment.enabled ? 'success' : 'info'"
              size="small"
            >
              {{ segment.enabled ? '已启用' : '已禁用' }}
            </el-tag>
            <el-tag 
              :type="getStatusType(segment.status)"
              size="small"
              style="margin-left: 8px;"
            >
              {{ getStatusText(segment.status) }}
            </el-tag>
          </div>
        </div>

        <!-- 分段内容显示（只读） -->
        <div class="segment-content">
          <div class="segment-text">
            {{ segment.content }}
          </div>
        </div>

        <!-- 关键词标签 -->
        <div class="segment-keywords" v-if="segment.keywords?.length">
          <el-tag
            v-for="keyword in segment.keywords"
            :key="keyword"
            size="small"
            style="margin-right: 8px;"
          >
            {{ keyword }}
          </el-tag>
        </div>
        
        <!-- 分段元数据 -->
        <div class="segment-meta">
          <span class="meta-item">
            <el-icon><Clock /></el-icon>
            创建时间: {{ formatTimestamp(segment.created_at) }}
          </span>
          <span class="meta-item" v-if="segment.completed_at">
            <el-icon><Check /></el-icon>
            完成时间: {{ formatTimestamp(segment.completed_at) }}
          </span>
          <span class="meta-item">
            <el-icon><View /></el-icon>
            命中次数: {{ segment.hit_count }}
          </span>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && segments.length === 0" class="empty-state">
        <p>暂无分段数据</p>
      </div>
    </div>

    <!-- 底部操作栏 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">关闭</el-button>
        <el-button 
          type="primary"
          @click="loadSegments"
        >
          刷新
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Clock, Check, View } from '@element-plus/icons-vue';
import { documentSegmentApi } from '../../../../../apis/ai';

defineOptions({
  name: 'DocumentSegmentDialog'
});

interface Props {
  /** 是否显示对话框 */
  modelValue: boolean;
  /** Dify数据集ID */
  datasetId: string;
  /** Dify文档ID */
  documentId: string;
}

const props = defineProps<Props>();
const emit = defineEmits(['update:modelValue']);

// 对话框显示状态
const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
});

// 数据状态
const loading = ref(false);
const segments = ref<any[]>([]);

// 统计信息
const totalSegments = computed(() => segments.value.length);
const totalWords = computed(() => 
  segments.value.reduce((sum, seg) => sum + (seg.word_count || 0), 0)
);
const totalTokens = computed(() => 
  segments.value.reduce((sum, seg) => sum + (seg.tokens || 0), 0)
);

// 组件挂载时自动加载数据（v-if 确保每次打开都会重新挂载）
onMounted(() => {
  loadSegments();
});

/**
 * 加载分段数据
 */
async function loadSegments() {
  try {
    loading.value = true;
    
    // 直接获取父级分段列表（Dify的分段本身就是主要内容）
    const result = await documentSegmentApi.getDocumentSegments(
      props.datasetId,
      props.documentId
    );
    
    if (result.success && result.dataList) {
      // 直接使用父级分段数据（后端已经从Dify响应中提取了data数组）
      segments.value = result.dataList || [];
    } else {
      segments.value = [];
      ElMessage.error(result.message || '加载分段失败');
    }
  } catch (error: any) {
    console.error('加载分段失败:', error);
    ElMessage.error(error.message || '加载分段失败');
  } finally {
    loading.value = false;
  }
}

/**
 * 获取状态类型
 */
function getStatusType(status: string): 'success' | 'info' | 'warning' | 'danger' {
  const typeMap: Record<string, 'success' | 'info' | 'warning' | 'danger'> = {
    'completed': 'success',
    'indexing': 'warning',
    'error': 'danger',
    'paused': 'info'
  };
  return typeMap[status] || 'info';
}

/**
 * 获取状态文本
 */
function getStatusText(status: string): string {
  const textMap: Record<string, string> = {
    'completed': '已完成',
    'indexing': '索引中',
    'error': '错误',
    'paused': '已暂停'
  };
  return textMap[status] || status;
}

/**
 * 格式化时间戳
 */
function formatTimestamp(timestamp: number): string {
  if (!timestamp) return '-';
  const date = new Date(timestamp * 1000);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
}

</script>

<style lang="scss" scoped>
.segment-dialog {
  :deep(.el-dialog) {
    border-radius: 14px;
    
    .el-dialog__header {
      padding: 24px 24px 16px;
      border-bottom: 1px solid #F3F3F5;
      
      .el-dialog__title {
        font-size: 18px;
        font-weight: 500;
        color: #101828;
        letter-spacing: -0.02em;
      }
    }
    
    .el-dialog__body {
      padding: 24px;
      background: #FAFAFA;
    }
    
    .el-dialog__footer {
      padding: 16px 24px;
      border-top: 1px solid #F3F3F5;
    }
  }
}

.segment-stats {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;

  .stat-item {
    flex: 1;
    background: #FFFFFF;
    border: 1px solid rgba(0, 0, 0, 0.1);
    border-radius: 14px;
    padding: 20px 16px;
    text-align: center;
    transition: all 0.2s;

    &:hover {
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
      transform: translateY(-2px);
    }

    .stat-label {
      font-size: 14px;
      font-weight: 400;
      color: #4A5565;
      margin-bottom: 8px;
      letter-spacing: -0.01em;
    }

    .stat-value {
      font-size: 28px;
      font-weight: 400;
      color: #101828;
      letter-spacing: -0.02em;
    }
  }
}

.segment-list {
  max-height: 520px;
  overflow-y: auto;
  padding-right: 4px;
  
  /* 自定义滚动条 */
  &::-webkit-scrollbar {
    width: 6px;
  }
  
  &::-webkit-scrollbar-track {
    background: transparent;
  }
  
  &::-webkit-scrollbar-thumb {
    background: #D1D5DB;
    border-radius: 3px;
    
    &:hover {
      background: #9CA3AF;
    }
  }

  .segment-item {
    background: #FFFFFF;
    border: 1px solid rgba(0, 0, 0, 0.1);
    border-radius: 14px;
    padding: 16px;
    margin-bottom: 12px;
    transition: all 0.2s;

    &:hover {
      border-color: #E7000B;
      box-shadow: 0 4px 12px rgba(231, 0, 11, 0.12);
    }

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

  .segment-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12px;
    gap: 12px;

    .segment-index {
      font-weight: 500;
      color: #101828;
      font-size: 14px;
      letter-spacing: -0.01em;
      white-space: nowrap;
    }

    .segment-info {
      flex: 1;
      font-size: 12px;
      color: #6A7282;
      letter-spacing: -0.01em;
      white-space: nowrap;
    }

    .segment-status {
      display: flex;
      gap: 8px;
    }
  }

  .segment-content {
    .segment-text {
      padding: 12px;
      background: #F9FAFB;
      border: 1px solid transparent;
      border-radius: 8px;
      line-height: 1.6;
      color: #4A5565;
      font-size: 14px;
      white-space: pre-wrap;
      word-break: break-word;
      letter-spacing: -0.01em;
    }
  }

  .segment-keywords {
    margin-top: 12px;
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    
    :deep(.el-tag) {
      background: #EFF6FF;
      border: 1px solid transparent;
      border-radius: 8px;
      color: #1447E6;
      font-size: 12px;
      padding: 2px 8px;
      height: 24px;
      line-height: 20px;
    }
  }

  .segment-meta {
    margin-top: 12px;
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    padding-top: 12px;
    border-top: 1px solid rgba(0, 0, 0, 0.06);

    .meta-item {
      display: flex;
      align-items: center;
      gap: 6px;
      font-size: 13px;
      color: #667085;
      letter-spacing: -0.01em;

      .el-icon {
        font-size: 14px;
        color: #9CA3AF;
      }
    }
  }

  .empty-state {
    text-align: center;
    padding: 80px 20px;
    background: #FFFFFF;
    border: 1px solid rgba(0, 0, 0, 0.1);
    border-radius: 14px;

    p {
      font-size: 14px;
      color: #6A7282;
      margin: 0;
      letter-spacing: -0.01em;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  :deep(.el-button) {
    border-radius: 8px;
    font-weight: 500;
    letter-spacing: -0.01em;
    
    &.el-button--default {
      background: #F3F3F5;
      border-color: transparent;
      color: #0A0A0A;
      
      &:hover {
        background: #E5E5E7;
      }
    }
    
    &.el-button--primary {
      background: #E7000B;
      border-color: #E7000B;
      
      &:hover {
        background: #C90009;
        border-color: #C90009;
      }
    }
  }
}

/* 添加分段对话框样式 */
:deep(.el-dialog__wrapper) {
  .el-dialog {
    border-radius: 14px;
    
    .el-form-item__label {
      font-size: 14px;
      font-weight: 500;
      color: #0A0A0A;
      letter-spacing: -0.01em;
    }
    
    .el-input__wrapper {
      background: #F3F3F5;
      border: 1px solid transparent;
      border-radius: 8px;
      box-shadow: none;
      
      &:hover {
        border-color: rgba(231, 0, 11, 0.2);
      }
      
      &.is-focus {
        border-color: #E7000B;
        background: #FFFFFF;
      }
    }
    
    .el-textarea__inner {
      background: #F3F3F5;
      border: 1px solid transparent;
      border-radius: 8px;
      box-shadow: none;
      
      &:hover {
        border-color: rgba(231, 0, 11, 0.2);
      }
      
      &:focus {
        border-color: #E7000B;
        background: #FFFFFF;
      }
    }
    
    .el-select {
      .el-input__wrapper {
        background: #F3F3F5;
      }
    }
  }
}
</style>

