<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="queryParams" ref="queryFormRef" :inline="true" label-width="80px">
              <el-form-item label="用户昵称" prop="nickName">
                <el-input
                  v-model="queryParams.nickName"
                  placeholder="请输入用户昵称"
                  clearable
                  style="width: 200px"
                  @keyup.enter="getList"
                />
              </el-form-item>
              <el-form-item label="AI模型" prop="modelId">
                <el-select v-model="queryParams.modelId" placeholder="请选择AI模型" clearable>
                  <el-option
                    v-for="dict in aiModelList"
                    :key="dict.modelId"
                    :label="dict.modelName"
                    :value="dict.modelId"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="getList">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <!-- 用户列表 -->
            <el-table
              v-loading="loading"
              :data="tokenUsageList"
              @row-click="handleUserSelect"
              highlight-current-row
            >
              <el-table-column label="用户" align="center" prop="nickName" v-if="columns[2].visible"/>
              <el-table-column label="AI模型" align="center" prop="modelName" v-if="columns[4].visible"/>
              <el-table-column label="提问Token" align="center" prop="promptToken" v-if="columns[5].visible"/>
              <el-table-column label="回复Token" align="center" prop="completionToken" v-if="columns[6].visible"/>
              <el-table-column label="总Token" align="center" prop="totalToken" v-if="columns[7].visible"/>
            </el-table>

            <!-- 用户分页 -->
            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                        v-model:limit="queryParams.pageSize" @pagination="getList"/>
          </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.nickName
                }}，当前模型：{{ selectedUser.modelName }}</span>
            </div>
          </template>

          <!-- 搜索区域 -->
          <el-form :model="detailQueryParams" ref="detailQueryFormRef" :inline="true" label-width="80px">
            <el-form-item label="使用类型" prop="messageDetailType">
              <el-select v-model='detailQueryParams.messageDetailType' placeholder='请选择使用类型' clearable>
                <el-option v-for='dict in ai_chat_message_detail_type' :key='dict.value' :label='dict.label' :value='dict.value'/>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="getDetailList">搜索</el-button>
              <el-button icon="Refresh" @click="resetDetailQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <!-- 详情列表 -->
          <el-table v-loading="detailLoading" :data="detailList">
            <el-table-column label="用户姓名" align="center" prop="nickName"/>
            <el-table-column label="使用类型" align="center" prop="messageDetailType">
              <template #default="scope">
                <dict-tag :options='ai_chat_message_detail_type' :value='scope.row.messageDetailType'/>
              </template>
            </el-table-column>
            <el-table-column label="AI模型" align="center" prop="modelName"/>
            <el-table-column label="提问内容" align="center" prop="questionContent" :show-overflow-tooltip="true"/>
            <el-table-column label="回复内容" align="center" prop="answerContent" :show-overflow-tooltip="true"/>
            <el-table-column label="提问Token" align="center" prop="promptToken">
              <template #default="scope">
                <span class="token-count">{{ scope.row.promptToken?.toLocaleString() }}</span>
              </template>
            </el-table-column>
            <el-table-column label="回答Token" align="center" prop="completionToken">
              <template #default="scope">
                <span class="token-count">{{ scope.row.completionToken?.toLocaleString() }}</span>
              </template>
            </el-table-column>
            <el-table-column label="总Token" align="center" prop="totalToken">
              <template #default="scope">
                <span class="token-count total">{{ scope.row.totalToken?.toLocaleString() }}</span>
              </template>
            </el-table-column>
          </el-table>

          <!-- 详情分页 -->
          <pagination v-show="detailTotal > 0" :total="detailTotal" v-model:page="detailQueryParams.pageNum"
                      v-model:limit="detailQueryParams.pageSize" @pagination="getDetailList"/>

        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup name="TokenUsage" lang="ts">
import {ref, reactive, onMounted, computed} from 'vue';
import {listTokenUsage, getAiChatMessageDetailList, getTokenUsage} from '@/api/ai/record/tokenUsage';
import {TokenUsageVO, TokenUsageQuery, TokenUsageForm} from '@/api/ai/record/tokenUsage/types';
import {getAiModelList} from '@/api/ai/base/aiModel';
import {AiModelVO} from '@/api/ai/base/aiModel/types';


const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const {ai_chat_message_detail_type} = toRefs<any>(proxy?.useDict('ai_chat_message_detail_type'));

const selectedUser = ref(null); // 当前选中的用户
const tokenUsageList = ref<TokenUsageVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const tokenUsageFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 列显隐信息
const columns = ref<FieldOption[]>([
  {key: 0, label: `主键`, visible: true},
  {key: 1, label: `租户ID`, visible: true},
  {key: 2, label: `用户`, visible: true},
  {key: 3, label: `待结算token`, visible: true},
  {key: 4, label: `模型ID，关联ai_model`, visible: true},
  {key: 5, label: `提问token数量`, visible: true},
  {key: 6, label: `回复token数量`, visible: true},
  {key: 7, label: `累计使用token`, visible: true},
]);

const initFormData: TokenUsageForm = {
  tokenUsageId: undefined,
  userId: undefined,
  token: undefined,
  modelId: undefined,
  promptToken: undefined,
  completionToken: undefined,
  totalToken: undefined
}
const data = reactive<PageData<TokenUsageForm, TokenUsageQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    tokenUsageId: undefined,
    userId: undefined,
    token: undefined,
    modelId: undefined,
    promptToken: undefined,
    completionToken: undefined,
    totalToken: undefined,
    params: {}
  },
  rules: {
    tokenUsageId: [
      {required: true, message: "主键不能为空", trigger: "blur"}
    ],
    userId: [
      {required: true, message: "用户不能为空", trigger: "blur"}
    ],
    token: [
      {required: true, message: "待结算token不能为空", trigger: "blur"}
    ],
    modelId: [
      {required: true, message: "模型ID，关联ai_model不能为空", trigger: "blur"}
    ],
    promptToken: [
      {required: true, message: "提问token数量不能为空", trigger: "blur"}
    ],
    completionToken: [
      {required: true, message: "回复token数量不能为空", trigger: "blur"}
    ],
    totalToken: [
      {required: true, message: "累计使用token不能为空", trigger: "blur"}
    ]
  }
});

const {queryParams, form, rules} = toRefs(data);

const aiModelList = ref<AiModelVO[]>([]);
/** 查询AI模型列表 */
const getAIModelList = async () => {
  const res = await getAiModelList({});
  aiModelList.value = res.data;
}


/** 查询用户token使用详情列表 */
const getList = async () => {
  loading.value = true;
  const res = await listTokenUsage(queryParams.value);
  tokenUsageList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  tokenUsageFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

const handleDetailQuery = () => {
  detailQueryParams.pageNum = 1;
  getDetailList();
}

/** 重置按钮操作 */
const resetDetailQuery = () => {
  detailQueryFormRef.value?.resetFields();
  selectedUser.value = null;
  detailQueryParams.userId = undefined;
  detailQueryParams.modelId = undefined;
  handleDetailQuery();
}


/** 多选框选中数据 */
const handleSelectionChange = (selection: TokenUsageVO[]) => {
  ids.value = selection.map(item => item.tokenUsageId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}


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

// 获取详情列表数据
const getDetailList = async () => {
  detailLoading.value = true;
  const res = await getAiChatMessageDetailList(detailQueryParams);
  detailList.value = res.rows;
  detailTotal.value = res.total;
  detailLoading.value = false;
};

// ================= 生命周期 =================
onMounted(() => {
  getAIModelList();
  getList();
  getDetailList();
});


// 用户选择操作
const handleUserSelect = (row) => {
  selectedUser.value = row;
  detailQueryParams.userId = row.userId;
  detailQueryParams.modelId = row.modelId;
  getDetailList();
};


// ================= 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 =================


</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>
