<template>
    <div class="home-container">
        <el-form>
            <el-form-item label="所属系统">
                <el-select
                    v-model="systemId"
                    :clearable="false"
                    :config="{ label: 'name', value: 'id' }"
                    :opts="opts.system"
                />
            </el-form-item>
        </el-form>
        <el-card header="在线人数">{{ online }}</el-card>
        <el-card>
            <template #header>
                <div class="flex">
                    <p>单日消息量</p>
                    <el-date-picker
                        v-model="date1"
                        :disabled-date="(date) => date.getTime() > Date.now()"
                        type="date"
                        value-format="YYYY-MM-DD"
                    />
                </div>
            </template>
            <div class="chart chart-1"></div>
        </el-card>
        <el-card>
            <template #header>
                <div class="flex">
                    <p>历史消息量</p>
                    <date-range v-model="date2" />
                </div>
            </template>
            <div class="chart chart-2"></div>
        </el-card>
    </div>
</template>

<script setup>
    import dayjs from 'dayjs';
    import * as echarts from 'echarts';
    import DateRange from './dateRange.vue';
    const store = useStore();
    const loading = ref(false);
    const opts = computed(() => store.state.imStore.opts);
    if (!unref(opts).init) {
        store.dispatch('imStore/load');
    }

    const systemId = ref(null);
    watch(
        () => unref(opts).system,
        (value) => {
            if (!unref(systemId)) {
                systemId.value = value?.[0]?.id;
            }
        },
        { immediate: true }
    );
    const online = computed(() => store.state.imHome.online);
    const handleLoadOnline = async () => {
        loading.value = true;
        if (unref(systemId)) {
            await store.dispatch('imHome/loadOnline', { systemId: unref(systemId) });
        }
        loading.value = false;
    };
    watch(systemId, handleLoadOnline);

    const charts = ref({});
    window.addEventListener('resize', () =>
        setTimeout(() => {
            Object.entries(unref(charts)).forEach((entry) => {
                entry[1].resize();
            });
        }, 100)
    );
    const handleChart = (
        selector,
        name,
        data,
        formatter = (params) =>
            `${params[0].axisValue}<br/><span style="color:${params[0].color};font-size:20px;margin-right:5px;">●</span>${params[0].seriesName}<b style="margin-left:10px;">${params[0].value}</b>`
    ) => {
        let chart = charts.value[selector];
        chart?.dispose();
        chart = charts.value[selector] = echarts.init(document.querySelector(selector));
        const option = {
            gradientColor: ['#1DE7FF', '#249AFF', '#6F41FA', '#6F41FA'],
            visualMap: [
                {
                    show: false,
                    type: 'continuous',
                    dimension: 0,
                    min: 0,
                    max: data.length - 1,
                },
            ],
            tooltip: {
                trigger: 'axis',
                formatter,
            },
            grid: {
                left: '0',
                right: '0',
                bottom: '30px',
                top: '60px',
                containLabel: true,
            },
            xAxis: {
                data: data.map((item) => item.label),
            },
            yAxis: {
                minInterval: 1,
            },
            series: {
                type: 'line',
                name,
                showSymbol: false,
                smooth: true,
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {
                            offset: 0,
                            color: 'rgba(29, 231, 255, 0.3)',
                        },
                        {
                            offset: 1,
                            color: 'rgba(29, 231, 255, 0)',
                        },
                    ]),
                },
                data: data.map((item) => item.value),
            },
        };
        chart.setOption(option);
    };

    const date1 = ref(dayjs(new Date()).format('YYYY-MM-DD'));
    const handleLoadSingle = async () => {
        loading.value = true;
        store.commit('imHome/setSingle', []);
        if (unref(systemId)) {
            if (unref(date1)) {
                await store.dispatch('imHome/loadSingle', {
                    systemId: unref(systemId),
                    days: unref(date1),
                });
            }
        }
        loading.value = false;
    };
    watch(date1, handleLoadSingle, { immediate: true });
    watch(systemId, handleLoadSingle);
    watch(
        () => store.state.imHome.single,
        (value) => {
            handleChart(
                '.chart-1',
                '消息量',
                value.map((item) => {
                    return {
                        label: item.hours,
                        value: item.messageCount,
                    };
                }),
                (params) =>
                    `${params[0].axisValue}:00 - ${params[0].axisValue}:59<br/><span style="color:${params[0].color};font-size:20px;margin-right:5px;">●</span>${params[0].seriesName}<b style="margin-left:10px;">${params[0].value}</b>`
            );
        }
    );

    const date2 = ref([]);
    const handleLoadRange = async () => {
        loading.value = true;
        store.commit('imHome/setRange', []);
        if (unref(systemId)) {
            if (unref(date2)?.length) {
                await store.dispatch('imHome/loadRange', {
                    systemId: unref(systemId),
                    start: unref(date2)[0],
                    end: unref(date2)[1],
                });
            }
        }
        loading.value = false;
    };
    watch(date2, handleLoadRange);
    watch(systemId, handleLoadRange);
    watch(
        () => store.state.imHome.range,
        (value) => {
            handleChart(
                '.chart-2',
                '消息量',
                value.map((item) => {
                    return {
                        label: item.days,
                        value: item.messageCount,
                    };
                })
            );
        }
    );

    onActivated(() => {
        handleLoadOnline();
        handleLoadSingle();
        handleLoadRange();
    });
</script>

<style lang="less" scoped>
    .home-container {
        .flex {
            display: flex;
            align-items: center;
            justify-content: space-between;
            p {
                margin-right: 20px;
            }
        }
        .el-card {
            & + .el-card {
                margin-top: 30px;
            }
            &:nth-of-type(1) {
                :deep(.el-card__body) {
                    font-size: 32px;
                }
            }
            .chart {
                width: 100%;
                height: 300px;
            }
        }
    }
</style>
