<template>
    <AdminLayout title="数据概览" info="泰豪小电智能客服运营数据">
        <div class="overview-container">
            <!-- 核心指标卡片 -->
            <div class="dashboard-stats">
                <div class="stat-card clickable" @click="goToChat">
                    <div class="stat-icon" style="background: linear-gradient(135deg, #409eff, #66b1ff);">
                        <el-icon><ChatDotRound /></el-icon>
                    </div>
                    <div class="stat-info">
                        <div class="stat-value">{{ dashboardData.consultCount }}</div>
                        <div class="stat-label">咨询次数</div>
                        <div class="stat-trend" :class="dashboardData.consultTrend >= 0 ? 'up' : 'down'">
                            <el-icon v-if="dashboardData.consultTrend >= 0"><Top /></el-icon>
                            <el-icon v-else><Top style="transform: rotate(180deg);" /></el-icon>
                            <span>较昨日 {{ dashboardData.consultTrend >= 0 ? '+' : '' }}{{ dashboardData.consultTrend }}%</span>
                        </div>
                    </div>
                </div>

                <div class="stat-card clickable" @click="goToWorkcase('pending')">
                    <div class="stat-icon" style="background: linear-gradient(135deg, #e6a23c, #f5c06a);">
                        <el-icon><Clock /></el-icon>
                    </div>
                    <div class="stat-info">
                        <div class="stat-value">{{ dashboardData.pendingTickets }}</div>
                        <div class="stat-label">待处理工单</div>
                        <div class="stat-trend">
                            <span>点击查看详情</span>
                            <el-icon><Right /></el-icon>
                        </div>
                    </div>
                </div>

                <div class="stat-card clickable" @click="goToWorkcase('completed')">
                    <div class="stat-icon" style="background: linear-gradient(135deg, #67c23a, #95d475);">
                        <el-icon><Select /></el-icon>
                    </div>
                    <div class="stat-info">
                        <div class="stat-value">{{ dashboardData.completedTickets }}</div>
                        <div class="stat-label">已处理工单</div>
                        <div class="stat-trend">
                            <span>点击查看详情</span>
                            <el-icon><Right /></el-icon>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 问题分类统计和词云 -->
            <div class="dashboard-charts">
                <el-card class="chart-card">
                    <template #header>
                        <div class="card-header">
                            <span>问题分类统计</span>
                            <el-radio-group v-model="questionStatPeriod" size="small">
                                <el-radio-button label="today">今日</el-radio-button>
                                <el-radio-button label="week">本周</el-radio-button>
                                <el-radio-button label="month">本月</el-radio-button>
                            </el-radio-group>
                        </div>
                    </template>
                    <div class="question-stats">
                        <div v-if="questionCategories.length > 0">
                            <div v-for="item in questionCategories" :key="item.name" class="question-stat-item clickable">
                                <div class="stat-bar-header">
                                    <span class="stat-name">{{ item.name }}</span>
                                    <span class="stat-count">{{ item.count }} 次</span>
                                </div>
                                <div class="stat-bar">
                                    <div class="stat-bar-fill" :style="{ width: item.percent + '%', background: item.color }"></div>
                                </div>
                            </div>
                        </div>
                        <div v-else class="empty-state">
                            <el-icon :size="48" style="color: #dcdfe6;"><Document /></el-icon>
                            <p>暂无数据</p>
                        </div>
                    </div>
                </el-card>

                <el-card class="chart-card">
                    <template #header>
                        <div class="card-header">
                            <span>涉及产品词云</span>
                            <el-button type="primary" link size="small" @click="goToChat">
                                查看详情
                                <el-icon><Right /></el-icon>
                            </el-button>
                        </div>
                    </template>
                    <div class="product-cloud">
                        <div v-if="productCloudData.length > 0">
                            <span v-for="(product, index) in productCloudData" :key="index" class="cloud-tag"
                                :style="{ fontSize: product.size + 'px', color: product.color, opacity: 0.7 + product.weight * 0.3 }">
                                {{ product.name }}
                            </span>
                        </div>
                        <div v-else class="empty-state">
                            <el-icon :size="48" style="color: #dcdfe6;"><Document /></el-icon>
                            <p>暂无数据</p>
                        </div>
                    </div>
                </el-card>
            </div>

            <!-- 快捷入口 -->
            <el-card class="quick-entry-card">
                <template #header>
                    <span>快捷入口</span>
                </template>
                <div class="quick-entries">
                    <div class="quick-entry-item" @click="goToKnowledge">
                        <el-icon class="entry-icon" style="background: #409eff;"><Document /></el-icon>
                        <span>知识库管理</span>
                    </div>
                    <div class="quick-entry-item" @click="goToWorkcase()">
                        <el-icon class="entry-icon" style="background: #e6a23c;"><Tickets /></el-icon>
                        <span>工单管理</span>
                    </div>
                    <div class="quick-entry-item" @click="goToChat">
                        <el-icon class="entry-icon" style="background: #67c23a;"><ChatDotRound /></el-icon>
                        <span>对话数据</span>
                    </div>
                    <div class="quick-entry-item" @click="goToAgent">
                        <el-icon class="entry-icon" style="background: #909399;"><Service /></el-icon>
                        <span>智能体管理</span>
                    </div>
                </div>
            </el-card>
        </div>
    </AdminLayout>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue'
import { useRouter } from 'vue-router'
import AdminLayout from '@/views/admin/AdminLayout.vue'
import { MessageCircle as ChatDotRound, Clock, CheckSquare as Select, ArrowUp as Top, ArrowRight as Right, FileText as Document, Ticket as Tickets, Headphones as Service } from 'lucide-vue-next'
import { workcaseAPI } from '@/api/workcase/workcase'
import { workcaseChatAPI } from '@/api/workcase/workcaseChat'
import type { TbWorkcaseDTO, TbWordCloudDTO, TbChatRoomDTO } from '@/types/workcase'

const router = useRouter()

const questionStatPeriod = ref('today')

// 核心数据统计
const dashboardData = ref({
    consultCount: 0,  // 咨询次数（昨日聊天室数量）
    consultTrend: 0,  // 较前日的增减百分比
    pendingTickets: 0,  // 待处理工单总量
    completedTickets: 0  // 已处理工单总量
})

// 问题分类统计数据
const questionCategories = ref<Array<{ name: string; count: number; percent: number; color: string }>>([])

// 词云数据
const productCloudData = ref<Array<{ name: string; size: number; weight: number; color: string }>>([])

// 颜色配置
const colors = ['#409eff', '#67c23a', '#e6a23c', '#f56c6c', '#909399']

// 获取昨日和前日的时间范围
const getYesterdayRange = () => {
    const today = new Date()
    today.setHours(0, 0, 0, 0)

    const yesterday = new Date(today)
    yesterday.setDate(today.getDate() - 1)

    const yesterdayEnd = new Date(today)
    yesterdayEnd.setMilliseconds(-1)

    const dayBeforeYesterday = new Date(yesterday)
    dayBeforeYesterday.setDate(yesterday.getDate() - 1)

    const dayBeforeYesterdayEnd = new Date(yesterday)
    dayBeforeYesterdayEnd.setMilliseconds(-1)

    return {
        yesterday: { start: yesterday, end: yesterdayEnd },
        dayBeforeYesterday: { start: dayBeforeYesterday, end: dayBeforeYesterdayEnd }
    }
}

// 根据时间周期计算开始和结束时间
const getTimeRange = (period: string) => {
    const now = new Date()
    const endTime = now
    const startTime = new Date()

    if (period === 'today') {
        startTime.setHours(0, 0, 0, 0)
    } else if (period === 'week') {
        startTime.setDate(now.getDate() - 7)
    } else if (period === 'month') {
        startTime.setMonth(now.getMonth() - 1)
    }

    return { startTime, endTime }
}

// 加载核心数据统计
const loadDashboardData = async () => {
    try {
        // 1. 统计昨日和前日的咨询次数（使用count接口）
        const timeRanges = getYesterdayRange()

        const yesterdayResult = await workcaseChatAPI.countChatRooms({
            startTime: timeRanges.yesterday.start,
            endTime: timeRanges.yesterday.end
        } as TbChatRoomDTO)

        const dayBeforeResult = await workcaseChatAPI.countChatRooms({
            startTime: timeRanges.dayBeforeYesterday.start,
            endTime: timeRanges.dayBeforeYesterday.end
        } as TbChatRoomDTO)

        if (yesterdayResult.success && dayBeforeResult.success) {
            const yesterdayCount = Number(yesterdayResult.data || 0)
            const dayBeforeCount = Number(dayBeforeResult.data || 0)

            dashboardData.value.consultCount = yesterdayCount

            // 计算增减百分比
            if (dayBeforeCount > 0) {
                const change = ((yesterdayCount - dayBeforeCount) / dayBeforeCount) * 100
                dashboardData.value.consultTrend = Math.round(change * 10) / 10  // 保留1位小数
            } else {
                dashboardData.value.consultTrend = yesterdayCount > 0 ? 100 : 0
            }
        }

        // 2. 统计待处理工单总量（使用count接口）
        const pendingResult = await workcaseAPI.countWorkcases({
            status: 'pending'
        } as TbWorkcaseDTO)

        if (pendingResult.success && pendingResult.data) {
            dashboardData.value.pendingTickets = Number(pendingResult.data || 0)
        }

        // 3. 统计已处理工单总量（使用count接口）
        const completedResult = await workcaseAPI.countWorkcases({
            status: 'done'
        } as TbWorkcaseDTO)

        if (completedResult.success && completedResult.data) {
            dashboardData.value.completedTickets = Number(completedResult.data || 0)
        }
    } catch (error) {
        console.error('加载核心数据统计失败:', error)
    }
}

// 加载问题分类统计
const loadQuestionStats = async () => {
    try {
        const { startTime, endTime } = getTimeRange(questionStatPeriod.value)

        const result = await workcaseAPI.countWorkcasesByType({
            startTime,
            endTime
        } as TbWorkcaseDTO)

        if (result.success && result.data) {
            const data = Array.isArray(result.data) ? result.data : [result.data]

            // 计算总数
            const total = data.reduce((sum, item) => sum + (item.count || 0), 0)

            // 转换数据格式并计算百分比
            questionCategories.value = data.map((item, index) => ({
                name: item.type || '未分类',
                count: Number(item.count || 0),
                percent: total > 0 ? Math.round((Number(item.count || 0) / total) * 100) : 0,
                color: colors[index % colors.length]
            }))
        }
    } catch (error) {
        console.error('加载问题分类统计失败:', error)
    }
}

// 加载词云数据
const loadWordCloud = async () => {
    try {
        const result = await workcaseChatAPI.getWordCloudList({
            limit: 10,
            category: 'product'
        } as TbWordCloudDTO)

        if (result.success && result.data) {
            const data = Array.isArray(result.data) ? result.data : [result.data]

            // 找出最大词频用于归一化
            const maxFreq = Math.max(...data.map(item => Number(item.frequency || 0)))

            // 转换数据格式
            productCloudData.value = data.map((item, index) => {
                const freq = Number(item.frequency || 0)
                const weight = maxFreq > 0 ? freq / maxFreq : 0

                return {
                    name: item.word || '',
                    size: 16 + Math.round(weight * 10), // 16-26px
                    weight,
                    color: colors[index % colors.length]
                }
            })
        }
    } catch (error) {
        console.error('加载词云数据失败:', error)
    }
}

// 监听时间周期变化
watch(questionStatPeriod, () => {
    loadQuestionStats()
})

// 页面加载时获取数据
onMounted(() => {
    loadDashboardData()
    loadQuestionStats()
    loadWordCloud()
})

const goToChat = () => {
    router.push('/admin/customerChat')
}

const goToWorkcase = (status?: string) => {
    router.push('/admin/workcase')
}

const goToKnowledge = () => {
    router.push('/admin/knowledge')
}

const goToAgent = () => {
    router.push('/admin/agent')
}
</script>

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

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

.dashboard-charts {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
}

@media (max-width: 1280px) {
    .dashboard-charts {
        grid-template-columns: 1fr;
    }
}
</style>