<template>
    <div class="dashboard-container">
        <el-row :gutter="20" class="card-row">
            <el-col :span="6" v-for="(item, index) in statsList" :key="index">
                <el-card class="summary-card" shadow="hover">
                    <div class="card-content">
                        <div :class="['icon-placeholder', item.bgClass]"><i :class="item.icon"></i></div>
                        <div class="info">
                            <div class="title">{{ item.title }}</div>
                            <div class="value">{{ item.prefix }}{{ item.value }}</div>
                        </div>
                    </div>
                </el-card>
            </el-col>
        </el-row>

        <el-row :gutter="20" class="chart-row">
            <el-col :span="16">
                <el-card class="chart-card" shadow="hover">
                    <div class="chart-title">周营收趋势</div>
                    <div id="weekChart" style="width: 100%; height: 280px"></div>
                </el-card>
            </el-col>
            <el-col :span="8">
                <el-card class="chart-card" shadow="hover">
                    <div class="card-header">
                        <div class="card-title">公告列表</div>
                    </div>
                    <div class="table-container">
                        <el-table
                            :data="noticeList"
                            height="250"
                            style="width: 100%"
                            :header-cell-style="tableHeaderStyle"
                            :cell-style="tableCellStyle"
                            :row-class-name="tableRowClassName"
                        >
                            <el-table-column prop="title" label="标题" min-width="40%" show-overflow-tooltip>
                                <template #default="scope">
                                    <div class="cell-content">
                                        <span class="title-text">{{ scope.row.title }}</span>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="content" label="内容" min-width="40%" show-overflow-tooltip>
                                <template #default="scope">
                                    <div class="cell-content">
                                        <span class="content-text">{{ scope.row.content }}</span>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="type" label="类型" min-width="20%" align="center">
                                <template #default="scope">
                                    {{ noticeTypeList.find(type => type.id === scope.row.type)?.title || '未知类型' }}
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-card>
            </el-col>
        </el-row>

        <el-row :gutter="20" class="chart-row">
            <el-col :span="10">
                <el-card class="chart-card" shadow="hover">
                    <div class="chart-title">用户充值排行</div>
                    <div id="userRankChart" style="width: 100%; height: 280px"></div>
                </el-card>
            </el-col>
            <el-col :span="14">
                <el-card class="chart-card" shadow="hover">
                    <div class="card-header">
                        <div class="card-title">模板列表</div>
                    </div>
                    <div class="table-container">
                        <el-table
                            :data="templateList"
                            height="250"
                            style="width: 100%"
                            :header-cell-style="tableHeaderStyle"
                            :cell-style="tableCellStyle"
                            :row-class-name="tableRowClassName"
                        >
                            <el-table-column prop="title" label="标题" min-width="18%" show-overflow-tooltip>
                                <template #default="scope">
                                    <div class="cell-content">
                                        <span class="title-text">{{ scope.row.title }}</span>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="type" label="类型" min-width="12%" align="center">
                                <template #default="scope">
                                    {{ templateTypeList.find(type => type.id === scope.row.type)?.title || '未知类型' }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="viewCount" label="浏览量" min-width="10%" align="center">
                                <template #default="scope">
                                    <span class="view-count">{{ scope.row.viewCount }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="price" label="价格" min-width="12%" align="right">
                                <template #default="scope">
                                    <span class="price">¥{{ scope.row.price }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="industry" label="行业" min-width="16%" align="center">
                                <template #default="scope">
                                    <el-tag size="small" type="info" effect="plain">
                                        {{ scope.row.industry }}
                                    </el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column prop="introduction" label="简介" min-width="32%" show-overflow-tooltip>
                                <template #default="scope">
                                    <div class="cell-content">
                                        <span class="intro-text">{{ scope.row.introduction }}</span>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<script setup>
import { getDataPanel, getMoneyListByWeek, getMoneyListByMonth } from '@/api/vrone/dataPanel'
import { listNoticeType } from '@/api/vrone/noticeType'

import { ref, computed, onMounted } from 'vue'
import * as echarts from 'echarts'

const loading = ref(false)
const noticeList = ref([])
const noticeTypeList = ref([])
const templateList = ref([])
const userOrderByMoneyList = ref([])
const moneyListByWeek = ref([])
const moneyListByMonth = ref([])
const userCount = ref(0)
const userCountByToday = ref(0)
const totalMoney = ref(0)
const todayMoney = ref(0)
const templateTypeList = ref([
    {
        id: 2,
        title: '720'
    },
    {
        id: 1,
        title: 'unity'
    }
])
const statsList = computed(() => [
    {
        title: '总用户数',
        value: userCount.value,
        prefix: '',
        icon: 'el-icon-user',
        bgClass: 'bg-purple'
    },
    {
        title: '今日新增用户',
        value: userCountByToday.value,
        prefix: '',
        icon: 'el-icon-user-plus',
        bgClass: 'bg-cyan'
    },
    {
        title: '总营收',
        value: totalMoney.value,
        prefix: '￥',
        icon: 'el-icon-wallet',
        bgClass: 'bg-blue'
    },
    {
        title: '今日营收',
        value: todayMoney.value,
        prefix: '￥',
        icon: 'el-icon-money',
        bgClass: 'bg-pink'
    }
])

let weekChartInstance = null
let userRankChartInstance = null

// 表格表头样式
const tableHeaderStyle = {
    background: '#f0f5ff',
    color: '#4b67e8',
    fontWeight: '600',
    borderBottom: '2px solid #e3eaff',
    padding: '12px 0'
}

// 表格单元格样式
const tableCellStyle = {
    padding: '8px 0',
    borderBottom: '1px solid #f0f5ff'
}

// 表格行类名
function tableRowClassName({ rowIndex }) {
    return rowIndex % 2 === 0 ? 'row-even' : 'row-odd'
}

// 设置总充值的淡蓝色
const TOTAL_MONEY_COLOR = '#b3c6ff'
const BALANCE_COLOR = '#7276ff'

function getList() {
    loading.value = true
    getDataPanel().then(response => {
        noticeList.value = response.data.noticeList
        templateList.value = response.data.templateList
        userOrderByMoneyList.value = response.data.userOrderByMoney
        userCount.value = response.data.userCount
        userCountByToday.value = response.data.userCountByToday
        totalMoney.value = response.data.totalMoney
        todayMoney.value = response.data.todayMoney
        loading.value = false

        setTimeout(initUserRankChart, 100)
    })
    listNoticeType().then(response => {
        noticeTypeList.value = response.rows
    })
    getWeekMoneyList()
}

function getWeekMoneyList() {
    getMoneyListByWeek().then(response => {
        moneyListByWeek.value = response.data
        setTimeout(initWeekChart, 100)
    })
}

function initWeekChart() {
    const chartDom = document.getElementById('weekChart')
    if (!chartDom) return
    
    weekChartInstance = echarts.init(chartDom)
    
    // 获取最近七天的日期范围（包括今天）
    const dates = []
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    
    for (let i = 6; i >= 0; i--) {
        const date = new Date(today)
        date.setDate(today.getDate() - i)
        dates.push(date.toISOString().split('T')[0])
    }
    
    // 处理已有数据，按日期排序
    const sortedData = [...moneyListByWeek.value].sort((a, b) => new Date(a.time) - new Date(b.time))
    
    // 将原始数据转换为以日期为键的映射
    const dataMap = {}
    sortedData.forEach(item => {
        const dateKey = new Date(item.time).toISOString().split('T')[0]
        dataMap[dateKey] = item.money
    })
    
    // 构建完整的七天数据，缺失的日期用0填充
    const fullData = dates.map(date => ({
        date: date,
        value: dataMap[date] || 0
    }))
    
    const option = {
        tooltip: {
            trigger: 'axis',
            formatter: function (params) {
                const data = params[0]
                return `${data.name}<br/>营收：￥${data.value.toLocaleString()}`
            },
            backgroundColor: 'rgba(255, 255, 255, 0.9)',
            borderColor: '#e3eaff',
            borderWidth: 1,
            textStyle: {
                color: '#333'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '5%',
            top: '8%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: fullData.map(item => item.date),
            axisLabel: {
                rotate: 0,
                formatter: function (value) {
                    return value.substring(5)
                },
                color: '#666'
            },
            axisLine: {
                lineStyle: {
                    color: '#e3eaff'
                }
            },
            axisTick: {
                show: false
            }
        },
        yAxis: {
            type: 'value',
            axisLabel: {
                formatter: value => `￥${(value / 10000).toFixed(0)}万`,
                color: '#666'
            },
            axisLine: {
                show: false
            },
            axisTick: {
                show: false
            },
            splitLine: {
                lineStyle: {
                    color: '#f0f5ff'
                }
            }
        },
        series: [
            {
                name: '营收',
                data: fullData.map(item => item.value),
                type: 'line',
                smooth: true,
                showSymbol: true,
                symbolSize: 8,
                lineStyle: {
                    width: 3,
                    shadowColor: 'rgba(0,0,0,0.1)',
                    shadowBlur: 10,
                    shadowOffsetY: 8,
                    color: '#4b67e8'
                },
                itemStyle: {
                    color: '#4b67e8',
                    borderColor: '#fff',
                    borderWidth: 2,
                    shadowColor: 'rgba(0,0,0,0.1)',
                    shadowBlur: 5
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: 'rgba(75, 103, 232, 0.3)' },
                        { offset: 1, color: 'rgba(75, 103, 232, 0.05)' }
                    ])
                }
            }
        ]
    }
    
    weekChartInstance.setOption(option)
}

function initUserRankChart() {
    const chartDom = document.getElementById('userRankChart')
    if (!chartDom) return

    userRankChartInstance = echarts.init(chartDom)

    // 取前5个用户数据并按总充值金额倒序排序
    const userData = [...userOrderByMoneyList.value]
        .sort((a, b) => b.totalMoney - a.totalMoney)
        .slice(0, 5)
        .reverse()

    // 计算已消费金额
    const consumedData = userData.map(item => {
        return {
            name: item.userName || '用户' + item.phone.substring(item.phone.length - 4),
            consumed: item.totalMoney - item.money,
            balance: item.money,
            totalMoney: item.totalMoney,
            phone: item.phone
        }
    })

    const option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            formatter: function (params) {
                const index = params[0].dataIndex
                const user = consumedData[index]
                const userName = user.name
                const phone = user.phone || '未知'
                const totalMoney = user.totalMoney
                const percent = ((user.balance / totalMoney) * 100).toFixed(1)

                let html = `<div style="font-weight:bold;margin-bottom:5px">${userName}</div>`
                html += `<div>手机：${phone}</div>`
                html += `<div>总充值：￥${totalMoney.toLocaleString()}</div>`
                html += `<div>已消费：￥${user.consumed.toLocaleString()}</div>`
                html += `<div>账户余额：￥${user.balance.toLocaleString()} (${percent}%)</div>`

                return html
            }
        },
        legend: {
            data: ['总充值', '账户余额'],
            right: 10,
            top: 10
        },
        grid: {
            left: '3%',
            right: '15%',
            bottom: '5%',
            top: '15%',
            containLabel: true
        },
        xAxis: {
            type: 'value',
            axisLabel: {
                formatter: value => `￥${(value / 10000).toFixed(0)}万`
            }
        },
        yAxis: {
            type: 'category',
            data: consumedData.map(item => item.name),
            axisTick: {
                alignWithLabel: true
            }
        },
        series: [
            {
                name: '总充值',
                type: 'bar',
                barWidth: '60%',
                data: consumedData.map(item => item.totalMoney),
                itemStyle: {
                    color: TOTAL_MONEY_COLOR // 淡蓝色
                },
                label: {
                    show: true,
                    position: 'right',
                    formatter: function (params) {
                        return `￥${params.value.toLocaleString()}`
                    }
                },
                z: 1
            },
            {
                name: '账户余额',
                type: 'bar',
                barWidth: '60%',
                barGap: '-100%', // 负值表示重叠
                data: consumedData.map(item => item.balance),
                itemStyle: {
                    color: BALANCE_COLOR // 原色
                },
                label: {
                    show: false
                },
                z: 2
            }
        ]
    }

    userRankChartInstance.setOption(option)
}

onMounted(() => {
    setTimeout(() => {
        getList()
    }, 300)

    window.addEventListener('resize', () => {
        if (weekChartInstance) {
            weekChartInstance.resize()
        }
        if (userRankChartInstance) {
            userRankChartInstance.resize()
        }
    })
})
</script>

<style scoped>
.dashboard-container {
    padding: 16px;
    background-color: #f7f9ff;
    height: calc(100vh - 94px); /* 减去顶部导航栏和标签页的高度 */
    overflow: hidden;
}

.card-row {
    margin-bottom: 12px;
}

.summary-card {
    height: 90px; /* 减少卡片高度 */
    transition: all 0.3s;
    border-radius: 12px;
    border: none;
    overflow: hidden;
}

.card-content {
    display: flex;
    align-items: center;
    height: 100%;
}

.icon-placeholder {
    width: 48px;
    height: 48px;
    border-radius: 10px;
    margin-right: 16px;
    display: flex;
    justify-content: center;
    align-items: center;
    color: white;
    font-size: 22px;
}

.bg-purple {
    background: linear-gradient(135deg, #6a75ca 0%, #4b67e8 100%);
}

.bg-cyan {
    background: linear-gradient(135deg, #33c9dc 0%, #00b8d9 100%);
}

.bg-blue {
    background: linear-gradient(135deg, #5b8ff9 0%, #2e5aac 100%);
}

.bg-pink {
    background: linear-gradient(135deg, #ff85c0 0%, #ff5891 100%);
}

.info .title {
    font-size: 14px;
    color: #8c8c8c;
    margin-bottom: 8px;
}

.info .value {
    font-size: 22px;
    font-weight: bold;
    color: #333;
}

.chart-row {
    margin-bottom: 12px;
}

.chart-card {
    height: 320px; /* 减少图表卡片高度 */
    position: relative;
    border-radius: 12px;
    transition: all 0.3s;
    border: none;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

.chart-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    padding: 10px 16px;
}

.chart-container {
    flex: 1;
    padding: 0;
    position: relative;
    width: 100%;
    height: calc(100% - 49px);
}

.chart-content {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
}

.chart-placeholder {
    width: 100%;
    flex: 1;
    min-height: 280px;
    background-color: #fff;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 16px;
    border-bottom: 1px solid #f0f5ff;
    flex-shrink: 0;
}

.card-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    position: relative;
    padding-left: 12px;
}

.card-title:before {
    content: '';
    position: absolute;
    left: 0;
    top: 2px;
    height: 16px;
    width: 4px;
    background: #4b67e8;
    border-radius: 2px;
}

.table-container {
    padding: 0 16px 12px;
    height: calc(100% - 45px);
}

/* 表格样式优化 */
:deep(.el-table) {
    border-radius: 8px;
    overflow: hidden;
    --el-table-header-bg-color: #f0f5ff;
    --el-table-row-hover-bg-color: #f7f9ff;
    --el-table-border-color: #e3eaff;
    height: 100%;
    max-height: 240px; /* 限制表格最大高度 */
    border: none;
}

:deep(.el-table th) {
    background-color: var(--el-table-header-bg-color);
    font-weight: 600;
    color: #4b67e8;
    border: none;
}

:deep(.el-table td) {
    padding: 6px 0;
}

:deep(.row-even) {
    background-color: #fff;
}

:deep(.row-odd) {
    background-color: #f8faff;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
    background-color: #f7f9ff;
}

:deep(.el-table::before) {
    display: none;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td) {
    background-color: #eef2ff;
}

.cell-content {
    display: flex;
    align-items: center;
    gap: 6px;
}

.title-text {
    font-weight: 500;
    color: #333;
}

.content-text,
.intro-text {
    color: #666;
    font-size: 13px;
}

.view-count {
    color: #666;
    font-size: 13px;
}

.price {
    color: #f56c6c;
    font-weight: 500;
}

:deep(.el-tag--small) {
    padding: 0 8px;
    height: 22px;
    line-height: 20px;
    border-radius: 4px;
    font-size: 12px;
}

/* 减少图表高度 */
#weekChart,
#userRankChart {
    width: 100%;
    height: 260px !important; /* 减少图表高度 */
}
</style>
