<template>
    <AdminLayout title="对话数据管理" info="管理和分析客服对话数据">
        <template #action>
            <el-button type="primary" @click="exportData">
                <el-icon><Download /></el-icon>
                导出数据
            </el-button>
        </template>

        <div class="chat-container">
            <!-- 筛选区域 -->
            <el-card class="filter-card">
                <div class="ticket-filters">
                    <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 280px;" />

                    <div class="filter-right">
                        <el-select v-model="statusFilter" placeholder="对话状态" clearable style="width: 120px;">
                            <el-option label="进行中" value="active" />
                            <el-option label="已结束" value="closed" />
                        </el-select>
                        <el-input v-model="searchKeyword" placeholder="搜索客户/聊天室" style="width: 200px;" :prefix-icon="Search" clearable @keyup.enter="loadChatRooms" />
                        <el-button type="primary" @click="loadChatRooms">搜索</el-button>
                    </div>
                </div>
            </el-card>

            <!-- 对话列表 -->
            <el-card v-loading="loading">
                <el-table :data="chatRooms" style="width: 100%">
                    <el-table-column prop="roomId" label="聊天室ID" width="180">
                        <template #default="{ row }">
                            <span style="color: #409eff; font-weight: 500;">{{ row.roomId?.substring(0, 8) }}...</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="roomName" label="聊天室名称" width="180" />
                    <el-table-column prop="guestName" label="客户" width="120" />
                    <el-table-column prop="workcaseId" label="关联工单" width="140">
                        <template #default="{ row }">
                            <span v-if="row.workcaseId" style="color: #67c23a;">{{ row.workcaseId }}</span>
                            <span v-else style="color: #909399;">-</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="status" label="状态" width="100">
                        <template #default="{ row }">
                            <el-tag :type="getStatusType(row.status)" size="small">
                                {{ getStatusName(row.status) }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="创建时间" width="160" />
                    <el-table-column label="操作" width="150" fixed="right">
                        <template #default="{ row }">
                            <el-button type="primary" link size="small" @click="viewChat(row)">查看</el-button>
                            <el-button v-if="row.status === 'active'" type="warning" link size="small" @click="closeChat(row)">关闭</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <div class="table-pagination">
                    <el-pagination 
                        v-model:current-page="currentPage" 
                        :page-size="pageSize" 
                        :total="total" 
                        layout="total, prev, pager, next"
                        @current-change="loadChatRooms"
                    />
                </div>
            </el-card>
        </div>

        <!-- 查看对话详情弹窗 - 复用 ChatMessage 组件 -->
        <el-dialog v-model="showChatDialog" title="对话详情" width="800px" class="chat-dialog">
            <ChatMessage v-if="showChatDialog && currentRoomId" :room-id="currentRoomId" :chat-room="currentChatRoom" />
        </el-dialog>
    </AdminLayout>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import AdminLayout from '@/views/admin/AdminLayout.vue'
import { ChatMessage } from '@/views/public/ChatRoom/'
import { Download, Search } from 'lucide-vue-next'
import { ElMessage } from 'element-plus'
import { workcaseChatAPI } from '@/api/workcase/workcaseChat'
import type { ChatRoomVO } from '@/types/workcase/chatRoom'

const dateRange = ref<[Date, Date] | null>(null)
const statusFilter = ref('')
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const showChatDialog = ref(false)
const currentRoomId = ref('')
const currentChatRoom = ref<ChatRoomVO | undefined>(undefined)

// 聊天室列表
const chatRooms = ref<ChatRoomVO[]>([])

// 加载聊天室列表
const loadChatRooms = async () => {
    loading.value = true
    try {
        const filter: any = {}
        if (statusFilter.value) {
            filter.status = statusFilter.value
        }
        if (searchKeyword.value) {
            filter.roomName = searchKeyword.value
        }
        
        const res = await workcaseChatAPI.getChatRoomPage({
            filter,
            pageParam: {
                page: currentPage.value,
                pageSize: pageSize.value
            }
        })
        
        if (res.success) {
            chatRooms.value = res.dataList || []
            total.value = res.total || 0
        } else {
            ElMessage.error(res.message || '加载聊天室列表失败')
        }
    } catch (error) {
        console.error('加载聊天室列表失败:', error)
        ElMessage.error('加载聊天室列表失败')
    } finally {
        loading.value = false
    }
}

const getStatusType = (status: string) => {
    const map: Record<string, string> = {
        active: 'success',
        closed: 'info'
    }
    return map[status] || 'info'
}

const getStatusName = (status: string) => {
    const map: Record<string, string> = {
        active: '进行中',
        closed: '已结束'
    }
    return map[status] || status
}

const viewChat = (row: ChatRoomVO) => {
    currentRoomId.value = row.roomId || ''
    currentChatRoom.value = row
    showChatDialog.value = true
}

const closeChat = async (row: ChatRoomVO) => {
    if (!row.roomId) return
    
    try {
        const loginDomain = JSON.parse(localStorage.getItem('loginDomain') || '{}')
        const userId = loginDomain?.userInfo?.userId || ''
        
        const res = await workcaseChatAPI.closeChatRoom(row.roomId, userId)
        if (res.success) {
            ElMessage.success('聊天室已关闭')
            await loadChatRooms()
        } else {
            ElMessage.error(res.message || '关闭失败')
        }
    } catch (error) {
        console.error('关闭聊天室失败:', error)
        ElMessage.error('关闭聊天室失败')
    }
}

const exportData = () => {
    ElMessage.success('数据导出功能开发中')
}

onMounted(() => {
    loadChatRooms()
})
</script>

<style lang="scss" scoped>
@import url("./CustomerChatView.scss");

.chat-container {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.customer-info {
    display: flex;
    flex-direction: column;
    gap: 2px;
}

.customer-info .name {
    font-weight: 500;
    color: #303133;
}

.customer-info .phone {
    font-size: 12px;
    color: #909399;
}

.chat-dialog {
    :deep(.el-dialog__body) {
        padding: 0;
        max-height: 600px;
        overflow: hidden;
    }
}
</style>