<template>
    <el-main>
        <div class="mb-4 flex items-center gap-2 flex-wrap" v-if="isAdmin">
            <el-select v-model="selectedChannel" placeholder="请选择渠道" @change="handleChannelChange" v-if="isAdmin">
                <el-option label="全部渠道" value="" />
                <el-option v-for="item in channelStore.channelOptions" :key="item" :label="item" :value="item" />
            </el-select>
            <el-button :icon="Refresh" circle @click="refreshData" :loading="loading" />
        </div>

        <!-- 今日数据表格 -->
        <el-card class="mb-4" v-if="isAdmin">
            <template #header>
                <div class="flex items-center justify-between">
                    <span>今日数据统计</span>
                    <div class="flex items-center gap-2">
                        <!-- 今日数据日期选择器 -->
                        <el-date-picker
                            v-model="selectedDate"
                            type="date"
                            placeholder="选择日期"
                            format="YYYY-MM-DD"
                            value-format="YYYY-MM-DD"
                            :clearable="true"
                            @change="handleDateChange"
                            size="small"
                        />
                    </div>
                </div>
            </template>
            <el-row :gutter="20">
                <el-col :span="8">
                    <div class="text-center">
                        <div class="text-gray-500 mb-2">新增设备数</div>
                        <div class="text-2xl font-bold text-blue-500">{{ todayData.deviceCount }}</div>
                    </div>
                </el-col>
                <el-col :span="8">
                    <div class="text-center">
                        <div class="text-gray-500 mb-2">ocr记录数</div>
                        <div class="text-2xl font-bold text-green-500">{{ todayData.total }}</div>
                    </div>
                </el-col>
                <el-col :span="8">
                    <div class="text-center">
                        <div class="text-gray-500 mb-2">已扫描数</div>
                        <div class="text-2xl font-bold text-orange-500">{{ todayData.scanned }}</div>
                    </div>
                </el-col>
            </el-row>
        </el-card>

        <!-- 折线图 -->
        <el-card v-if="isAdmin">
            <template #header>
                <div class="flex items-center justify-between">
                    <span>数据统计</span>
                    <div class="flex items-center gap-2">
                        <!-- 图表数据日期范围选择器 -->
                        <el-date-picker
                            v-model="dateRange"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            format="YYYY-MM-DD"
                            value-format="YYYY-MM-DD"
                            :clearable="true"
                            @change="handleDateRangeChange"
                            size="small"
                        />
                    </div>
                </div>
            </template>
            <div ref="chartRef" style="width: 100%; height: 400px"></div>
        </el-card>
        <div class="text-center text-2xl" v-if="!isAdmin">Welcome</div>
    </el-main>
</template>

<script setup>
import { ref, onMounted, inject } from 'vue'
import * as echarts from 'echarts'
import { http } from '@/plugins/http'
import { Refresh } from '@vicons/tabler'
import { useChannelStore } from '@/stores/channel'

const isAdmin = inject('isAdminAndOperator')
const chartRef = ref(null)
let chart = null
const selectedChannel = ref('')
const loading = ref(false)
const selectedDate = ref(null)
const dateRange = ref(null)
const channelStore = useChannelStore()
const todayData = ref({
    date: '',
    total: 0,
    scanned: 0,
    deviceCount: 0
})

onMounted(() => {
    // 监听窗口大小变化，调整图表大小
    window.addEventListener('resize', () => {
        if (chart) {
            chart.resize()
        }
    })

    // 获取渠道列表并加载全部渠道数据
    channelStore.fetchChannelOptions()
    handleChannelChange('')
})

// 获取今日数据
async function getTodayData(channelName) {
    try {
        const params = {
            channel: channelName
        }

        // 如果选择了日期，则添加到参数中
        if (selectedDate.value) {
            params.date = selectedDate.value
        }

        const response = await http.post('/ocrDevice/today', params)
        todayData.value = response
    } catch (error) {
        console.error('获取今日数据失败:', error)
    }
}

// 处理日期变化
function handleDateChange() {
    refreshData()
}

// 处理日期范围变化
function handleDateRangeChange() {
    refreshData()
}

// 刷新数据
async function refreshData() {
    await handleChannelChange(selectedChannel.value)
}

// 处理渠道变化
async function handleChannelChange(channelName) {
    if (!chart) {
        chart = echarts.init(chartRef.value)
    }

    loading.value = true
    try {
        // 获取今日数据
        await getTodayData(channelName)

        // 准备getStatistics接口的参数
        const params = {
            channel: channelName
        }

        // 如果选择了日期范围，则添加到参数中
        if (dateRange.value && dateRange.value.length === 2) {
            params.startDate = dateRange.value[0]
            params.endDate = dateRange.value[1]
        }

        // 获取渠道数据
        const response = await http.post('/ocrDevice/getStatistics', params)

        // 准备图表数据
        const option = {
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['新增设备数', 'ocr记录数', '已扫描数']
            },
            xAxis: {
                type: 'category',
                data: response.dates
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    name: '新增设备数',
                    type: 'line',
                    data: response.deviceCount,
                    label: {
                        show: true,
                        position: 'top'
                    },
                    itemStyle: {
                        color: '#409EFF' // 蓝色
                    }
                },
                {
                    name: 'ocr记录数',
                    type: 'line',
                    data: response.total,
                    label: {
                        show: true,
                        position: 'top'
                    },
                    itemStyle: {
                        color: '#67C23A' // 绿色
                    }
                },
                {
                    name: '已扫描数',
                    type: 'line',
                    data: response.scanned,
                    label: {
                        show: true,
                        position: 'top'
                    },
                    itemStyle: {
                        color: '#E6A23C' // 橘色
                    }
                }
            ]
        }

        // 设置图表配置
        chart.setOption(option)
    } catch (error) {
        console.error('获取数据失败:', error)
    } finally {
        loading.value = false
    }
}
</script>

<style scoped>
.el-date-picker {
    width: auto !important;
}
</style>
