<template>
    <div class="go-border-box">
       <img src="./assets/title.svg" class="svg" />
        <div class="header-title">报警统计</div>
        <v-chart ref="vChartRef" autoresize :init-options="initOptions" :theme="themeColor" :option="option"></v-chart>
         <!-- 使用新的下拉选择器组件 -->
        <CustomSelect 
            :options="option.dateTime.dataset" 
            :selectedValue="option.dateTime.selectValue"
            @change="handleSelectChange"
        />
    </div>
    
</template>

<script setup lang="ts">
import { computed, PropType, onMounted, watch, ref, onUnmounted } from 'vue'
import VChart from 'vue-echarts'
import { useCanvasInitOptions } from '@/hooks/useCanvasInitOptions.hook'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart } from 'echarts/charts'
import { mergeTheme } from '@/packages/public/chart'
import config, { includes } from './config'
import { useChartDataFetch } from '@/hooks'
import { useChartEditStore } from '@/store/modules/chartEditStore/chartEditStore'
import { DatasetComponent, GridComponent, TooltipComponent, LegendComponent, GraphicComponent } from 'echarts/components'
import CustomSelect from './select.vue'
import dataJson from './data.json'

const props = defineProps({
    themeSetting: {
        type: Object,
        required: true
    },
    themeColor: {
        type: Object,
        required: true
    },
    chartConfig: {
        type: Object as PropType<config>,
        required: true
    }
})

const initOptions = useCanvasInitOptions(props.chartConfig.option, props.themeSetting)

use([DatasetComponent, CanvasRenderer, PieChart, GridComponent, TooltipComponent, LegendComponent, GraphicComponent])

const option = computed(() => {
    return mergeTheme(props.chartConfig.option, props.themeSetting, includes)
})

function calculateTotal(data: any) {
    if (!data || !data.source) return 0
    return data.source.reduce((total: number, item: any) => {
        return total + (item[data.dimensions[1]] || 0)
    }, 0)
}

function calculatePercentage(value: number, total: number) {
    return total > 0 ? ((value / total) * 100).toFixed(1) : '0.0'
}

const updateChartData = (newData: any) => {
    if (!newData) return

    const total = calculateTotal(newData)
    if (props.chartConfig.option.graphic?.[0]) {
        props.chartConfig.option.graphic[0].style.text = total.toString()
    }

    // 统一显示为 “名称  百分比”
    props.chartConfig.option.legend.formatter = (name: string) => {
        const item = newData.source.find((it: any) => it[newData.dimensions[0]] === name)
        if (!item) return null
        const val = item[newData.dimensions[1]] ?? 0
        let p = calculatePercentage(val, total)
        // return `{row|${name}    ${p}%}`
        if(Number(p)<10){
            p=' '+p
        }
        return `{name|${name}}{value|${p}}{unit|%}`;
    }

    // 每行独立渐变背景
    props.chartConfig.option.legend.textStyle = {
        color: '#fff',
        rich: {
            name: {
                width: 80,
                padding: [8, 0, 8, 10],
                color: '#999',
                backgroundColor: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [
                        { offset: 0, color: 'rgba(58, 160, 255, 0)' },
                        { offset: 0.5, color: 'rgba(58, 160, 255, 0.05)' },
                        { offset: 1, color: 'rgba(58, 160, 255, 0.15)' }
                    ]
                },
            },
            value: {
                width: 30,
                padding: [8, 0, 8, 0],
                textAlign: 'right',
                fontFamily: 'monospace',
                backgroundColor: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [
                        { offset: 0, color: 'rgba(58, 160, 255, 0)' },
                        { offset: 0.5, color: 'rgba(58, 160, 255, 0.05)' },
                        { offset: 1, color: 'rgba(58, 160, 255, 0.15)' }
                    ]
                },
            },
            unit: {
                width: 10,
                padding: [8, 10, 8, 0],
                textAlign: 'left',
                color: '#999',
                backgroundColor: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [
                        { offset: 0, color: 'rgba(58, 160, 255, 0)' },
                        { offset: 0.5, color: 'rgba(58, 160, 255, 0.05)' },
                        { offset: 1, color: 'rgba(58, 160, 255, 0.15)' }
                    ]
                },
            },
        }
    }

    const totalValue=newData.source.reduce((total: number, item: any) => {
        return total + (item.value || 0)
    }, 0)
    props.chartConfig.option.series[props.chartConfig.option.series.length-1].label.formatter=`{a|${totalValue}}\n\n{b|总数}`
}

watch(
    () => props.chartConfig.option.dataset,
    newData => {
        if (newData) {
            props.chartConfig.option.dataset = newData
            updateChartData(newData)
        }
    },
    { deep: false, immediate: true }
)

const { vChartRef } = useChartDataFetch(props.chartConfig, useChartEditStore, (newData: any) => {
    props.chartConfig.option.dataset = newData
    updateChartData(newData)
})

onMounted(() => {
    updateChartData(props.chartConfig.option.dataset)
})

// 处理下拉选择器变化
const handleSelectChange = (value: any) => {
    props.chartConfig.option.dateTime.selectValue = value
}
</script>

<style lang="scss" scoped>
@include go(border-box) {
  position: relative;
  border-radius: 5px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  height: 100%;
  padding: 0;
  // 不渐变
  // background-color: #0E121B;
  // 渐变
  background: linear-gradient(to top,
      rgba(14, 18, 27, 1) 0%,
      rgba(14, 18, 27, 0.6) 100%);

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    border-radius: 5px;
    padding: 2px;
    /* 边框宽度 */
    background: linear-gradient(to top,
        rgba(128, 128, 128, 0.3),
        rgba(128, 128, 128, 0));
    -webkit-mask:
      linear-gradient(#fff, #fff) content-box,
      linear-gradient(#fff, #fff);
    -webkit-mask-composite: xor;
    mask-composite: exclude;
    pointer-events: none;
  }
}

.header-title{
    position: absolute;
    top: 0;
    height: 45px;
    line-height: 45px;
    left: 80px;
    font-size: 16px;
    font-weight: bold;
    color: #eee;
    font-style: italic;
    text-shadow: 0 0 10px #00E5FF;
    white-space: nowrap;
}


.svg {
  width: 100%;
  height: 45px;
}
</style>