<template>
  <div class="user-session-container">
    <!-- 左侧会话列表 -->
    <div class="session-list-panel" :style="{ flexBasis: leftPanelWidth + 'px' }">
      <el-card shadow="never" class="session-list-card">
        <el-form :model="queryParams" :inline="true" class="mb-2">
          <el-form-item label="用户姓名">
            <el-input v-model="queryParams.userName" placeholder="模糊搜索" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="使用类型">
            <el-select v-model="queryParams.usageType" placeholder="全部" clearable>
              <el-option label="AI问答" value="ai_chat" />
              <el-option label="AI知识库" value="ai_knowledge" />
              <el-option label="AI生成SQL" value="ai_sql" />
              <el-option label="AI智能填报" value="ai_form" />
            </el-select>
          </el-form-item>
          <el-form-item label="AI模型">
            <el-select v-model="queryParams.aiModel" placeholder="全部" clearable>
              <el-option label="GPT-3.5" value="gpt-3.5" />
              <el-option label="GPT-4" value="gpt-4" />
              <el-option label="Claude-3" value="claude-3" />
              <el-option label="DeepSeek" value="deepseek" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-table
          :data="paginatedList"
          highlight-current-row
          @row-click="handleSelect"
          :row-class-name="rowClass"
          style="height: 60vh"
        >
          <el-table-column label="用户姓名" prop="userName" />
          <el-table-column label="使用类型" prop="usageType">
            <template #default="scope">
              {{ usageTypeLabel(scope.row.usageType) }}
            </template>
          </el-table-column>
          <el-table-column label="AI模型" prop="aiModel" />
          <el-table-column label="知识库" prop="knowledgeBase" />
          <el-table-column label="会话名称" prop="sessionName" />
        </el-table>
        <el-pagination
          class="mt-2"
          :total="total"
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleQuery"
          @current-change="handleQuery"
        />
      </el-card>
    </div>
    <!-- 拖拽分割条（flex子项） -->
    <div class="drag-bar" @mousedown="startDrag"></div>
    <!-- 右侧会话详情 -->
    <div class="session-detail-panel">
      <el-card shadow="never" class="session-detail-card">
        <template #header>
          <div class="detail-header">
            <span v-if="selectedSession">会话详情：{{ selectedSession.sessionName }}</span>
            <span v-else>请选择左侧会话</span>
            <div v-if="selectedSession" class="detail-meta">
              <span>用户：{{ selectedSession.userName }}</span>
              <span>｜类型：{{ usageTypeLabel(selectedSession.usageType) }}</span>
              <span>｜AI模型：{{ selectedSession.aiModel }}</span>
            </div>
          </div>
        </template>
        <div v-if="selectedSession">
          <div class="chat-list">
            <div
              v-for="(msg, idx) in sessionDetail"
              :key="idx"
              :class="['chat-item', msg.role === 'user' ? 'chat-user' : 'chat-ai']"
            >
              <div class="chat-bubble">
                <span v-if="msg.role === 'user'">👤</span>
                <span v-else>🤖</span>
                <span class="chat-content">{{ msg.content }}</span>
              </div>
            </div>
          </div>
        </div>
        <div v-else class="empty-detail">暂无会话详情</div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue'

// mock 数据
const mockSessionList = [
  {
    id: 1,
    userName: '张三',
    usageType: 'ai_chat',
    aiModel: 'gpt-3.5',
    sessionName: '关于Vue3开发的讨论',
    knowledgeBase: '产品知识库'
  },
  {
    id: 2,
    userName: '李四',
    usageType: 'ai_knowledge',
    aiModel: 'gpt-4',
    sessionName: '知识库查询-产品文档',
    knowledgeBase: '技术文档库'
  },
  {
    id: 3,
    userName: '王五',
    usageType: 'ai_sql',
    aiModel: 'claude-3',
    sessionName: 'SQL生成-用户统计',
    knowledgeBase: 'SQL知识库'
  },
  {
    id: 4,
    userName: '张三',
    usageType: 'ai_form',
    aiModel: 'gpt-3.5',
    sessionName: '智能填报-客户信息',
    knowledgeBase: ''
  }
]

const mockSessionDetails = {
  1: [
    { role: 'user', content: 'Vue3和Vue2有什么区别？' },
    { role: 'ai', content: 'Vue3在响应式、性能、TypeScript支持等方面有较大提升。' },
    { role: 'user', content: '能举个例子吗？' },
    { role: 'ai', content: '比如ref和reactive的用法，组合式API等。' }
  ],
  2: [
    { role: 'user', content: '请查找产品文档相关知识。' },
    { role: 'ai', content: '已为您找到产品文档相关内容，请查收。' }
  ],
  3: [
    { role: 'user', content: '帮我生成一个用户统计的SQL。' },
    { role: 'ai', content: 'SELECT COUNT(*) FROM users;' }
  ],
  4: [
    { role: 'user', content: '我要填报客户信息。' },
    { role: 'ai', content: '请提供客户名称、联系方式等信息。' }
  ]
}

// 工具
const usageTypeLabel = (type) => {
  const map = {
    ai_chat: 'AI问答',
    ai_knowledge: 'AI知识库',
    ai_sql: 'AI生成SQL',
    ai_form: 'AI智能填报'
  }
  return map[type] || type
}

// 查询与分页
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  userName: '',
  usageType: '',
  aiModel: ''
})
const total = ref(0)
const sessionList = ref([])
const selectedSession = ref(null)
const sessionDetail = ref([])

// 拖拽宽度
const minLeft = 240
const maxLeft = 600
const leftPanelWidth = ref(Math.floor(window.innerWidth * 0.3)) // 3:7 初始

let dragging = false
let startX = 0
let startWidth = 0

function startDrag(e) {
  dragging = true
  startX = e.clientX
  startWidth = leftPanelWidth.value
  document.body.style.cursor = 'col-resize'
  document.addEventListener('mousemove', onDrag)
  document.addEventListener('mouseup', stopDrag)
}
function onDrag(e) {
  if (!dragging) return
  let newWidth = startWidth + (e.clientX - startX)
//   if (newWidth < minLeft) newWidth = minLeft
//   if (newWidth > maxLeft) newWidth = maxLeft
  leftPanelWidth.value = newWidth
}
function stopDrag() {
  dragging = false
  document.body.style.cursor = ''
  document.removeEventListener('mousemove', onDrag)
  document.removeEventListener('mouseup', stopDrag)
}
onBeforeUnmount(() => {
  stopDrag()
})

const filteredList = computed(() => {
  let list = mockSessionList
  if (queryParams.userName) {
    list = list.filter(item => item.userName.includes(queryParams.userName))
  }
  if (queryParams.usageType) {
    list = list.filter(item => item.usageType === queryParams.usageType)
  }
  if (queryParams.aiModel) {
    list = list.filter(item => item.aiModel === queryParams.aiModel)
  }
  return list
})

const paginatedList = computed(() => {
  total.value = filteredList.value.length
  const start = (queryParams.pageNum - 1) * queryParams.pageSize
  return filteredList.value.slice(start, start + queryParams.pageSize)
})

function handleQuery() {
  queryParams.pageNum = 1
}

function resetQuery() {
  queryParams.userName = ''
  queryParams.usageType = ''
  queryParams.aiModel = ''
  handleQuery()
}

function handleSelect(row) {
  selectedSession.value = row
  sessionDetail.value = mockSessionDetails[row.id] || []
}

function rowClass({ row }) {
  return selectedSession.value && row.id === selectedSession.value.id ? 'selected-row' : ''
}

onMounted(() => {
  sessionList.value = mockSessionList
})
</script>

<style scoped>
.user-session-container {
  display: flex;
  height: 100vh;
  background: #f5f7fa;
  position: relative;
  overflow: hidden;
  min-width: 0;
}
.session-list-panel {
  min-width: 120px;
  max-width: 90%;
  height: 100%;
  background: #fff;
  border-right: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
  transition: flex-basis 0.2s;
  z-index: 1;
  flex-shrink: 0;
  flex-grow: 0;
  min-width: 0;
}
.drag-bar {
  width: 6px;
  background: #d3e2f7;
  cursor: col-resize;
  height: 100%;
  z-index: 10;
  transition: background 0.2s;
  flex-shrink: 0;
}
.drag-bar:hover {
  background: #409eff;
}
.session-detail-panel {
  flex: 1 1 0;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
  min-width: 0 !important;
}
.session-list-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  min-width: 0;
}
.session-detail-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  min-width: 0;
}
.session-detail-card :deep(.el-card__body) {
  min-width: 0 !important;
}
.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.detail-meta {
  font-size: 14px;
  color: #888;
  font-weight: 400;
  display: flex;
  gap: 16px;
}
.chat-list {
  padding: 24px 0 0 0;
  display: flex;
  flex-direction: column;
  gap: 16px;
  height: 100%;
  overflow-y: auto;
  min-width: 0;
}
.chat-item {
  display: flex;
  align-items: flex-start;
}
.chat-user {
  justify-content: flex-start;
}
.chat-ai {
  justify-content: flex-end;
}
.chat-bubble {
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 8px;
  padding: 8px 16px;
  box-shadow: 0 2px 8px #f0f1f2;
  max-width: 70%;
  word-break: break-all;
}
.chat-user .chat-bubble {
  background: #e6f7ff;
}
.chat-ai .chat-bubble {
  background: #f4f4f5;
}
.chat-content {
  margin-left: 8px;
}
.selected-row {
  background: #f0f9ff !important;
}
.empty-detail {
  color: #bbb;
  text-align: center;
  margin-top: 40px;
}
.mb-2 {
  margin-bottom: 12px;
}
.mt-2 {
  margin-top: 12px;
}
</style>
