<template>
    <div class="temperature">
        <el-container class="containerPart">
            <el-aside class="defaultAside">
                <el-main class="treeMain">
                    <el-tree
                        style="max-width: 600px;margin-top: 2.2%"
                        ref="equipTreeRef"
                        :data="deviceData"
                        :props="defaultProps"
                        node-key="id"
                        @node-click="handleNodeClick"
                        :default-expanded-keys="defaultExpandedKeys"
                    />
                </el-main>
            </el-aside>
            <el-container class="defaultMainContainer">
                <div class="temperature-chart" ref="temperatureChartRef"></div>
            </el-container>
        </el-container>
    </div>
</template>

<script setup lang="ts">
import {nextTick, onActivated, onMounted, onUnmounted, reactive, ref} from 'vue'
import {equipList,getTemperatureLimitByDeviceId,getsnapshotData} from "/@/api/backend/temperature/request.ts";
import * as echarts from "echarts";
import {useEventListener } from '@vueuse/core'
import {dayjs} from "element-plus";
const defaultProps = {
    children: 'children',
    label: 'name'
}
const devicelistData = reactive({
    objectType: 10002,
})
const deviceData = ref(
    [{
    id: 0,
    name: "风机列表",
    children: []
}]
)
const defaultExpandedKeys = ref([0]);
const deviceId=ref()
const equipTreeRef = ref()
const deviceQuery = (data: any) => {
    equipList(data).then((res) => {
        deviceData.value[0].children = res.data
        nextTick(() => {
            deviceId.value=res.data[0]?.id
            equipTreeRef.value?.setCurrentKey(deviceData.value[0].children[0].id!, true)
            getChartData({id:deviceId.value})
        })
    })
}
const handleNodeClick = (data: any) => {
    deviceId.value=data.id
    state.charts.temperatureChart.clear()
    getChartData({id:deviceId.value})
}

const state: {
    charts: { temperatureChart: any; }
    remark: string
    workingTimeFormat: string
    pauseWork: boolean
} = reactive({
    charts: { temperatureChart: null },
    remark: 'dashboard.Loading',
    workingTimeFormat: '',
    pauseWork: false,
})
const temperatureChartRef = ref()

const temperatureData:any ={
    name: [],
    values: [],
    limit1High: [],
    limit1Low: [],
    limit2High: [],
    limit2Low: []
}
const inittemperatureChar = () => {
    const temperatureChart = state.charts.temperatureChart ?? echarts.init(temperatureChartRef.value as unknown as HTMLElement)
    const option = {
        grid: {
            show:true,
            top: 50,
            right: 23,
            bottom: 10,
            left: 25,
            containLabel: true,
            borderColor:'transparent',
            backgroundColor:'rgba(254,55,49,0.20)'
        },
        // tooltip: {
        //     trigger: 'axis',
        //     axisPointer: {
        //         type: 'shadow',
        //     },
        // },
        xAxis: {
            type: 'value',
            interval: 10,
            axisLine: {
                show: true,
                lineStyle: {
                    color: '#ffffff',
                    width: 1,
                    type: 'solid',
                },
            },
            axisLabel: {
                //x轴文字的配置
                show: true,
                textStyle: {
                    color: '#4E5969',
                },
                interval: 10,
                //rotate: 45
            },
            splitLine: {
                //分割线配置
                show: true,
                lineStyle: {
                    color: '#ffffff',
                },
            }
        },
        yAxis: [
            {
                type: 'category',
                nameTextStyle: {
                    color: '#4E5969',
                },
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: '#ffffff',
                        width: 0,
                        type: 'solid',
                    },
                },
                axisLabel: {
                    //x轴文字的配置
                    show: true,
                    textStyle: {
                        color: '#4E5969',
                    },
                },
                axisTick: { show: false },
                splitLine: {
                    interval: 50,
                    lineStyle: {
                        type: 'solid',
                        color: '#ffffff',
                    },
                },
                data: temperatureData.name
            },

        ],
        series: [
            {
                type: 'bar',
                barWidth: 40,
                itemStyle: {
                    color: '#0064AA',
                    barBorderRadius: 2
                },
                label:{
                    show:true,
                    position:'insideRight',
                    color:'#ffffff'
                },
                data: temperatureData.values,
                z:3
            },
            {
                name: '上限值',
                type: 'bar',
                barWidth: 40,
                barGap: '-100%',
                data: temperatureData.limit1High,
                itemStyle: {
                    color: '#ccecea',
                },
                z:2
            },
            {
                name: '下限值',
                type: 'bar',
                barWidth: 40,
                barGap: '-100%',
                data: temperatureData.limit1Low,
                itemStyle: {
                    color: '#ccecea',
                },
                z:2
            },
            {
                name: '上上限值',
                type: 'bar',
                barWidth: 40,
                barGap: '-100%',
                itemStyle: {
                    color: '#fff0cc',
                },
                data: temperatureData.limit2High,
                z:1
            },
            {
                name: '下下限值',
                type: 'bar',
                barWidth: 40,
                barGap: '-100%',
                data: temperatureData.limit2Low,
                itemStyle: {
                    color: '#fff0cc',
                },
                z:1
            },

        ],
    }
    temperatureChart.setOption(option)
    state.charts.temperatureChart = temperatureChart
}
const attributesCode:any[]=[]
const getChartData = (data: any) => {
    console.log(JSON.stringify(data))
    getTemperatureLimitByDeviceId(data).then((res) => {
        debugger
        if (res.code=='200') {
            temperatureData.name=[]
            temperatureData.values=[]
            temperatureData.limit1High=[]
            temperatureData.limit1Low=[]
            temperatureData.limit2High=[]
            temperatureData.limit2Low=[]
            res.data.forEach((item,index) => {
                temperatureData.name.push(item.measPointName)
                attributesCode.push(item.measPointCode)
                if(item.limit1Enable){
                    temperatureData.limit1High.push(item.limit1High)
                    temperatureData.limit1Low.push(item.limit1Low)
                }
                if(item.limit2Enable){
                    temperatureData.limit2High.push(item.limit2High)
                    temperatureData.limit2Low.push(item.limit2Low)
                }
            })
            getTemperaData([{deviceId:data.id,attributes:attributesCode}])
        }
    })
}
const getTemperaData = (data:any) => {
    getsnapshotData(data).then((res) => {
        if (res.code == 200) {
            const data = res.data[deviceId.value]
            const rangeKeys = Object.keys(data)
            temperatureData.values=[]
            attributesCode.forEach((attribute, index) => {
                if (attribute) {
                    const attributeLower = attribute.toLowerCase();
                    const foundKey = Object.keys(rangeKeys).find(key => rangeKeys[key] === attributeLower);
                    if (foundKey) {
                        const value=data[rangeKeys[foundKey]]
                        const formattedValue=value !== undefined ? (value % 1 === 0 ? value : value.toFixed(2)) : '-';
                        temperatureData.values = temperatureData.values.concat({value:formattedValue,itemStyle:{color:'#0064AA'}});
                    }
                }
            });
            const values = temperatureData.values
            const limit1High = temperatureData.limit1High
            const limit1Low = temperatureData.limit1Low
            const limit2High = temperatureData.limit2High
            const limit2Low = temperatureData.limit2Low
            inittemperatureChar()
            seriesStyle(values, limit1High, limit1Low, limit2High, limit2Low)
        }
    })
}

const seriesStyle= (values, limit1High, limit1Low, limit2High, limit2Low) =>{
    const option = state.charts.temperatureChart.getOption();
    const series = option?.series?.[0];
    values.forEach((item,index) => {
        if (Number(item.value) > Number(limit1High[index]) || Number(item.value) < Number(limit1Low[index])) {
            //debugger
            item.itemStyle.color= 'red'
            series.data[index].itemStyle = { color: 'red' };
        } else if (Number(item.value) > Number(limit2High[index]) || Number(item.value) < Number(limit2Low[index])) {
            item.itemStyle.color= 'red'
            series.data[index].itemStyle = { color: 'red' };
        } else {
            item.itemStyle.color= '#0064AA'
            series.data[index].itemStyle = { color: '#0064AA' };
        }
    })
        state.charts.temperatureChart.setOption(option);

}
let autoUpdateTimer: any = null
const autoUpdate = () => {
    if (!autoUpdateTimer) {
        autoUpdateTimer = setInterval(() => {
            getChartData({id:deviceId.value})
        }, 2000)
    }
}
const echartsResize = () => {
    nextTick(() => {
        const chartKeys = Object.keys(state.charts) as Array<keyof typeof state.charts>
        chartKeys.forEach((key) => {
            state.charts[key].resize()
        })
    })
}
onActivated(() => {
    echartsResize()
})

onMounted(() => {
    deviceQuery(devicelistData)
    autoUpdate()
    useEventListener(window, 'resize', echartsResize)
})
onUnmounted(() => {
    autoUpdateTimer && clearInterval(autoUpdateTimer)
    const chartKeys = Object.keys(state.charts) as Array<keyof typeof state.charts>
    chartKeys.forEach((key) => {
        state.charts[key] && state.charts[key].dispose()
    })
})
</script>

<style scoped lang="scss">
.temperature{
    width: 100%;
    height: 100%;
    .containerPart {
        height: 100%;
        .defaultAside {
            width: 260px;
            height: 100%;
            border-right: 1px solid #eaebed;
        }
        .defaultMainContainer{
            width: calc(100% - 260px);
            height: 100%;
            .temperature-chart{
                width: 100%;
                height: calc(100% - 50px);
            }
        }
    }
}
</style>
