<template>
    <div class="eqData flex-col">
        <div class="blur-background" />
        <div class="eqData_title">
            <div class="eqData_title_center"> DCS主页大屏 </div>
            <div class="time_box"> {{ time }} &nbsp; {{ week }}</div>
        </div>
        <div class="homePage_eCharts" id="eCharts">

            <div class="el_first_row">
                <div class="chart_box">
                    <dv-border-box-1>
                        <div class="chart">
                            <div ref="chartLeftTop" class="chart_left_top chart_content" />
                        </div>
                    </dv-border-box-1>
                </div>
                <div class="chart_box">
                    <!-- 设备预警信息表 -->
                    <dv-border-box-1>
                        <div class="chart">
                            <div ref="chartRightTop" style="width: 100%; height: 300px;" />
                        </div>
                    </dv-border-box-1>
                </div>
            </div>

            <div class="el_second_row">
                <div class="chart_box">
                    <dv-border-box-1>
                        <div class="chart">
                            <!-- <div ref="chartLeftMiddle" style="width: 100%; height: 300px;" /> -->
                        </div>
                    </dv-border-box-1>
                </div>
                <div class="chart_box">
                    <dv-border-box-1>
                        <div class="chart">
                            <div ref="chartRightMiddle" style="width: 100%; height: 300px;" />
                        </div>
                    </dv-border-box-1>
                </div>
            </div>
            <div class="el_third_row">
                <div class="chart_box">
                    <dv-border-box-1>
                        <div class="chart">
                            <!-- 能耗图表 -->
                            <div ref="chartLeftBottom" style="width: 100%; height: 300px;" />
                        </div>
                    </dv-border-box-1>
                </div>
                <div class="chart_box">
                    <!-- 设备预警信息表 -->
                    <dv-border-box-1>
                        <div class="chart_box_title">设备预警信息表</div>
                        <div class="chart">
                            <dv-scroll-board :config="alarmConfig" style="width:605px;height:250px"
                                ref="alarmScrollBoard" />
                        </div>
                    </dv-border-box-1>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import '@/css/dcs/style.css'
import config from '@/myConfig/config';
import * as echarts from 'echarts'
import { getHourFlowData, getEqTempData, getAlarmData, getWeekFlowData ,getEnergyData} from '@/api/dcs/dcs'

export default {
    components: {},
    props: {},
    data() {
        return {
            time: '',// 时间
            week: '',// 星期
            timeInterval: null,
            updateChartInterval: null,

            chartInstance: null, // ECharts 实例对象

            chartRightTop: null, // 右上ECharts 实例对象-产能图表
            chartRightMiddle: null, // 右中ECharts 实例对象-设备状态
            alarmScrollBoard: null, // 设备预警信息表实例对象
            chartLeftBottom: null, // 左下ECharts 实例对象-能耗图表

            options: {
                dataset: {
                    source: [
                        ['Category', '2021', '2022', '2023'],
                        ['Category A', 10, 20, 30],
                        ['Category B', 15, 25, 35],
                        ['Category C', 20, 30, 40],
                    ]
                },
                tooltip: {//提示框组件
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                legend: {//图例组件
                    textStyle: {
                        color: '#fff'
                    }
                },
                xAxis: [
                    {
                        type: 'category',
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                    },
                ],
                series: [
                    {
                        type: 'bar',
                    },
                    {
                        type: 'bar',
                    },
                    {
                        type: 'line',
                    }]
            },
            // 设备预警信息表
            alarmConfig: {
                columnWidth: [70],//列宽
                waitTime: 2000,//等待时间
                // carousel: 'page',
                header: ['设备组', '设备名', '预警信息', '时间'],
                data: []
            }
        }

    },
    mounted() {
        this.setIntervalTime()// 时间显示
        this.getWeek()// 星期显示
        this.initChart()// 初始化图表 
        this.setIntervalUpdateChart()// 图表数据更新
    },
    beforeDestroy() {
        this.clearIntervalTime()
        this.clearIntervalUpdateChart()
    },

    methods: {
        // 时间显示
        setIntervalTime() {
            this.timeInterval = setInterval(() => {
                this.time = new Date().toLocaleString()
            }, 1000)
        },
        setIntervalUpdateChart() {
            this.updateChartInterval = setInterval(() => {
                this.updateChartRightMiddle()
                this.updateChartRightBottom()
                this.updateChartRightTop()
                this.updateChartLeftBottom()
            }, 5000)
        },
        clearIntervalUpdateChart() {
            clearInterval(this.updateChartInterval)
        },
        // 清除时间显示
        clearIntervalTime() {
            clearInterval(this.timeInterval)
        },
        // 星期显示
        getWeek() {
            const date = new Date();
            const week = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
            this.week = week[date.getDay()];
        },
        // 初始化图表
        initChart() {
            // this.initchartLeftTop()
            this.initChartRightTop()
            this.initChartRightMiddle()
            this.initChartRightBottom()
            this.initChartLeftBottom()

        },
        //初始化左上图表
        initChartLeftTop() {
            getHourFlowData().then(res => {
                // console.log('getHourFlowData: ', res)
                const data = res.split(',').filter(item => item != '').map(item => item.trim())
                const tableField = data.slice(0, 5)
                const tableData = []
                for (let index = 1; index < data.length / 5; index++) {
                    const i = 5 * index
                    tableData.push(data.slice(i, i + 5))
                }
                console.log('tableField: ', tableField)
                console.log('tableData: ', tableData)
            })
            const chart = echarts.init(this.$refs.chartLeftTop);
            this.chartInstance = chart;
            this.chartInstance.setOption({
                ...this.options,
            })
        },
        //初始化左下图表-能耗图表
        initChartLeftBottom() {
            this.chartLeftBottom = echarts.init(this.$refs.chartLeftBottom)
            const series = [
                {
                    type: 'bar',
                },
                {
                    type: 'line',
                },
            ]
            let datasetSource = [
                ['日期', '当天能耗', '累计能耗'],
            ]
            this.chartLeftBottom.setOption({
                ...this.options,
                dataset: {
                    source: datasetSource,
                },
                series: series,
                yAxis: [
                    {
                        type: 'value',
                        axisLabel: {
                            color: "rgba(252, 252, 252, 1)"
                        },
                        name: 'kWh',
                        nameTextStyle: {
                            color: "rgba(252, 252, 252, 1)"
                        }
                    },
                ],
            })

        },
        //初始化右上图表-产能图表
        initChartRightTop() {
            this.chartRightTop = echarts.init(this.$refs.chartRightTop)
            const yAxisData = [
                {
                    type: 'value',
                    axisLabel: {
                        color: "rgba(252, 252, 252, 1)"
                    },
                    name:'m³',
                    nameTextStyle: {
                        color: "rgba(252, 252, 252, 1)"
                    }
                },
            ]
            const series = [
                {
                    type: 'bar',
                },
                {
                    type: 'bar',
                },
                {
                    type: 'line',
                },
                {
                    type: 'line',
                },
            ]
            let datasetSource = [
                ['日期', 'K当天流量', 'L当天流量', 'K累计流量', 'L累计流量'],
            ]
            this.chartRightTop.setOption({
                ...this.options,
                yAxis: yAxisData,
                grid: {
                    left: '16%',
                },
                series: series,
                dataset: {
                    source: datasetSource,
                },
            })
        },
        //初始化右中图表-设备状态
        initChartRightMiddle() {
            // 数据初始化·
            let datasetSource = [
                ['设备名称', '空闲', '生产', '故障'],
            ]
            this.chartRightMiddle = echarts.init(this.$refs.chartRightMiddle);
            const series = [
                {
                    type: 'bar',
                    stack: 'eqStatus',//堆叠
                },
                {
                    type: 'bar',
                    stack: 'eqStatus',//堆叠
                },
                {
                    type: 'bar',
                    stack: 'eqStatus',//堆叠
                }]
            this.chartRightMiddle.setOption({
                ...this.options,
                dataset: {
                    source: datasetSource,
                },
                series: series,
            })

        },
        //初始化右下图表-设备预警信息表
        initChartRightBottom() {
            //实例化右下图表
            this.alarmScrollBoard = this.$refs.alarmScrollBoard
        },
        // 更新左下图表-能耗图表
        updateChartLeftBottom() {
            if (this.chartLeftBottom) {
                let datasetSource = [
                    ['日期', '当天能耗', '累计能耗'],
                ]
                getEnergyData().then(res => {
                    // console.log('getEnergyData: ', res)
                    //数据过多时，只保留最近7天的数据
                    res.data.slice(-7).forEach(item => {
                        datasetSource.push([item.day.slice(5, 10), item.value, item.sum])
                    })
                    this.updateChartData(this.chartLeftBottom, datasetSource)
                })
            }
        },
        // 更新右上图表-产能图表
        updateChartRightTop() {
            if (this.chartRightTop) {
                let datasetSource = [
                    ['日期', 'K当天流量', 'L当天流量', 'K累计流量', 'L累计流量'],
                ]
                getWeekFlowData().then(res => {
                    // console.log('getWeekFlowData: ', res)
                    const data = this.convertData(res)
                    // console.log('data: ', data)
                    const valueIndex = data[0].indexOf('_value')
                    const timeIndex = data[0].indexOf('_time')
                    let K_Sum = 0
                    let L_Sum = 0
                    for (let i = 1; i < data.length; i += 2) {
                        //字符串转整数
                        K_Sum += parseInt(data[i][valueIndex])
                        L_Sum += parseInt(data[i + 1][valueIndex])
                        datasetSource.push([data[i][timeIndex].slice(5, 10), parseInt(data[i][valueIndex]), parseInt(data[i + 1][valueIndex]), K_Sum, L_Sum])
                    }
                    this.updateChartData(this.chartRightTop, datasetSource)
                })
            }

        },
        // 更新右下图表-设备预警信息表
        updateChartRightBottom() {
            if (this.alarmScrollBoard) {
                getAlarmData().then(res => {
                    const data = this.convertData(res)
                    // const valueIndex = data[0].indexOf('_value')
                    const nameIndex = data[0].indexOf('_field')
                    const BucketIndex = data[0].indexOf('_bucket')
                    const timeIndex = data[0].indexOf('_time')
                    let alarmData = []
                    for (let i = 1; i < data.length; i++) {
                        let dataArr = []
                        //根据桶名找到对应的设备组名
                        const groupName = config.eqGroupNames[config.eqBucketNames.indexOf(data[i][BucketIndex])]
                        dataArr.push(groupName)
                        const wdCodeIndex = parseInt(data[i][nameIndex].split('_')[1])
                        dataArr.push(groupName + '-' + config.WD_Code[wdCodeIndex])
                        dataArr.push('温度超过阈值，请及时查看')
                        dataArr.push(new Date(data[i][timeIndex]).toLocaleString())
                        alarmData.push(dataArr)
                    }
                    this.alarmConfig.data = alarmData
                    this.alarmScrollBoard.updateRows(alarmData)
                })
            }
        },
        // 右中图表数据更新-设备状态
        updateChartRightMiddle() {
            if (this.chartRightMiddle) {
                const chart = this.chartRightMiddle
                // 数据初始化·
                let datasetSource = [
                    ['设备名称', '空闲', '生产', '故障']
                ];
                for (let i = 0; i < config.eqGroupNames.length; i++) {
                    datasetSource.push([config.eqGroupNames[i], 0, 0, 0]);
                }

                // console.log('updateChartRightMiddle', this.datasetSource)
                getEqTempData().then(res => {
                    // console.log('getEqTempData: ', res)
                    // console.log('getEqTempData: ', this.convertData(res))

                    const data = this.convertData(res)
                    const valueIndex = data[0].indexOf('_value')
                    // const tableIndex = data[0].indexOf('table')

                    const rangeIndex = data[0].indexOf('temp_range')
                    const BucketIndex = data[0].indexOf('_bucket')
                    for (let i = 1; i < data.length; i++) {
                        const index1 = config.eqBucketNames.indexOf(data[i][BucketIndex]) + 1
                        const index2 = parseInt(data[i][rangeIndex])
                        datasetSource[index1][index2] = data[i][valueIndex]
                    }
                    // for (let i = 1; i < data.length; i++) {
                    //     const index = parseInt(data[i][tableIndex])
                    //     if (data[i][valueIndex] >= 60) {
                    //         datasetSource[index + 1][2]++
                    //     } else if (data[i][valueIndex] < 45) {
                    //         datasetSource[index + 1][1]++
                    //     } else {
                    //         datasetSource[index + 1][3]++
                    //     }
                    // }
                    this.updateChartData(chart, datasetSource)
                })
            }

        },
        //图表数据更新
        updateChartData($ref, data) {
            $ref.setOption({
                dataset: {
                    source: data,
                },
            })
        },
        // 转换数据格式
        convertData(input) {
            // 去除可能存在的多余空格，并按行分割输入字符串
            const lines = input.trim().split('\n').map(line => line.trim());
            // 获取列名（标题）
            const headers = lines[0].split(',');
            const result = lines.map(line => {
                // 按逗号分割当前行的数据
                const values = line.split(',');
                // 将每行数据与对应的列名组合起来形成对象，然后转换成所需格式
                return headers.map((header, index) => values[index]);
            });
            return result;
        }
    }
}
</script>
<style lang="scss" scoped>
.eqData {
    width: 1920px;
    height: 1080px;
    flex-shrink: 0;
    background: rgba(0, 0, 0, 0.70);
    backdrop-filter: blur(2px);


    .eqData_title {
        background-image: url('../../../assets/dcs/eqData/header.svg');
        background-size: 100% 100%;
        background-repeat: no-repeat;
        width: 1919.5px;
        height: 74.5px;
        flex-shrink: 0;
        position: relative;

        .eqData_title_center {
            font-family: PangMenZhengDao;
            font-size: 36px;
            font-style: normal;
            font-weight: 400;
            line-height: normal;
            letter-spacing: 7.2px;
            background: linear-gradient(180deg, #FFF 32.33%, #00ABFF 130.49%);
            background-clip: text;
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            text-align: center;
            margin-top: 10px;
        }

        .time_box {
            position: absolute;
            top: 9px;
            right: 155px;
            font-size: 24px;
            color: #95bfca;
        }
    }

    .homePage_eCharts {
        width: 1920px;
        height: 800px;

        .chart {
            padding-top: 10px;
            // width: 80%;
            background: rgba($color: #0c2839, $alpha: 0.3);

            .chart_content {
                width: 100%;
                height: 280px;
            }
        }

        .el_first_row,
        .el_second_row,
        .el_third_row {
            display: flex;
            justify-content: space-between;

            .chart_box {
                width: 626px;
                text-align: center;
                height: 300px;

                ::v-deep .dv-border-box-1 {
                    .border {
                        border: none !important;
                    }
                }

            }
        }

        .el_third_row {
            .chart_box {
                .chart_box_title {
                    font-size: 24px;
                    font-weight: 500;
                    color: #fff;
                }

                .chart {
                    // width: 80%;
                    margin-left: 10px;
                    background: rgba($color: #0c2839, $alpha: 0.3);

                    .dv-scroll-board {
                        //透明度
                        opacity: 0.8;
                        box-sizing: border-box;
                    }
                }
            }
        }
    }
}
</style>