<template>
    <div class="_consume">
        <HeadlineTag type="right" value="用水量昼夜分析"></HeadlineTag>
        <div class="_consume_mains">
            <!-- <div class="_consume_mains" v-if="resultData && Object.keys(resultData).length != 0"> -->
            <div ref="chartRef" style="width: 100%; height: 100%;"></div>
        </div>
        <!-- <Empty :bottom="true" v-else></Empty> -->
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import * as echarts from 'echarts';
import HeadlineTag from '@/components/HeadlineTag';
import Empty from '@/components/Empty'
const props = defineProps({
    resultData: {
        type: Object,
        default: {}
    }
})

const chartRef = ref(null);
let chart = null;
const generateRandomData = (length, max) => {
    const randomData = [];
    for (let i = 0; i < length; i++) {
        randomData.push(Math.floor(Math.random() * max));
    }
    return randomData;
};
const handleResize = () => {
    if (chart) {
        chart.resize();
    }
};
onMounted(() => {
    initChart();
});
const initChart = (dates, waterData, totalUsage, dayUsage) => {
    if (chartRef.value) {
        chart = echarts.init(chartRef.value);
        const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
        // const months = []
        const option = {
            xAxis: {
                type: 'category',
                data: months,
                axisLabel: {
                    color: '#fff'
                },
                data: dates,
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                    crossStyle: {
                        color: '#999'
                    }
                },
                textStyle: {
                    color: '#fafafa',
                },
                borderColor: 'transparent',
                backgroundColor: 'rgba(0, 0, 0, 0.5)',
                extraCssText: 'backdrop-filter: blur(6px);',
            },
            // 调整 grid 配置以在 Y 轴方向拉伸图表
            grid: {
                top: '10%', // 减小顶部边距，让图表向上扩展
                bottom: '10%', // 减小底部边距，让图表向下扩展
                left: '15%',
                right: '10%',
            },
            yAxis: [
                {
                    name: '能耗量',
                    type: 'value',
                    axisLabel: {
                        formatter: '{value}m³',
                        color: '#fff'
                    },
                    splitLine: {
                        show: false,
                    }
                },
                {
                    name: '百分比',
                    type: 'value',
                    axisLabel: {
                        formatter: '{value}%',
                        color: '#fff'
                    },
                    splitLine: {
                        show: false,
                    }
                }
            ],
            series: [
                // 单根柱状图
                {
                    name: '昼间能耗',
                    type: 'bar',
                    stack: 'BB',
                    // data: waterData,
                    data: generateRandomData(7, 50),
                    barWidth: '30%',
                    tooltip: {
                        valueFormatter: function (value) {
                            return value + 'm³';
                        }
                    },
                },
                {
                    name: '夜间能耗',
                    type: 'bar',
                    stack: 'BB',
                    // data: totalUsage,
                    data: generateRandomData(7, 50),
                    barWidth: '30%',
                    tooltip: {
                        valueFormatter: function (value) {
                            return value + 'm³';
                        }
                    },
                },
                // 曲线
                {
                    name: '夜间能耗百分比',
                    type: 'line',
                    // data: dayUsage,
                    data: generateRandomData(7, 50),
                    lineStyle: {
                        width: 2,
                        type: 'solid'
                    },
                    tooltip: {
                        valueFormatter: function (value) {
                            return value + '%';
                        }
                    },
                    showSymbol: false,
                    smooth: true,
                    yAxisIndex: 1,
                }
            ]
        };
        chart.setOption(option);
    }
}
const getChartData = (electricityCount) => {
    const dates = [];
    const waterData = [];
    const dayUsage = [];
    const totalUsage = [];
    Object.entries(electricityCount || {}).forEach(([date, value]) => {
        dates.push(value.time);
        let dayWater = JSON.parse(value.day_usage);
        waterData.push(dayWater.total_water)
        let totalWater = JSON.parse(value.total_usage);
        let water = (totalWater.total_water - dayWater.total_water).toFixed(2)
        totalUsage.push(water);
        let arr = ((dayWater.total_water / totalWater.total_water) * 100).toFixed(2)
        if (arr == 'NaN') {
            arr = '0'
        }
        dayUsage.push(arr);
    });

    return { dates, dayUsage, waterData, totalUsage };
};
watch(() => props.resultData, (newVal) => {
    const { dates, dayUsage, waterData, totalUsage } = getChartData(newVal);
    if (newVal && chart == null) {
        nextTick(() => {
            initChart(dates, waterData, totalUsage, dayUsage);
        });
    }
    if (chart) {
        chart.setOption({
            xAxis: {
                data: dates,
            },
            series: [{
                name: '昼间能耗',
                stack: 'BB',
                tooltip: {
                    valueFormatter: function (value) {
                        return value + 'm³';
                    }
                },
                data: waterData,
            }, {
                name: '夜间能耗',
                stack: 'BB',
                tooltip: {
                    valueFormatter: function (value) {
                        return value + 'm³';
                    }
                },
                data: totalUsage,
            }, {
                name: '夜间能耗百分比',
                tooltip: {
                    valueFormatter: function (value) {
                        return value + '%';
                    }
                },
                data: dayUsage,
                type: 'line',
                yAxisIndex: 1,
            }],
        })
    }
}, { deep: true, immediate: true } // 开启深度监听
)
onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
    if (chart) {
        chart.dispose();
    }
});
</script>

<style lang="scss">
._divider {
    height: 1px;
    border: 1px dashed #168cdb;
    flex: 1;
    margin: 0 10px;
}

._consume {
    display: flex;
    flex-direction: column;

    &_mains {
        margin: 10px 10px;
        flex: 1;
        display: flex;

        &_item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;

            &_name {
                width: 30px;
                height: 30px;
                background: url("@/assets/images/content_circle_num.png");
                background-size: 100% 100%;
                background-position: center;
                background-repeat: no-repeat;
                // animation: scanning 4s linear infinite;
                border: 1px solid red;
            }

            &_flag {
                display: flex;
                align-items: center;
                gap: 3px;

                &_item {
                    width: 30px;
                    height: 30px;
                    border: 3px dashed #168cdb;
                    box-sizing: border-box;
                    background: #0e6ead;
                    color: #fff;
                    border-radius: 50%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    font-size: 14px;
                }
            }
        }

        &_item:hover {
            cursor: pointer;
            background-image: linear-gradient(to right, #168cdb, transparent);
        }
    }
}
</style>