<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="会话标识" prop="sessionId">
              <el-input v-model="queryParams.sessionId" placeholder="请输入会话标识" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="客服ID" prop="agentId">
              <el-input v-model="queryParams.agentId" placeholder="请输入客服ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="客户电话" prop="customerPhone">
              <el-input v-model="queryParams.customerPhone" placeholder="请输入客户电话" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="创建人" prop="userId">
              <el-input v-model="queryParams.userId" placeholder="请输入创建人ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <div style="width: 100%"></div>
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker clearable
                v-model="queryParams.startTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择开始时间"
              />
            </el-form-item>
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker clearable
                v-model="queryParams.endTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择结束时间"
              />
            </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-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['talk:session:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['talk:session:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="sessionList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="会话ID" align="center" prop="id" width="80" />
        <el-table-column label="会话标识" align="center" prop="sessionId" width="200" show-overflow-tooltip />
        <el-table-column label="客服ID" align="center" prop="agentId" />
        <el-table-column label="客户电话" align="center" prop="customerPhone" />
        <el-table-column label="创建人" align="center" prop="userId" />
        <el-table-column label="开始时间" align="center" prop="startTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" prop="endTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看详情" placement="top">
              <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['talk:session:query']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['talk:session:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 查看会话详情对话框 -->
    <el-dialog title="会话详情" v-model="dialog.visible" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="会话标识">{{ sessionDetail.sessionId }}</el-descriptions-item>
        <el-descriptions-item label="客服ID">{{ sessionDetail.agentId }}</el-descriptions-item>
        <el-descriptions-item label="客户电话">{{ sessionDetail.customerPhone }}</el-descriptions-item>
        <el-descriptions-item label="创建人">{{ sessionDetail.userId }}</el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ parseTime(sessionDetail.startTime) }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ parseTime(sessionDetail.endTime) }}</el-descriptions-item>
      </el-descriptions>
      <el-divider content-position="left">对话内容</el-divider>
      <div class="conversation-content">
        <div v-if="parsedConversation.length > 0" class="message-list">
          <div v-for="(msg, index) in parsedConversation" :key="index" class="message-item">
            <div class="message-header">
              <span class="message-role" :class="msg.role === 'user' ? 'user-role' : 'assistant-role'">
                {{ msg.role === 'user' ? 'User' : 'AI' }}
              </span>
              <span class="message-time">{{ formatTimestamp(msg.timestamp) }}</span>
            </div>
            <div class="message-content">{{ msg.content }}</div>
          </div>
        </div>
        <div v-else class="empty-conversation">暂无对话内容</div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Session" lang="ts">
import { listSession, getSession, delSession } from '@/api/talk/session';
import { SessionVO, SessionQuery } from '@/api/talk/session/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const sessionList = ref<SessionVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const multiple = ref(true);
const total = ref(0);
const sessionDetail = ref<SessionVO>({} as SessionVO);

const queryFormRef = ref<ElFormInstance>();

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

const data = reactive<PageData<any, SessionQuery>>({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    sessionId: undefined,
    agentId: undefined,
    customerPhone: undefined,
    userId: undefined,
    startTime: undefined,
    endTime: undefined,
    orderByColumn: 'createTime',
    isAsc: 'desc'
  },
  rules: {}
});

const { queryParams } = toRefs(data);

/** 解析对话内容 */
const parsedConversation = computed(() => {
  if (!sessionDetail.value.conversationJson) {
    return [];
  }
  try {
    return JSON.parse(sessionDetail.value.conversationJson);
  } catch (e) {
    console.error('解析对话内容失败:', e);
    return [];
  }
});

/** 格式化时间戳 */
const formatTimestamp = (timestamp: string) => {
  if (!timestamp) return '';
  const date = new Date(parseInt(timestamp));
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

/** 查询会话列表 */
const getList = async () => {
  loading.value = true;
  const res = await listSession(queryParams.value);
  sessionList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

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

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

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

/** 查看详情 */
const handleView = async (row: SessionVO) => {
  const res = await getSession(row.id);
  sessionDetail.value = res.data;
  dialog.visible = true;
}

/** 删除按钮操作 */
const handleDelete = async (row?: SessionVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除会话编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delSession(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('talk/session/export', {
    ...queryParams.value
  }, `session_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>

<style scoped>
.conversation-content {
  max-height: 400px;
  overflow-y: auto;
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
}

.message-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.message-item {
  background: white;
  padding: 12px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  padding-bottom: 6px;
  border-bottom: 1px solid #e5e7eb;
}

.message-role {
  font-weight: 600;
  font-size: 14px;
  padding: 2px 8px;
  border-radius: 4px;
}

.user-role {
  background-color: #dbeafe;
  color: #1e40af;
}

.assistant-role {
  background-color: #dcfce7;
  color: #166534;
}

.message-time {
  font-size: 12px;
  color: #6b7280;
}

.message-content {
  font-size: 14px;
  line-height: 1.6;
  color: #374151;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.empty-conversation {
  text-align: center;
  color: #9ca3af;
  padding: 20px;
  font-size: 14px;
}
</style>
