<template>
  <div class="chat-record-viewer">
    <div v-if="chatData && parsedMessages.length > 0" class="chat-messages">
      <div
        v-for="(message, index) in displayedMessages"
        :key="index"
        :class="['message', message.role]"
      >
        <div class="message-content">
          <div
            :class="{ 'content-collapsed': shouldCollapse(index) && !expandedMessages[index] }"
            :style="{ maxHeight: shouldCollapse(index) && !expandedMessages[index] ? '130px' : 'none' }"
          >
            <pre>{{ formatMessageContent(message.content) }}</pre>
          </div>

          <!-- 将展开按钮移到消息项内部 -->
          <div v-if="shouldCollapse(index)" class="expand-toggle">
            <el-button
              type="text"
              size="mini"
              @click="toggleMessageExpand(index)"
              class="expand-btn"
            >
              {{ expandedMessages[index] ? '收起' : '展开' }}
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 正确的无数据提示 -->
    <div v-if="!chatData || parsedMessages.length === 0" class="no-chat-data">
      <i class="el-icon-chat-line-round"></i>
      <p>暂无聊天记录</p>
    </div>

    <!-- 加载更多按钮应该独立于消息容器 -->
    <div v-if="hasMoreMessages" class="load-more">
      <el-button
        type="text"
        @click="loadMore"
        :loading="loadingMore"
      >
        加载更多消息 ({{ remainingCount }} 条)
      </el-button>
    </div>
  </div>
</template>


<script>
export default {
  name: "ChatRecordViewer",
  props: {
    chatData: {
      type: [String, Object],
      default: null
    },
    initialDisplayCount: {
      type: Number,
      default: 7
    },
    agentName: {
      type: String,
      default: '客服'
    },
    customerName: {
      type: String,
      default: '客户'
    }
  },
  data() {
    return {
      displayCount: this.initialDisplayCount,
      loadingMore: false,
      expandedMessages: {}
    };
  },
  computed: {
    parsedMessages() {
      if (!this.chatData) return [];

      try {
        // 如果是字符串，尝试解析为JSON
        const data = typeof this.chatData === 'string'
          ? JSON.parse(this.chatData)
          : this.chatData;

        // 根据不同的数据结构进行处理
        if (Array.isArray(data)) {
          return data.map(msg => ({
            role: msg.role || 'user',
            content: msg.content || msg.text || '',
            time: msg.time || msg.timestamp || Date.now()
          }));
        } else if (typeof data === 'object') {
          // 如果是对象，转换为数组
          return Object.entries(data).map(([key, value]) => ({
            role: key.includes('user') ? 'user' : 'assistant',
            content: value,
            time: Date.now()
          }));
        }

        return [];
      } catch (error) {
        // 如果不是JSON，按纯文本处理
        return [{
          role: 'system',
          content: this.chatData,
          time: Date.now()
        }];
      }
    },

    displayedMessages() {
      return this.parsedMessages.slice(-this.displayCount);
    },

    hasMoreMessages() {
      return this.displayCount < this.parsedMessages.length;
    },

    remainingCount() {
      return this.parsedMessages.length - this.displayCount;
    }
  },
  methods: {
    formatTime(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      return date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      });
    },

    formatMessageContent(content) {
      if (!content) return '';

      // 替换[客服]为实际的客服名称
      let formattedContent = content.replace(/\[客服\]/g, this.agentName || '客服');

      // 替换[客户]为实际的客户名称
      formattedContent = formattedContent.replace(/\[客户\]/g, this.customerName || '客户');

      return formattedContent;
    },

    shouldCollapse(index) {
      // 检查消息内容是否超过8行（默认显示8行）
      const message = this.displayedMessages[index];
      if (!message || !message.content) return false;

      // 计算行数（简单估算）
      const lines = message.content.split('\n').length;
      const wordsPerLine = 50; // 假设每行约50个字符
      const estimatedLines = Math.ceil(message.content.length / wordsPerLine);

      return estimatedLines > 8 || lines > 8;
    },

    toggleMessageExpand(index) {
      this.$set(this.expandedMessages, index, !this.expandedMessages[index]);
    },

    loadMore() {
      this.loadingMore = true;
      setTimeout(() => {
        this.displayCount = Math.min(
          this.displayCount + this.initialDisplayCount,
          this.parsedMessages.length
        );
        this.loadingMore = false;
      }, 300);
    }
  }
};
</script>

<style scoped>
.chat-record-viewer {
  max-height: 380px;
  overflow-y: auto;
  overflow-x: hidden; /* 移除水平滚动条 */
  width: 100%;
  padding: 8px 4px; /* 压缩内边距 */
  box-sizing: border-box;
}

.chat-messages {
  padding: 8px; /* 压缩内边距 */
}

.message {
  margin-bottom: 16px;
  padding: 18px 20px;
  border-radius: 14px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  border: 1px solid transparent;
  position: relative;
  overflow: hidden;
  max-width: 100%;
  overflow-wrap: break-word;
  word-wrap: break-word;
  line-height: 1.7;
  background: white;
  border: 1px solid #e0e0e0;
}

.message:hover {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  transform: translateY(-3px);
  border-color: #d0d0d0;
}

.message.user {
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
  border: 1px solid #2196f3;
}

.message.assistant {
  background: linear-gradient(135deg, #f1f8e9 0%, #dcedc8 100%);
  border: 1px solid #4caf50;
}

.message.system {
  background: linear-gradient(135deg, #f5f5f5 0%, #eeeeee 100%);
  border: 1px solid #9e9e9e;
}

.message-content {
  position: relative;
  white-space: pre-wrap;
  word-break: break-word;
  word-wrap: break-word;
  overflow-wrap: break-word;
  max-width: 100%;
}

.message-content pre {
  margin: 0;
  font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
  line-height: 1.7;
  color: #2c3e50;
  white-space: pre-wrap;
  word-break: break-word;
  word-wrap: break-word;
  overflow-wrap: break-word;
  font-size: 15px;
  font-weight: 500;
  letter-spacing: 0.3px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  background: linear-gradient(135deg, #ffffff 0%, #f9f9f9 100%);
  border-radius: 10px;
  padding: 16px 20px;
  box-shadow: 0 3px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid #e0e0e0;
  transition: all 0.3s ease;
  border-left: 3px solid #667eea;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.message-content pre:hover {
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
  transform: translateY(-1px);
}

.content-collapsed {
  overflow: hidden;
  position: relative;
  transition: all 0.3s ease;
}

.content-collapsed pre {
  margin: 0;
  white-space: pre-wrap;
  word-break: break-word;
  font-family: inherit;
  line-height: 1.6;
  color: #303133;
}

.expand-toggle {
  text-align: center;
  padding: 10px 0;
  margin-top: 8px;
  position: relative;
  z-index: 2;
  border-radius: 8px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border: 1px solid #e1e8ef;
}

.expand-toggle .expand-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px;
  padding: 8px 18px;
  font-size: 14px;
  font-weight: 600;
  min-height: 32px;
  box-shadow: 0 3px 10px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.expand-toggle .expand-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 14px rgba(102, 126, 234, 0.4);
}

.expand-btn {
  background: #409EFF;
  color: white;
  border-radius: 10px; /* 减小圆角 */
  padding: 3px 10px; /* 压缩内边距 */
  font-size: 11px; /* 减小字体 */
  min-height: 24px;
}

.expand-btn:hover {
  background: #66b1ff;
}

.load-more {
  text-align: center;
  padding: 16px;
  border-top: 1px solid #ebeef5;
  background: linear-gradient(to bottom, rgba(248,250,252,0.9), rgba(248,250,252,1));
  position: sticky;
  bottom: 0;
  z-index: 10;
  margin-top: 12px;
  border-radius: 8px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.load-more .el-button {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px;
  padding: 10px 20px;
  font-size: 14px;
  font-weight: 600;
  min-height: 36px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.load-more .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(102, 126, 234, 0.4);
}

.load-more .el-button:active {
  transform: translateY(0);
}

.no-chat-data {
  text-align: center;
  padding: 60px 20px;
  color: #909399;
}

.no-chat-data i {
  font-size: 48px;
  margin-bottom: 16px;
  display: block;
}

.no-chat-data p {
  margin: 0;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-record-viewer {
    max-height: 300px;
  }

  .message {
    padding: 8px;
  }

  .expand-btn {
    padding: 2px 8px;
    font-size: 11px;
  }
}
</style>
