<template>
    <div style="height: 100%;">
        <input type="text" @focus="focusFun" @blur="blurFun">
        <div id="container" style="min-height:500px;"></div>
        <div style="text-align: center;margin-top: 20px;">{{ computedData }}</div>
        <n-modal v-model:show="showModal">
            <n-card style="width: 600px" title="超标数据">
                <template #header-extra>
                    <div style="cursor: pointer;" @click="showModal = false">关闭</div>
                </template>
                <n-table :bordered="false" :single-line="false">
                    <thead>
                        <tr>
                            <th>编号</th>
                            <th>时间</th>
                            <th>备注</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(item,index) in tableData" :key="index">
                            <td>{{item.ids}}</td>
                            <td>{{item.times}}</td>
                            <td>当前温度：{{item.t}}</td>
                        </tr>
                    </tbody>
                </n-table>
            </n-card>
        </n-modal>
    </div>
</template>

<script setup>

import Highcharts from 'highcharts/highstock.src.js';
import emitter from "@/plugin/bus";
// const emit = defineEmits(['submit']);
import { TimeData } from '@/plugin/timeFun';
import { computed, onBeforeUnmount, reactive, watch, ref, nextTick } from "vue";
import { useMessage } from "naive-ui";
import { useStore } from 'vuex'
const message = useMessage()
const showModal = ref(false)
const popData = defineProps({
    dataList: {
        type: Array,
        default: () => [],
    }
})

const plotLinesData = reactive({
    tBottom: 2,
    tTop: 8
})
const store = useStore()
const plot = computed(() => store.state.plotLineList)


const dataObj = reactive({
    chartOptions: null,
    data: []
})


const higFun = () => {
    dataObj.chartOptions = new Highcharts.stockChart('container', {
        chart: {
            zoomType: "x",
            events: {
                selection(event) {
                    console.log('框选', event)
                    if (event.xAxis) {
                        emitter.emit("onSelectionTime", event.xAxis);
                        emit("setTimeFun", event.xAxis)
                    }
                },
            },
            // zoomType: 'x',
            panning: this, //禁用放大 
            pinchType: '', //禁用手势操作
            // zoomType: '',
            panKey: 'shift',
        },
        xAxis: {
            type: 'datetime',
            // labels: {
            //     format: '{value:%Y-%m-%d %H:%M:%S}',
            // },
        },
        time: {
            useUTC: false
        },
        boost: {
            useGPUTranslations: true
        },

        // tooltip: {
        //     xDateFormat: '%Y-%m-%d %H:%M:%S',

        // },
        tooltip: {
            formatter: function () {
                var s = TimeData(this.points[0].x) + '<br/>';
                const arr = this.points.sort((a, b) => {
                    return b.y - a.y // 从小到大 -> a.age - b.age
                })
                for (let i in this.points) {
                    s += '<br/>' + `<div style='color:${this.points[i].series.color}'>` + this.points[i].series.name + ': ' + (this.points[i].y).toFixed(1) + '°C</div>';
                }
                return s;
            },
            shared: false
        },

        yAxis: {
            opposite: false, //设置y轴提示在左边
            title: {
                // text: '温度℃'
            },
            plotLines: [{
                color: '#FF1D00', //线的颜色，定义为红色
                dashStyle: 'DashDot', //默认值，这里定义为实线
                value: plotLinesData.tTop, //定义在那个值上显示标示线，这里是在x轴上刻度为3的值处垂直化一条线  
                width: 2, //标示线的宽度，2px
                label: {
                    text: `上限（${plotLinesData.tTop}°C`, //标签的内容
                    align: 'right', //标签的水平位置，水平居左,默认是水平居中center
                    // x: 10 //标签相对于被定位的位置水平偏移的像素，重新定位，水平居左10px
                }
            }, {
                color: '#FF1D00', //线的颜色，定义为红色
                dashStyle: 'DashDot', //默认值，这里定义为实线
                value: plotLinesData.tBottom, //定义在那个值上显示标示线，这里是在x轴上刻度为3的值处垂直化一条线  
                width: 2, //标示线的宽度，2px
                label: {
                    text: `下限（${plotLinesData.tBottom}°C`, //标签的内容
                    align: 'right', //标签的水平位置，水平居左,默认是水平居中center
                    // x: 10 //标签相对于被定位的位置水平偏移的像素，重新定位，水平居左10px
                }
            }]

        },
        plotOptions: {
            series: {
                turboThreshold: 0, //性能阈值检查,默认值为1000，当数据量超过这个值就会报错；如果需要关掉性能阈值检查，可以将此参数设置为 0
                // marker: {//鼠标放上去的取消小圆点
                //     radius: 6, //曲线点半径，默认是4
                //     smooth:3,
                //     symbol: 'triangle' //曲线点类型：”circle”, “square”, “diamond”, “triangle”,”triangle-down”，默认是”circle”
                // }
                marker: {
                    enabled: true,
                    radius: 3,
                    // symbol: 'url(https://www.highcharts.com/samples/graphics/sun.png)'
                },

            },
        },

        legend: {
            enabled: true,
        },

        accessibility: {
            enabled: false,
        },
        rangeSelector: {
            buttons: [], // 不显示左边的zoom
            selected: 1,
            inputEnabled: false // 不显示日期输入框
        },
        boost: {
            useGPUTranslations: true,
            seriesThreshold: 5,
        },

        scrollbar: {
            enabled: false,
        },
        exporting: {//右上角下载
            enabled: false
        },
        credits: {//右下角水印
            enabled: false
        },
        series: dataObj.data
    })
}


emitter.on("onFormData", (val) => {
    console.log("打印11111：", val);
});
//设置就展示
emitter.on("onMessage", (val) => {
    console.log('初值1111', val,popData.dataList)
    plotLinesData.tTop = val.tTop != '' ? val.tTop : null
    plotLinesData.tBottom = val.tBottom != '' ? val.tBottom : null  
    standardFun()   
    nextTick(() => {   
            
        higFun()
    })
});
const tableData = ref([])
//整理超标列表
const standardFun = ()=>{
    tableData.value = []
    for (const iterator of popData.dataList) {
        if(plotLinesData.tBottom==null && plotLinesData.tTop!=null){//设置了上限
            const b = iterator.data.find(item => plotLinesData.tTop<=item[1])
            if(b!=undefined){
                var obj = {
                    ids:b[4],
                    times:TimeData(b[0]),
                    t:b[1]
                }
                tableData.value.push(obj)
            }
            if(tableData.value.length!=0) showModal.value = true
        }else if(plotLinesData.tBottom!=null && plotLinesData.tTop==null){//只设置了下限
            
            const b = iterator.data.find(item => plotLinesData.tBottom>=item[1])
            if(b!=undefined){
                var obj = {
                    ids:b[4],
                    times:TimeData(b[0]),
                    t:b[1]
                }
                tableData.value.push(obj)
            }
            if(tableData.value.length!=0) showModal.value = true
        }else if(plotLinesData.tBottom!=null && plotLinesData.tTop!=null){//上下限都有
            
            const b = iterator.data.find(item => plotLinesData.tBottom>=item[1] || plotLinesData.tTop<=item[1])
            if(b!=undefined){
                var obj = {
                    ids:b[4],
                    times:TimeData(b[0]),
                    t:b[1]
                }
                tableData.value.push(obj)
            }
            if(tableData.value.length!=0) showModal.value = true
            
        }else{//没有设置
            showModal.value = false
        }
    }
}
//关闭
onBeforeUnmount(() => {
    emitter.off("onMessage");
});
const refData = ref(null)


const computedData = computed(() => {
    // console.log('计算属性',popData.dataList)
    if (popData.dataList.length != 0) {
        return computedDataFun()
    } else {
        return ''
    }
})
const computedDataFun = () => {
    let arr = popData.dataList
    let mapData = []
    for (const key of arr) {
        for (let i = 0; i < key.data.length; i++) {
            mapData.push(key.data[i][1])
        }
    }
    if (mapData.length == 0) {
        message.error('哎呀，没有可展示的数据哦')
        return
    }
    //求和
    let num = mapData.reduce((n, m) => n + m);//求和
    //最大值
    let maxData = Math.max(...mapData)
    //最小值
    let minData = Math.min(...mapData)
    //平均值
    let pingjun = (num / mapData.length).toFixed(1)

    return `最大值${maxData}，最小值${minData}，平均值${pingjun}`
}
watch(() => store.state.focuDatas, (newValue) => {
    if (newValue != null) {
        dataObj.chartOptions.zoomBool = true
    } else {
        dataObj.chartOptions.zoomBool = false
    }
})
watch(() => popData.dataList, (newValue) => {
    console.log('123456', newValue)
    // if(dataObj.chartOptions)dataObj.chartOptions.__proto__.__proto__.destroy()
    dataObj.data = newValue
    
    nextTick(() => {
        console.log('89',dataObj.chartOptions) 
        higFun()
    })
}, { deep: true, immediate: false })

const emit = defineEmits(['setTimeFun']);
// 图表配置
const chartOptions1 = reactive({
    xAxis: {
        type: 'datetime',
        // labels: {
        //     format: '{value:%Y-%m-%d %H:%M:%S}',
        // },
    },
    time: {
        useUTC: false
    },
    boost: {
        useGPUTranslations: true
    },

    // tooltip: {
    //     xDateFormat: '%Y-%m-%d %H:%M:%S',

    // },
    tooltip: {
        formatter: function () {
            var s = TimeData(this.points[0].x) + '<br/>';
            for (let i in this.points) {
                s += '<br/>' + `<div style='color:${this.points[i].series.color}'>` + this.points[i].series.name + ': ' + (this.points[i].y).toFixed(1) + '°C</div>';
            }
            return s;
        },
        shared: false
    },

    yAxis: {
        opposite: false, //设置y轴提示在左边
        title: {
            // text: '温度℃'
        },
        plotLines: [{
            color: '#FF1D00', //线的颜色，定义为红色
            dashStyle: 'DashDot', //默认值，这里定义为实线
            value: plotLinesData.hTop, //定义在那个值上显示标示线，这里是在x轴上刻度为3的值处垂直化一条线  
            width: 2, //标示线的宽度，2px
            label: {
                text: `上限（${plotLinesData.hTop}Rh）`, //标签的内容
                align: 'right', //标签的水平位置，水平居左,默认是水平居中center
                // x: 10 //标签相对于被定位的位置水平偏移的像素，重新定位，水平居左10px
            }
        }, {
            color: '#FF1D00', //线的颜色，定义为红色
            dashStyle: 'DashDot', //默认值，这里定义为实线
            value: plotLinesData.hBottom, //定义在那个值上显示标示线，这里是在x轴上刻度为3的值处垂直化一条线  
            width: 2, //标示线的宽度，2px
            label: {
                text: `下限（${plotLinesData.hBottom}Rh）`, //标签的内容
                align: 'right', //标签的水平位置，水平居左,默认是水平居中center
                // x: 10 //标签相对于被定位的位置水平偏移的像素，重新定位，水平居左10px
            }
        }]

    },
    plotOptions: {
        series: {
            turboThreshold: 0, //性能阈值检查,默认值为1000，当数据量超过这个值就会报错；如果需要关掉性能阈值检查，可以将此参数设置为 0
            // marker: {//鼠标放上去的取消小圆点
            //     radius: 6, //曲线点半径，默认是4
            //     smooth:3,
            //     symbol: 'triangle' //曲线点类型：”circle”, “square”, “diamond”, “triangle”,”triangle-down”，默认是”circle”
            // }
            marker: {
                enabled: true,
                radius: 3,
                // symbol: 'url(https://www.highcharts.com/samples/graphics/sun.png)'
            },

        },
    },

    legend: {
        enabled: true,
    },

    accessibility: {
        enabled: false,
    },
    rangeSelector: {
        buttons: [], // 不显示左边的zoom
        selected: 1,
        inputEnabled: false // 不显示日期输入框
    },
    boost: {
        useGPUTranslations: true,
        seriesThreshold: 5,
    },

    scrollbar: {
        enabled: false,
    },
    exporting: {//右上角下载
        enabled: false
    },
    credits: {//右下角水印
        enabled: false
    },
    chart: {
        // zooming: {
        //     singleTouch: false,
        //     resetButton: {},
        //     type:'x',
        // },

        // panning: false, //禁用放大
        // pinchType:'x', //禁用手势操作
        zoomType: "x",
        panKey: 'shift',
        events: {

            selection(event) {
                // console.log('框选', event)
                if (event.xAxis) {
                    emitter.emit("onSelectionTime", event.xAxis);
                    emit("setTimeFun", event.xAxis)
                }
            },
        },
    },

    series: [],
})

</script>
