<template>
  <div class="app-container">
    <div class="panel-container">
      <!-- 左侧：用户总览 -->
      <div class="left-panel" :class="{ 'collapsed': isLeftPanelCollapsed }">
        <el-card shadow="never" class="user-overview-card">
          <template #header>
            <div class="card-header">
              <span>用户Token使用总览</span>
            </div>
          </template>

          <div v-show="!isLeftPanelCollapsed">
            <!-- 搜索区域 -->
            <el-form :model="userQueryParams" ref="userQueryFormRef" :inline="true" label-width="80px">
              <el-form-item label="用户姓名" prop="userName">
                <el-input
                  v-model="userQueryParams.userName"
                  placeholder="请输入用户姓名进行模糊搜索"
                  clearable
                  style="width: 200px"
                  @keyup.enter="handleUserQuery"
                />
              </el-form-item>
              <el-form-item label="AI模型" prop="aiModel">
                <el-select v-model="userQueryParams.aiModel" placeholder="请选择AI模型" clearable style="width: 200px">
                  <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-option label="通义千问" value="qwen" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleUserQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetUserQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <!-- 用户列表 -->
            <el-table
              v-loading="userLoading"
              :data="userPaginatedList"
              @row-click="handleUserSelect"
              highlight-current-row
              :row-class-name="getUserRowClass"
            >
              <el-table-column label="用户姓名" align="center" prop="userName" />
              <el-table-column label="AI模型" align="center" prop="aiModel" />
              <el-table-column label="提问Token" align="center" prop="promptTokens">
                <template #default="scope">
                  <span class="token-count">{{ scope.row.promptTokens.toLocaleString() }}</span>
                </template>
              </el-table-column>
              <el-table-column label="回答Token" align="center" prop="completionTokens">
                <template #default="scope">
                  <span class="token-count">{{ scope.row.completionTokens.toLocaleString() }}</span>
                </template>
              </el-table-column>
              <el-table-column label="总Token" align="center" prop="totalTokens">
                <template #default="scope">
                  <span class="token-count total">{{ scope.row.totalTokens.toLocaleString() }}</span>
                </template>
              </el-table-column>
            </el-table>

            <!-- 用户分页 -->
            <el-pagination
              v-show="userTotal > 0"
              class="mt-4"
              :total="userTotal"
              v-model:current-page="userQueryParams.pageNum"
              v-model:page-size="userQueryParams.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleUserQuery"
              @current-change="handleUserQuery"
            />
          </div>
        </el-card>
      </div>

      <!-- 收缩/展开按钮 -->
      <div class="toggle-button" @click="toggleLeftPanel">
        <el-button
          type="text"
          :icon="isLeftPanelCollapsed ? 'ArrowRight' : 'ArrowLeft'"
          class="toggle-btn"
        />
      </div>

      <!-- 右侧：详情记录 -->
      <div class="right-panel">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span>Token使用详情记录</span>
              <span v-if="selectedUser" class="selected-user">当前用户：{{ selectedUser.userName }}</span>
            </div>
          </template>

          <!-- 搜索区域 -->
          <el-form :model="detailQueryParams" ref="detailQueryFormRef" :inline="true" label-width="80px">
            <el-form-item label="使用类型" prop="usageType">
              <el-select v-model="detailQueryParams.usageType" placeholder="请选择使用类型" clearable style="width: 200px">
                <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>
              <el-button type="primary" icon="Search" @click="handleDetailQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetDetailQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <!-- 详情列表 -->
          <el-table v-loading="detailLoading" :data="detailPaginatedList">
            <el-table-column label="用户姓名" align="center" prop="userName" />
            <el-table-column label="使用类型" align="center" prop="usageType">
              <template #default="scope">
                <el-tag :type="getUsageTypeTagType(scope.row.usageType)">
                  {{ getUsageTypeLabel(scope.row.usageType) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="AI模型" align="center" prop="aiModel" />
            <el-table-column label="会话名称" align="center" prop="sessionName" :show-overflow-tooltip="true" />
            <el-table-column label="提问Token" align="center" prop="promptTokens">
              <template #default="scope">
                <span class="token-count">{{ scope.row.promptTokens.toLocaleString() }}</span>
              </template>
            </el-table-column>
            <el-table-column label="回答Token" align="center" prop="completionTokens">
              <template #default="scope">
                <span class="token-count">{{ scope.row.completionTokens.toLocaleString() }}</span>
              </template>
            </el-table-column>
            <el-table-column label="总Token" align="center" prop="totalTokens">
              <template #default="scope">
                <span class="token-count total">{{ scope.row.totalTokens.toLocaleString() }}</span>
              </template>
            </el-table-column>
          </el-table>

          <!-- 详情分页 -->
          <el-pagination
            v-show="detailTotal > 0"
            class="mt-4"
            :total="detailTotal"
            v-model:current-page="detailQueryParams.pageNum"
            v-model:page-size="detailQueryParams.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleDetailQuery"
            @current-change="handleDetailQuery"
          />
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup name="TokenUsageDetails">
import { ref, reactive, onMounted, computed } from 'vue';

// ================= MOCK DATA =================
// 模拟用户总览数据
const mockUserList = [
  {
    id: 1,
    userName: '张三',
    aiModel: 'gpt-3.5',
    promptTokens: 15420,
    completionTokens: 8920,
    totalTokens: 24340
  },
  {
    id: 2,
    userName: '李四',
    aiModel: 'gpt-4',
    promptTokens: 23450,
    completionTokens: 15680,
    totalTokens: 39130
  },
  {
    id: 3,
    userName: '王五',
    aiModel: 'claude-3',
    promptTokens: 9870,
    completionTokens: 6540,
    totalTokens: 16410
  },
  {
    id: 4,
    userName: '赵六',
    aiModel: 'deepseek',
    promptTokens: 12340,
    completionTokens: 7890,
    totalTokens: 20230
  },
  {
    id: 5,
    userName: '钱七',
    aiModel: 'qwen',
    promptTokens: 8760,
    completionTokens: 5430,
    totalTokens: 14190
  },
  {
    id: 6,
    userName: '孙八',
    aiModel: 'gpt-3.5',
    promptTokens: 11230,
    completionTokens: 6780,
    totalTokens: 18010
  },
];

// 模拟详情记录数据
const mockDetailList = [
  {
    id: 1,
    userId: 1,
    userName: '张三',
    usageType: 'ai_chat',
    aiModel: 'gpt-3.5',
    sessionName: '关于Vue3开发的讨论',
    promptTokens: 1200,
    completionTokens: 800,
    totalTokens: 2000,
    createTime: '2024-01-15 10:30:00'
  },
  {
    id: 2,
    userId: 1,
    userName: '张三',
    usageType: 'ai_knowledge',
    aiModel: 'gpt-3.5',
    sessionName: '知识库查询-产品文档',
    promptTokens: 800,
    completionTokens: 600,
    totalTokens: 1400,
    createTime: '2024-01-15 14:20:00'
  },
  {
    id: 3,
    userId: 2,
    userName: '李四',
    usageType: 'ai_sql',
    aiModel: 'gpt-4',
    sessionName: 'SQL生成-用户统计',
    promptTokens: 1500,
    completionTokens: 1200,
    totalTokens: 2700,
    createTime: '2024-01-15 09:15:00'
  },
  {
    id: 4,
    userId: 2,
    userName: '李四',
    usageType: 'ai_form',
    aiModel: 'gpt-4',
    sessionName: '智能填报-订单信息',
    promptTokens: 2000,
    completionTokens: 1500,
    totalTokens: 3500,
    createTime: '2024-01-15 16:45:00'
  },
  {
    id: 5,
    userId: 3,
    userName: '王五',
    usageType: 'ai_chat',
    aiModel: 'claude-3',
    sessionName: '技术问题咨询',
    promptTokens: 900,
    completionTokens: 700,
    totalTokens: 1600,
    createTime: '2024-01-15 11:30:00'
  },
  {
    id: 6,
    userId: 4,
    userName: '赵六',
    usageType: 'ai_knowledge',
    aiModel: 'deepseek',
    sessionName: '知识库查询-技术文档',
    promptTokens: 1100,
    completionTokens: 900,
    totalTokens: 2000,
    createTime: '2024-01-15 13:20:00'
  },
  {
    id: 7,
    userId: 5,
    userName: '钱七',
    usageType: 'ai_sql',
    aiModel: 'qwen',
    sessionName: 'SQL生成-销售报表',
    promptTokens: 1300,
    completionTokens: 1000,
    totalTokens: 2300,
    createTime: '2024-01-15 15:10:00'
  },
  {
    id: 8,
    userId: 6,
    userName: '孙八',
    usageType: 'ai_form',
    aiModel: 'gpt-3.5',
    sessionName: '智能填报-客户信息',
    promptTokens: 1800,
    completionTokens: 1200,
    totalTokens: 3000,
    createTime: '2024-01-15 17:30:00'
  },
];

/**
 * 模拟API调用
 * @param {*} data
 * @param {number} delay
 */
const mockApiCall = (data, delay = 300) => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(data);
    }, delay);
  });
};
// ================= MOCK DATA END =================

// ================= 面板控制逻辑 =================
const isLeftPanelCollapsed = ref(false);

// 切换左侧面板收缩状态
const toggleLeftPanel = () => {
  isLeftPanelCollapsed.value = !isLeftPanelCollapsed.value;
};
// ================= 面板控制逻辑 END =================

// ================= 工具函数 =================
/**
 * 获取使用类型标签
 * @param {string} usageType
 */
const getUsageTypeLabel = (usageType) => {
  const typeMap = {
    'ai_chat': 'AI问答',
    'ai_knowledge': 'AI知识库',
    'ai_sql': 'AI生成SQL',
    'ai_form': 'AI智能填报'
  };
  return typeMap[usageType] || usageType;
};

/**
 * 获取使用类型标签颜色
 * @param {string} usageType
 */
const getUsageTypeTagType = (usageType) => {
  const typeMap = {
    'ai_chat': 'primary',
    'ai_knowledge': 'success',
    'ai_sql': 'warning',
    'ai_form': 'info'
  };
  return typeMap[usageType] || '';
};

/**
 * 获取用户行样式类名
 * @param {object} param0
 */
const getUserRowClass = ({ row }) => {
  return selectedUser.value && row.id === selectedUser.value.id ? 'selected-row' : '';
};
// ================= 工具函数 END =================

// ================= 左侧用户总览逻辑 =================
const userLoading = ref(false);
const userList = ref([]);
const userTotal = ref(0);
const userQueryFormRef = ref();
const userQueryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  userName: '',
  aiModel: '',
});

// 计算属性：用户列表过滤和分页
const userFilteredList = computed(() => {
  let list = userList.value;
  if (userQueryParams.userName) {
    list = list.filter(item => item.userName.includes(userQueryParams.userName));
  }
  if (userQueryParams.aiModel) {
    list = list.filter(item => item.aiModel === userQueryParams.aiModel);
  }
  return list;
});

const userPaginatedList = computed(() => {
  userTotal.value = userFilteredList.value.length;
  const start = (userQueryParams.pageNum - 1) * userQueryParams.pageSize;
  const end = start + userQueryParams.pageSize;
  return userFilteredList.value.slice(start, end);
});

// 获取用户列表数据
const getUserList = async () => {
  userLoading.value = true;
  const res = await mockApiCall(mockUserList);
  userList.value = res;
  handleUserQuery();
  userLoading.value = false;
};

// 用户搜索按钮操作
const handleUserQuery = () => {
  userQueryParams.pageNum = 1;
};

// 用户重置按钮操作
const resetUserQuery = () => {
  userQueryFormRef.value.resetFields();
  handleUserQuery();
};
// ================= 左侧用户总览逻辑 END =================

// ================= 右侧详情记录逻辑 =================
const detailLoading = ref(false);
const detailList = ref([]);
const detailTotal = ref(0);
const detailQueryFormRef = ref();
const detailQueryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  usageType: '',
  userId: null, // 当前选中的用户ID
});

const selectedUser = ref(null); // 当前选中的用户

// 计算属性：详情列表过滤和分页
const detailFilteredList = computed(() => {
  let list = detailList.value;

  // 根据选中的用户过滤
  if (detailQueryParams.userId) {
    list = list.filter(item => item.userId === detailQueryParams.userId);
  }

  // 根据使用类型过滤
  if (detailQueryParams.usageType) {
    list = list.filter(item => item.usageType === detailQueryParams.usageType);
  }

  return list;
});

const detailPaginatedList = computed(() => {
  detailTotal.value = detailFilteredList.value.length;
  const start = (detailQueryParams.pageNum - 1) * detailQueryParams.pageSize;
  const end = start + detailQueryParams.pageSize;
  return detailFilteredList.value.slice(start, end);
});

// 获取详情列表数据
const getDetailList = async () => {
  detailLoading.value = true;
  const res = await mockApiCall(mockDetailList);
  detailList.value = res;
  handleDetailQuery();
  detailLoading.value = false;
};

// 详情搜索按钮操作
const handleDetailQuery = () => {
  detailQueryParams.pageNum = 1;
};

// 详情重置按钮操作
const resetDetailQuery = () => {
  detailQueryFormRef.value.resetFields();
  detailQueryParams.userId = selectedUser.value ? selectedUser.value.id : null;
  handleDetailQuery();
};

// 用户选择操作
const handleUserSelect = (row) => {
  selectedUser.value = row;
  detailQueryParams.userId = row.id;
  handleDetailQuery();
};
// ================= 右侧详情记录逻辑 END =================

// ================= 生命周期 =================
onMounted(() => {
  getUserList();
  getDetailList();
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.collapse-btn {
  font-size: 12px;
}

.panel-container {
  display: flex;
  height: 100vh;
  position: relative;
  overflow: hidden;
}

.left-panel {
  width: 40%;
  height: 100%;
  transition: width 0.3s ease;
  flex-shrink: 0;
  overflow: hidden;
}

.left-panel.collapsed {
  width: 0;
  overflow: hidden;
  flex-shrink: 0;
}

.right-panel {
  flex: 1;
  height: 100%;
  transition: width 0.3s ease;
  overflow: hidden;
}

.toggle-button {
  position: absolute;
  left: 40%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 10;
  background: white;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: left 0.3s ease;
}

.left-panel.collapsed ~ .toggle-button {
  left: 0;
}

.left-panel:not(.collapsed) ~ .toggle-button {
  left: 40%;
}

.toggle-btn {
  padding: 8px;
  font-size: 14px;
}

.user-overview-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.user-overview-card .el-card__body {
  flex: 1;
  overflow: auto;
}

.right-panel .el-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.right-panel .el-card__body {
  flex: 1;
  overflow: auto;
}

.selected-user {
  font-size: 14px;
  color: #409eff;
  font-weight: 500;
}

.token-count {
  font-family: 'Courier New', monospace;
  font-weight: 500;
}

.token-count.total {
  color: #e6a23c;
  font-weight: 600;
}

:deep(.selected-row) {
  background-color: #f0f9ff !important;
}

:deep(.selected-row td) {
  background-color: #f0f9ff !important;
}

.mt-4 {
  margin-top: 1.25rem;
}
</style>
