<template>
    <div class="barCharts">
        <div class="operation" v-if="props.showLegend">
            <el-checkbox
                :model-value="showAll"
                :indeterminate="indeterminate"
                @change="(val)=>HandleCheckAllOrNot(val)"
            
            >
            显示全部
            </el-checkbox>
        </div>
        <div class="render_bar_charts" ref="chartsRef" id="charts">
        </div>
    </div>

</template>

<script setup lang="ts">
import {ref,onMounted, watch} from 'vue'
import * as echarts from 'echarts';

const props = defineProps({
    chartData:{
        required:true,
        type:{
            xAxis:Array,
            series:Array,
            yAxisLabelFormater:Function,
            tooltipFormater:Function,
        }
    },
    randomActiveIndex:{
        type:Number,
        required:true
    },
    showLegend:{
        type:Boolean,
        default:false
    },
    maxLabel:{
        type:Number,
        default:5
    }
})

const chartsRef = ref()
const myChart = ref()

const showAll = ref(true)
const indeterminate = ref(false)
const selectedLegendList = ref([])

const HandleCheckAllOrNot = (val)=>{
    console.log('当前的变更值',val)
    showAll.value = val
    indeterminate.value = false
    if(val){
        myChart.value.dispatchAction({
            type: 'legendAllSelect',
        });
    }else{
        // 第一次点击没有图例值 需要调用反选
        if(selectedLegendList.value?.length > 0){
            selectedLegendList.value.map(item=>{
                myChart.value.dispatchAction({
                    type: 'legendUnSelect',
                    name:item
                })
            })
        }else{
            // 反选
            myChart.value.dispatchAction({
                type: 'legendInverseSelect',
            })
        }
    }
}


const baseOption = {
    grid:{
        id:'grid',
        width:'100%',
        left:0,
        top:props.showLegend ?  '16%' : '7%',
        right:0,
        bottom:30,
    },
    legend: {
        id:'legend',
        show:props.showLegend,
        top: '0%',
        left: 92,
        itemGap:15,
        itemWidth:20,
        padding:1,
        itemHeight:10,
        formatter:function (name) {
            return name;
        },
        textStyle:{
            fontSize:12,
        },
    },
    title: {
        id:'title',
        text: ''
    },
    color:['#5470C6','#3BA272','#FAC858','#995FB3','#EE6666','#72C0DD','#90CB75','#EA7ACB','#FC8451','#65789B',
          '#178BD3','#26A616','#A6129E','#D3A141','#234098','#047640','#B43535','#848BDC','#D6AF83','#84313D'],
    tooltip:{
        trigger: 'item',
        borderWidth:0,
        showContent:true,
        textStyle:{
            color:'#666'
        }
    },
    xAxis:{
        id:'xAxis',
        axisPointer:{
            show:true,
            type: 'shadow',
            label:{
                show:false
            },
            shadowStyle:{
                color:'rgba(46, 100, 250,0.05)'
            },
        },
        axisLine: {
            lineStyle: {
                color: '#666',
            }
        },
        axisLabel: {
            width:100,
            interval:0,
            overflow:'truncate',
            color: '#666',
        },
        data: [], // 初始为空，后续动态赋值
    },
    yAxis: {
        id:'yAxis',
        type: 'value',
        axisLine: {
            show: false
        },
        axisTick: {
            show: false
        },
        // 分割线
        splitLine: {
            lineStyle: {
                type: 'solid',
                color: '#E4E7ED'
            }
        },
        // 斑马纹
        splitArea: {
            show: true,
            areaStyle: {
            color:['#fafafa','transparent'],
            }
        },
        axisLabel: {
            color: '#666',
        }
    },
    animation:false,
    dataZoom:[
        {
            type: 'slider',
            id:'slider',  // 唯一标识 
            show: props.chartData?.dataset?.source ? props.chartData?.dataset?.source?.length > props.maxLabel : props.chartData?.series[0]?.data?.length > props.maxLabel,
            backgroundColor:'rgba(255,255,255,0)',
            dataBackground:{
                lineStyle:{
                    opacity:0,
                },
                areaStyle:{
                    opacity:0,
                }
            },
            selectedDataBackground:{
                lineStyle:{
                    opacity:0,
                },
                areaStyle:{
                    opacity:0,
                },
            },
            borderColor:'rgba(255,255,255,0)',
            fillerColor:'rgba(176, 199, 249,0)',

            xAxisIndex: [0],
            // start: 1,
            // end: 35,

            // minSpan:20,
            minValueSpan:(props.maxLabel - 1),
            maxValueSpan:(props.maxLabel - 1),

            showDetail:false,
            height:7,
            bottom:0,
            throttle:0,
            // brushSelect:false,
            moveHandleStyle:{
                color:'#b0c7f9'
            },
            handleStyle:{
                opacity:0
            }
        },
        {
            type: 'inside',
            id:'inside',
            xAxisIndex: [0],

            // minSpan:20,
            minValueSpan:(props.maxLabel - 1),
            maxValueSpan:(props.maxLabel - 1),
        },
  
    ]
}

// baseOption  基础固定配置
// baseInheritOpt  基础实际配置，可能为空
const UpdateChart = (chartData,baseInheritOpt) =>{
    let tmpXAxis = chartData?.xAxis?.length > 0 ? chartData?.xAxis : ['暂无数据']
    let dynamicOption = {
        xAxis: {
            ...baseOption.xAxis,
            data: [...tmpXAxis],
        },
        series: chartData?.series?.map(item=>{
            return {
                type:'bar',
                barWidth: 30,
                barGap:0,
                ...item,
                label: {
                    show: true,
                    position: 'top',
                    color:'#666',
                    ...item?.label,
                },
            }
        }),
        dataset:chartData?.dataset,
    }
    myChart.value.setOption({
        ...baseOption,
        dataZoom:[
            {
                ...(baseOption?.dataZoom?.[0]),
                show:chartData?.dataset?.source ? chartData?.dataset?.source?.length > props.maxLabel :chartData?.series[0]?.data?.length > props.maxLabel,
            },
            {
                 ...(baseOption?.dataZoom?.[1])
            }
        ],

        tooltip:{
            ...baseOption.tooltip,
            formatter: chartData?.tooltipFormater ?  chartData?.tooltipFormater : function (params) {
                const {name,seriesName,value,marker} = params
                return name + '<br/>' + marker + seriesName + `<span style=\"margin-left:10px;\">${value}</span>` ;
            }
        },

        yAxis:{
            ...baseOption.yAxis,
            axisLabel:{
                ...baseOption.yAxis.axisLabel,
                formatter:chartData?.yAxisLabelFormater ? chartData?.yAxisLabelFormater : '{value}' 
            }
        },
        ...dynamicOption
       
    },{notMerge:true});
}

const HandleInitChart = ()=>{
    // 基于准备好的dom，初始化echarts实例
    myChart.value = echarts.init(chartsRef.value);
    UpdateChart(props.chartData,baseOption)

    // 系统默认 onMounted后就开始监听 dataZoom事件变化，此处onMounted后父容器无高度，报错 ？？？
    //需要手动 动态监听 dataZoom的位置
    myChart.value.on('dataZoom', function (event) {
        console.log('缩放区域触发了---:', event);
        // event 有 batch 是 inside  内部 滚动，
        // event 无 batch 是  鼠标拖拽
        let chartData = props.chartData
        let tmpXAxis = chartData?.xAxis?.length > 0 ? chartData?.xAxis : ['暂无数据']
        let dynamicOption = {
            xAxis: {
                ...baseOption.xAxis,
                data: [...tmpXAxis],
            },
            series: chartData?.series?.map(item=>{
                return {
                    type:'bar',
                    barWidth: 30,
                    barGap:0,
                    ...item,
                    label: {
                        show: true,
                        position: 'top',
                        color:'#666',
                        ...item?.label,
                    },
                }
            }),
            dataset:chartData?.dataset,
        }
        myChart.value.setOption({
            ...baseOption,
            dataZoom:[
                {
                    ...(baseOption?.dataZoom?.[0]),
                    show:chartData?.dataset?.source ? chartData?.dataset?.source?.length >props.maxLabel :chartData?.series[0]?.data?.length > props.maxLabel,
                    start: event?.batch ? event?.batch[0].start : event?.start,
                    end:  event?.batch ? event?.batch[0].end : event?.end,
                },
                {
                    ...(baseOption?.dataZoom?.[1]),
                    start: event?.batch ? event?.batch[0].start :  event?.start,
                    end: event?.batch ? event?.batch[0].end : event?.end,
                }
            ],

            tooltip:{
                ...baseOption.tooltip,
                formatter: chartData?.tooltipFormater ?  chartData?.tooltipFormater : function (params) {
                    const {name,seriesName,value,marker} = params
                    return name + '<br/>' + marker + seriesName + `<span style=\"margin-left:10px;\">${value}</span>` ;
                }
            },

            yAxis:{
                ...baseOption.yAxis,
                axisLabel:{
                    ...baseOption.yAxis.axisLabel,
                    formatter:chartData?.yAxisLabelFormater ? chartData?.yAxisLabelFormater : '{value}' 
                }
            },
            ...dynamicOption
        
        },{notMerge:true});

    });


    myChart.value.on('legendselectchanged', function (params) {
        console.log('图例状态切换了',params);
        selectedLegendList.value = Object.entries(params.selected).map(itm=>itm[0])

        let selectedStatus = Object.values(params.selected)
        let length = selectedStatus.length
        let selectedLegendStatus =  selectedStatus.filter(item=>item === true)
        let unSelectedLegend =  selectedStatus.filter(item=>item === false)

        if(selectedLegendStatus.length === length || unSelectedLegend.length ===  length){
            indeterminate.value = false
            if(selectedLegendStatus.length === length){
                showAll.value = true
            }else{
                showAll.value = false
            }
        }else{
            indeterminate.value = true
        }
    });
}

onMounted(async ()=>{
    HandleInitChart()
})

watch(()=>props.randomActiveIndex,(newVal)=>{
    // 监听到父组件页面的容器尺寸变化后，要重新init
    if(myChart.value){
        myChart.value.dispose();
        myChart.value = null
    }
    HandleInitChart()
})



watch(()=>props.chartData,(newVal)=>{
    // console.log('数据变化了')
    // // 数据变换后要重新渲染
    // UpdateChart(newVal,{})

    if(myChart.value){
        myChart.value.dispose();
        myChart.value = null
    }
    HandleInitChart()


},{deep:true})

</script>


<style  lang="scss" scoped>

.render_bar_charts{
    position: relative;
    width: 100%;
    height: 270px;
}

.operation{
    position: absolute;
    :deep(.el-checkbox){
        display: flex;
        align-items: center;
        height: auto !important;
        .el-checkbox__label{
            font-size: 12px !important;
        }
        color:#333333;
    }
}

</style>
