<template>
    <div :class="$style['container']">
        <div class="header">
            <div class="title">
                <header2 ref="headerref" :width="'100%'" :height="'150px'" :title="t('messages.generalEnvironment')"
                    :titleTip="titleTip" :typeFun="['AbnormalData', 'time']"
                    :alarmType="['noiseAlarm', 'temphuim', 'dustAlarm', 'saving']"></header2>
            </div>
        </div>
        <div class="content" ref="Acontent">
            <div class="top-box">
                <div style="width: 12%; height: 250px; margin-bottom: 10px; display: flex; align-items: center; justify-content: space-evenly;"
                    v-for="item in store.newVerticalNum">
                    <verticalNumLoop :title="item.title" :icon="item.icon" :limit="item.limit" :unit="item.unit"
                        :value="item.value"></verticalNumLoop>
                </div>

            </div>
            <div class="bottom-box">
                <power style="width: 33%;height: 100%;box-sizing: border-box;" :title="powerTitle" :series="powerSeries"
                    :listName="listName">
                </power>
                <div style="width: 33%;height: 100%;background: #bfb;">
                </div>
                <div style="width: 33%;height: 100%;background: #bfc;">
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang='ts'>
import { onMounted, onUnmounted, reactive, ref } from 'vue'
import header2 from '@/components/headerBox/header2.vue'
import verticalNumLoop from './components/verticalNumLoop.vue'
import power from './components/power.vue';
import { getSafeWarningData, getpipeData } from "@/http/realtimeSecurity";
import { getnoiseData } from "@/http/generalEnvironment";
import { getHumitureData, getPmtenData, getPmtwoData } from "@/http/generalEnvironment";
import { getPowerData } from "@/http/energyConsume";
import { useSocketStore } from "@/store/moduleSocketMechanics";
import { connectWebsocket, closeWebsocket } from "@/utils/websocket";
import { gettime, clacendTime } from "@/utils/time"

import { useI18n } from 'vue-i18n'
let { t } = useI18n();
const store = useSocketStore();
let deptIds = '6,7,9,10,11'
let titleTip = [
    {
        color: "#E43961",
        name: t('messages.abnormal'),
    },
    {
        color: "#20AEC5",
        name: t('messages.NoAbnormal'),
    },
    {
        color: "#A7A6BD",
        name: t('messages.disconnection'),
    },
];
const verticalType = {
    'TVOC': { icon: 'icon-TVOC-Outlined', title: t('messages.TVOCDetection'), unit: 'mg/m³' },
    'Smoke': { icon: 'icon-yanwubaojingqi', title: t('messages.smokeDetection'), unit: "ppm" },
    'Methane': { icon: 'icon-ranqi', title: t('messages.gasDetection'), unit: null },
    'CH2O': { icon: 'icon-app_icons--', title: t('messages.CH2ODetection'), unit: 'mg/m³' },
    'FIRE': { icon: 'icon-weibiaoti1', title: t('messages.flameDetection'), unit: null },
    'noise': { icon: 'icon-shengyin', title: t('messages.noiseDetection'), unit: 'dB' },
}
/**用电量 */
let listName = ref<string[]>()
let powerTitle = t('messages.Powerto2023')
let powerSeries = ref()


let headerref = ref()
let verticalList: any[] = reactive([])
//获取传感器实时数据
async function getSensorData() {
    let list = []
    const res: any = await Promise.all([
        getnoiseData({ deptIds }),
        getSafeWarningData({ deptIds }),
    ])
    let noiseData = {
        limit: res[0].data.top.value,
        type: 'noise',
        value: res[0].data.listData.map((item: any) => {
            return {
                devId: item.devId,
                name: item.name + '噪音监测',
                type: 'noise',
                status: true,
                val: item.value,
            }
        })
    }
    list.push(noiseData);
    list.push(...res[1].data)

    let datetime = new Date().getTime();
    let handle_vertical = list.map((item: any) => {
        item.value.forEach(element => {
            if (element.name.includes("TVOC")) {
                element.name = element.name.split('TVOC')[0] + verticalType[item.type].title
            }

            if (element.val > item.limit) {
                element.date = gettime(element.ts),
                    element.time = element.ts || datetime
                element.continuous = clacendTime(datetime, element.ts || datetime)
            } else {
                element.date = null
                element.time = null
                element.continuous = null
            }
        });
        return {
            type: item.type,
            icon: verticalType[item.type].icon,
            title: verticalType[item.type].title,
            limit: item.limit,
            unit: verticalType[item.type].unit,
            value: item.value
        }
    })

    store.setNewVerticalNum(handle_vertical)
}

async function getPower_data() {
    const { data }: any = await getPowerData({ time: 1 })
    listName.value = data.name


    let series = []
    data.listData.forEach(res => {
        if (res.years == 2023) {
            for (let key in res.month) {
                series.push({
                    name: key + '月',
                    type: 'bar',
                    stack: res.years,
                    emphasis: {
                        focus: 'coordinateSystem',
                        label: {
                            show: true,
                            formatter: function (value, index) {
                                return value.value.toLocaleString()
                            }
                        }
                    },
                    data: res.month[key]
                })
            }
        }
    })
    //data0用于初始化计算的数据
    let data0 = []

    for (let i = 1; i <= data.name.length; i++) {
        data0.push(0)
    }

    series.push(
        {
            name: '',
            type: 'bar',
            data: data0,
            color: '#bbf',
            stack: data.listData[1].years,
            // barWidth: 30,
            label: {
                show: true,
                position: 'right',
                color: '#fff'
            }
        }
    )
    powerSeries.value = series

}

function getWebsocket(val) {
    headerref.value.HeadergetWebsocket(val)
    try {
        let data = JSON.parse(val);

        //精饰车间燃气监测
        if (data.type == "paintingGas") {
            let verticalData = { name: data.msg.devName, val: data.msg.paintingGas.value, devId: data.msg.devId }
            store.changeNewVerticalNum({ type: 'Methane', data: verticalData })

        }
        //甲醛TVOC
        if (data.type == "TVOC_CH2O") {
            let verticalData_TVOC = { name: data.msg.TVOC.name, val: data.msg.TVOC.value, devId: data.msg.TVOC.devId }
            store.changeNewVerticalNum({ type: 'TVOC', data: verticalData_TVOC })
            let verticalData_CH2O = { name: data.msg.CH2O.name, val: data.msg.CH2O.value, devId: data.msg.CH2O.devId }
            store.changeNewVerticalNum({ type: 'CH2O', data: verticalData_CH2O })

        }
        //火焰传感器？
        if (data.type == "flame") {
            let verticalData = { name: data.msg.devName, val: data.msg.flame.value, devId: data.msg.devId }
            store.changeNewVerticalNum({ type: 'FIRE', data: verticalData })

        }
        //精饰车间烟雾传感器
        if (data.type == "smoke") {
            let verticalData = { name: data.msg.devName, val: data.msg.smoke.value, devId: data.msg.devId }
            store.changeNewVerticalNum({ type: 'Smoke', data: verticalData })
            // console.log(JSON.stringify({type:'Smoke',data:verticalData}),"烟雾传感器");
        }
        //   if (data.type == "airPressure") {
        //     store.changePressure(data.msg);
        //   }
        //   if (data.type == "waterPressure") {
        //     store.changePipe(data.msg);
        //   }

    } catch (err) {
        console.log(err, "报错了大哥", console.log(val)
        );

    }
}
function errWebsocket(val) {
    headerref.value ? headerref.value.HeadererrWebsocket(val) : ''
    // console.log(val);
}


onMounted(() => {
    getSensorData()
    getPower_data()
    connectWebsocket(null, null, getWebsocket, errWebsocket);
})
</script>

<style module>
.container {
    height: 1080px;
    width: 1920px;
    color: #20aec5;
    background-color: #100c2a;
    box-sizing: border-box;
}
</style>
<style scoped>
.content {
    width: 1920px;
    height: 930px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
}

.top-box {
    width: 1920px;
    height: 290px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.bottom-box {
    width: 1920px;
    height: 630px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    /* background-color: #afb; */
}
</style>
