<template>
  <el-drawer
    :visible.sync="drawerVisible"
    :title="title"
    direction="rtl"
    size="480px"
    :before-close="handleClose"
    class="xt-test-connection-drawer"
    :wrapper-closable="false"
    :close-on-press-escape="true"
  >
    <!-- 抽屉头部 -->
    <template slot="title">
      <div class="drawer-header">
        <div class="header-title">
          <i class="el-icon-connection header-icon"></i>
          <span>{{ title }}</span>
        </div>
        <div class="header-actions">
          <el-button
            type="primary"
            size="small"
            :loading="loading"
            @click="handleRetest"
            class="retest-btn"
          >
            <i class="el-icon-refresh" v-if="!loading"></i>
            重新测试
          </el-button>
        </div>
      </div>
    </template>

    <!-- 抽屉内容 -->
    <div class="drawer-content" v-loading="loading" element-loading-text="正在测试连接...">
      <!-- 测试状态概览 -->
      <div class="test-overview" v-if="logs.length > 0">
        <div class="overview-stats">
          <div class="stat-item success">
            <span class="stat-count">{{ successCount }}</span>
            <span class="stat-label">成功</span>
          </div>
          <div class="stat-item warning">
            <span class="stat-count">{{ warningCount }}</span>
            <span class="stat-label">警告</span>
          </div>
          <div class="stat-item error">
            <span class="stat-count">{{ failCount }}</span>
            <span class="stat-label">失败</span>
          </div>
          <div class="stat-item total">
            <span class="stat-count">{{ totalCost }}ms</span>
            <span class="stat-label">总耗时</span>
          </div>
        </div>
      </div>

      <!-- 测试日志时间轴 -->
      <div class="timeline-container" v-if="logs.length > 0">
        <div class="timeline">
          <div
            v-for="(log, index) in logs"
            :key="index"
            class="timeline-item"
            :class="[`status-${log.status}`, { 'is-last': index === logs.length - 1 }]"
          >
            <!-- 时间轴节点 -->
            <div class="timeline-node">
              <div class="node-icon">
                <i 
                  :class="getStatusIcon(log.status)"
                  :style="{ color: getStatusColor(log.status) }"
                ></i>
              </div>
              <div class="node-line" v-if="index < logs.length - 1"></div>
            </div>

            <!-- 日志内容 -->
            <div class="timeline-content">
              <div class="log-header">
                <span class="log-step">{{ log.step }}</span>
                <div class="log-meta">
                  <span class="log-time">{{ formatTime(log.ts) }}</span>
                  <span class="log-cost" v-if="log.cost">{{ log.cost }}ms</span>
                </div>
              </div>
              
              <div class="log-tip" v-if="log.tip">
                {{ log.tip }}
              </div>

              <!-- 额外信息 -->
              <div class="log-details" v-if="log.details">
                <el-collapse>
                  <el-collapse-item title="查看详情" name="details">
                    <pre class="details-content">{{ log.details }}</pre>
                  </el-collapse-item>
                </el-collapse>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div class="empty-state" v-else-if="!loading">
        <div class="empty-icon">
          <i class="el-icon-connection"></i>
        </div>
        <div class="empty-text">
          <p class="empty-title">暂无测试记录</p>
          <p class="empty-desc">点击"重新测试"开始连接测试</p>
        </div>
      </div>
    </div>

    <!-- 抽屉底部 -->
    <div class="drawer-footer" v-if="logs.length > 0">
      <el-button @click="handleExportLogs" size="small" icon="el-icon-download">
        导出日志
      </el-button>
      <el-button @click="handleClearLogs" size="small" type="danger" plain>
        清空日志
      </el-button>
    </div>
  </el-drawer>
</template>

<script>
export default {
  name: 'XtTestConnectionDrawer',
  
  props: {
    // 是否显示抽屉
    visible: {
      type: Boolean,
      default: false
    },
    
    // 抽屉标题
    title: {
      type: String,
      default: '连接测试'
    },
    
    // 测试日志数据
    logs: {
      type: Array,
      default: () => []
      // 日志格式: { ts, step, status: 'ok'|'warn'|'fail', cost, tip, details }
    },
    
    // 加载状态
    loading: {
      type: Boolean,
      default: false
    }
  },

  computed: {
    drawerVisible: {
      get() {
        return this.visible
      },
      set(value) {
        if (!value) {
          this.handleClose()
        }
      }
    },

    // 成功数量
    successCount() {
      return this.logs.filter(log => log.status === 'ok').length
    },

    // 警告数量
    warningCount() {
      return this.logs.filter(log => log.status === 'warn').length
    },

    // 失败数量
    failCount() {
      return this.logs.filter(log => log.status === 'fail').length
    },

    // 总耗时
    totalCost() {
      return this.logs.reduce((total, log) => total + (log.cost || 0), 0)
    }
  },

  methods: {
    handleClose() {
      this.$emit('close')
    },

    handleRetest() {
      this.$emit('retest')
    },

    handleExportLogs() {
      const content = JSON.stringify(this.logs, null, 2)
      const blob = new Blob([content], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `test-logs-${Date.now()}.json`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
      
      this.$message.success('日志导出成功')
    },

    handleClearLogs() {
      this.$confirm('确定要清空所有测试日志吗？', '清空确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$emit('clear-logs')
        this.$message.success('日志已清空')
      }).catch(() => {
        // 用户取消
      })
    },

    // 获取状态图标
    getStatusIcon(status) {
      const iconMap = {
        ok: 'el-icon-circle-check',
        warn: 'el-icon-warning',
        fail: 'el-icon-circle-close'
      }
      return iconMap[status] || 'el-icon-info'
    },

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

    // 格式化时间
    formatTime(timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp)
      return date.toLocaleTimeString('zh-CN', { 
        hour12: false,
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.xt-test-connection-drawer {
  ::v-deep .el-drawer {
    background: var(--color-bg-card);
  }

  ::v-deep .el-drawer__header {
    background: var(--color-bg-card);
    border-bottom: 1px solid var(--color-border-primary);
    padding: var(--spacing-4) var(--spacing-6);
    margin-bottom: 0;

    .drawer-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;

      .header-title {
        display: flex;
        align-items: center;
        gap: var(--spacing-2);
        color: var(--color-text-primary);
        font-size: var(--font-size-lg);
        font-weight: var(--font-weight-semibold);

        .header-icon {
          color: var(--color-primary);
          font-size: var(--font-size-xl);
        }
      }

      .header-actions {
        .retest-btn {
          border-radius: var(--radius-lg);
          font-weight: var(--font-weight-medium);
          
          &:hover {
            transform: translateY(-1px);
            box-shadow: var(--shadow-md);
          }
        }
      }
    }
  }

  ::v-deep .el-drawer__body {
    background: var(--color-bg-card);
    padding: 0;
    display: flex;
    flex-direction: column;
    height: calc(100% - 73px);
  }

  .drawer-content {
    flex: 1;
    overflow-y: auto;
    padding: var(--spacing-6);

    .test-overview {
      background: var(--color-bg-secondary);
      border-radius: var(--radius-lg);
      padding: var(--spacing-4);
      margin-bottom: var(--spacing-6);

      .overview-stats {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: var(--spacing-4);

        .stat-item {
          text-align: center;
          padding: var(--spacing-3);
          background: var(--color-bg-card);
          border-radius: var(--radius-md);
          transition: all var(--duration-200) var(--ease-out);

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

          .stat-count {
            display: block;
            font-size: var(--font-size-xl);
            font-weight: var(--font-weight-bold);
            line-height: var(--line-height-tight);
            margin-bottom: var(--spacing-1);
          }

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

          &.success .stat-count {
            color: var(--color-success);
          }

          &.warning .stat-count {
            color: var(--color-warning);
          }

          &.error .stat-count {
            color: var(--color-danger);
          }

          &.total .stat-count {
            color: var(--color-primary);
          }
        }
      }
    }

    .timeline-container {
      .timeline {
        position: relative;

        .timeline-item {
          display: flex;
          margin-bottom: var(--spacing-6);
          position: relative;

          &.is-last {
            margin-bottom: 0;
          }

          .timeline-node {
            position: relative;
            margin-right: var(--spacing-4);
            display: flex;
            flex-direction: column;
            align-items: center;

            .node-icon {
              width: 32px;
              height: 32px;
              background: var(--color-bg-card);
              border: 2px solid var(--color-border-primary);
              border-radius: var(--radius-full);
              display: flex;
              align-items: center;
              justify-content: center;
              z-index: 1;
              transition: all var(--duration-200) var(--ease-out);

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

            .node-line {
              width: 2px;
              flex: 1;
              background: var(--color-border-secondary);
              margin-top: var(--spacing-2);
              min-height: 40px;
            }
          }

          .timeline-content {
            flex: 1;
            background: var(--color-bg-card);
            border: 1px solid var(--color-border-primary);
            border-radius: var(--radius-lg);
            padding: var(--spacing-4);
            transition: all var(--duration-200) var(--ease-out);

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

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

              .log-step {
                color: var(--color-text-primary);
                font-weight: var(--font-weight-medium);
                font-size: var(--font-size-base);
              }

              .log-meta {
                display: flex;
                align-items: center;
                gap: var(--spacing-3);
                font-size: var(--font-size-sm);
                color: var(--color-text-tertiary);

                .log-time {
                  font-family: var(--font-family-mono);
                }

                .log-cost {
                  background: var(--color-bg-tertiary);
                  padding: var(--spacing-1) var(--spacing-2);
                  border-radius: var(--radius-sm);
                  font-family: var(--font-family-mono);
                }
              }
            }

            .log-tip {
              color: var(--color-text-secondary);
              font-size: var(--font-size-sm);
              line-height: var(--line-height-relaxed);
              margin-bottom: var(--spacing-3);
            }

            .log-details {
              margin-top: var(--spacing-3);

              ::v-deep .el-collapse {
                border: none;

                .el-collapse-item__header {
                  background: var(--color-bg-tertiary);
                  border: none;
                  border-radius: var(--radius-md);
                  padding: var(--spacing-2) var(--spacing-3);
                  font-size: var(--font-size-sm);
                  color: var(--color-text-tertiary);
                }

                .el-collapse-item__content {
                  padding: var(--spacing-3) 0 0;

                  .details-content {
                    background: var(--color-bg-tertiary);
                    border-radius: var(--radius-md);
                    padding: var(--spacing-3);
                    font-family: var(--font-family-mono);
                    font-size: var(--font-size-sm);
                    color: var(--color-text-secondary);
                    white-space: pre-wrap;
                    word-break: break-all;
                    margin: 0;
                    max-height: 200px;
                    overflow-y: auto;
                  }
                }
              }
            }
          }

          // 状态相关样式
          &.status-ok {
            .timeline-node .node-icon {
              background: var(--color-success-50);
              border-color: var(--color-success);
            }
          }

          &.status-warn {
            .timeline-node .node-icon {
              background: var(--color-warning-50);
              border-color: var(--color-warning);
            }
          }

          &.status-fail {
            .timeline-node .node-icon {
              background: var(--color-danger-50);
              border-color: var(--color-danger);
            }
            
            .timeline-content {
              border-color: var(--color-danger);
              background: var(--color-danger-50);
            }
          }
        }
      }
    }

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

      .empty-icon {
        font-size: 64px;
        color: var(--color-text-quaternary);
        margin-bottom: var(--spacing-4);

        i {
          font-size: inherit;
        }
      }

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

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

  .drawer-footer {
    background: var(--color-bg-secondary);
    border-top: 1px solid var(--color-border-primary);
    padding: var(--spacing-4) var(--spacing-6);
    display: flex;
    justify-content: flex-end;
    gap: var(--spacing-3);

    .el-button {
      border-radius: var(--radius-lg);
      font-weight: var(--font-weight-medium);
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .xt-test-connection-drawer {
    ::v-deep .el-drawer {
      width: 100% !important;
    }

    .drawer-content {
      .test-overview {
        .overview-stats {
          grid-template-columns: repeat(2, 1fr);
        }
      }

      .timeline-container {
        .timeline {
          .timeline-item {
            .timeline-content {
              .log-header {
                flex-direction: column;
                align-items: flex-start;
                gap: var(--spacing-2);
              }
            }
          }
        }
      }
    }
  }
}
</style>
