<template>
    <div :class="$style['container']">
        <div class="header">
            <div class="title">
                <header2 ref="headerref" :width="'100%'" :height="'150px'" :title="t('messages.环境 实时监测系统')"
                    :titleTip="titleTip" :typeFun="['AbnormalData', 'time']"
                    :alarmType="['noiseAlarm', 'temphuim', 'dustAlarm', 'saving']"></header2>
            </div>
        </div>
        <div class="content" ref="Acontent">
            <div class="top-box">
                <div class="top-box-item" v-for="item in store.newVerticalNum">
                    <verticalNumLoop @click="gotoTrendChart(item.value, item.unit)" :title="item.title" :icon="item.icon"
                        :limit="item.limit" :unit="item.unit" :value="item.value"></verticalNumLoop>
                </div>
                <div class="top-box-item" @click="gotoTrendChart(store.pm, 'μg/m3')">
                    <pm :pm10limit="150" :pm25limit="75"></pm>
                </div>
                <div class="top-box-item"  @click="gotoTrendChart(store.humiture, '℃/%RH')">
                    <humidity :top="humidityTop" :bottom="humidityBottom"></humidity>
                </div>
            </div>
            <div class="bottom-box">
                <div style="width: 33%;height: 100%;">
                    <border13>
                        <pipe :title="t('messages.PipelinePressure_Mpa')" :value="pipeData"></pipe>
                    </border13>
                </div>
                <div style="width: 33%;height: 100%;">
                    <border13>
                        <power :title="powerData.title" :seriesVal="powerData.seriesVal" :httpValue="powerData.value">
                        </power>
                    </border13>
                </div>
                <div style="width: 16%;height: 100%;">
                    <border13>
                        <!-- <humidityBar :title="'温湿度'" :data="humidityData" :bottom="humidityBottom" :top="humidityTop">
                        </humidityBar> -->
                        <gas :title="t('messages.gashistory')" :value="gasData" 
                        :color="gascolor"></gas>
                    </border13>
                </div>
                <div style="width: 16%;height: 100%;">
                    <border13>
                        <!-- <humidityBar :title="'温湿度'" :data="humidityData" :bottom="humidityBottom" :top="humidityTop">
                        </humidityBar> -->
                        <gas :title="t('messages.waterhistory')" :value="waterData" 
                        :color="watercolor"></gas>
                    </border13>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang='ts'>
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import header2 from '@/components/headerBox/header2.vue'
import verticalNumLoop from './components/verticalNumLoop.vue'
import power from './components/power2023.vue';
import pm from './components/pm.vue';
import humidityBar from './components/humidityBar.vue';
import humidity from './components/humidity.vue';
import gas from './components/gas.vue'
import pipe from './components/pipe.vue'
import border13 from '@/components/border/Border13.vue'
import { getSafeWarningData, getpipeData } from "@/http/realtimeSecurity";
import { getnoiseData } from "@/http/generalEnvironment";
import { getHumitureData, getPmtenData, getPmtwoData } from "@/http/generalEnvironment";
import { getPowerData, getconsumeDetail } from "@/http/energyConsume";
import { useSocketStore } from "@/store/moduleSocketMechanics";
import { connectWebsocket, closeWebsocket } from "@/utils/websocket";
import { gettime, clacendTime } from "@/utils/time"
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { hu } from 'element-plus/es/locale';
let { t } = useI18n();
let router = useRouter()
const store = useSocketStore();
let deptIds = '6,7,9,10,11'
document.title = t('messages.环境 实时监测系统')
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 powerData = ref({ value: { name: [] }, seriesVal: [], title: t('messages.Powerto2023') })

let gasData = ref(0)
let waterData = ref(0)
let pipeData = ref({ listData: [], top: 0 })

let headerref = ref()
let verticalList: any[] = reactive([])
let pmtimer = null
let humidityTop = ref({})
let humidityBottom = ref({})

/**
 * 跳转到趋势图
 */
function gotoTrendChart(value, unit) {
    let ids = value.map((item) => item.devId).toString();
    ElMessageBox.confirm(
        '即将跳转到传感器监测走势图页面，是否继续？',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'info',
        }
    )
        .then(() => {
            router.push({ path: '/TrendChart', query: { ids: ids, unit: unit } })
        })
        .catch(() => {

        })

}


//获取传感器实时数据
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 gethumitureData() {
    let result: any = await getHumitureData({ deptIds })

    if (result.code == 200) {
        store.$patch((state) => {
            state.humiture = result.data.Humiture
        })
        humidityBottom.value = result.data.bottom
        humidityTop.value = result.data.top
    }
}
/**用电量柱状图
let humidityData = ref({})
let humidityBottom = ref({})
let humidityTop = ref({})
watch(() => store.humiture, (newVal, oldVal) => {
    let data = { list: [], temp: [], humidity: [] }
    newVal.Humiture.forEach((res) => {
        data.list.push(res.name);
        data.temp.push(res.temp);
        data.humidity.push(res.humidity);
    });
    humidityData.value = data;
    humidityBottom.value = newVal.bottom;
    humidityTop.value = newVal.top;
}, { deep: true, immediate: true })
 */
//获取粉尘数据
let pmindex = ref(0);
async function getPmData() {
    let resulttwo: any = await getPmtwoData()
    let resultten: any = await getPmtenData()
    let arr = [
        '01336fd0-1fa0-11ed-9223-7db1174970a8',
        '083e3900-3435-11ed-a7e1-fd42bca6c8c6',
        '270e1500-eee1-11ed-b2ee-2d727e0cafab',
        '54058c30-eee3-11ed-b2ee-2d727e0cafab',
        '76efb040-eee3-11ed-b2ee-2d727e0cafab',
        'a6020310-eee3-11ed-b2ee-2d727e0cafab',
        'bcbfb530-88b2-11ed-a926-570995ad0254'
    ]
    let data = {}
    if (resulttwo) {
        resulttwo.data.forEach(ele => {
            if (arr.indexOf(ele.devId) > -1) {                
                data[ele.devId] = {
                    devId: ele.devId,
                    name: ele.devName.split('监测')[0],
                    pm25: ele.value,
                    pm10: null
                }
            }
        })
    }

    if (resultten) {
        resultten.data.forEach(ele => {
            if (data.hasOwnProperty(ele.devId)) {
                data[ele.devId].pm10 = ele.value
            }

        })
    }
    
    store.$patch((state) => {
        state.pm = Object.values(data)
    })

}
//获取用电量数据
async function getPower_data() {
    let result: any = await getPowerData({ time: 1 });

    if (result.code == 200) {
        let series = [];
        result.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 <= result.data.name.length; i++) {
            data0.push(0);
        }

        series.push({
            name: "",
            type: "bar",
            data: data0,
            color: "#bbf",
            stack: result.data.listData[1].years,
            barWidth: 40,
            label: {
                show: true,

                position: "right",
                color: "#fff",
            },
        });

        powerData.value.value = result.data
        powerData.value.seriesVal = series
        powerData.value.title = '机械分厂用电量'
    }
}

let gascolor = {step0:'#186945',step1:'#1b7a4f',border:'rgba(8, 206, 120, 0.8)',color:'rgba(8, 206, 120, 0.4)'}
let watercolor = {step0:'#0D73B3',step1:'#1176C6',border:'#1E4D7B',color:'#0F2A57'}
//获取用气量数据
async function getconsumeDetailfun() {
    let result: any = await getconsumeDetail()
    if (result.code == 200) {
        result.data.forEach(res => {
            if (res.deptName == '喷漆车间' && res.type == 'GasDetail') {
                gasData.value = res.usageNum
            }
            if (res.deptName == '生产区' && res.type == 'WaterDetail') {
                waterData.value = res.usageNum
            }
        })

    }
}
async function getpipeDatafun() {
    let pageValue = '6,7,9,10,11'
    let result: any = await getpipeData({ deptIds: pageValue })

    if (result.code == 200) {
        pipeData.value.listData = result.data.listData
        pipeData.value.top = result.data.top
    }
}
/************************************************************ */
let noiseData = [
    '55aaf760-4e88-11ed-b6af-15994988a6b3',
    '8733fe40-4e82-11ed-b6af-15994988a6b3',
    'cae16000-4e88-11ed-b6af-15994988a6b3',
    '08144ba0-4e88-11ed-b6af-15994988a6b3',
    '2a5f6600-4e87-11ed-b6af-15994988a6b3'
]
//socket
function getWebsocket(val) {
    headerref.value.HeadergetWebsocket(val)
    try {
        let data = JSON.parse(val);

        if (data.type == "noise") {
            data.msg.listData.forEach(ele => {
                if (noiseData.indexOf(ele.devId) > -1) {
                    let verticalData = { name: ele.name, val: ele.value, devId: ele.devId }                    
                    store.changeNewVerticalNum({ type: 'noise', data: verticalData })
                }
            })
        }
        //精饰车间燃气监测
        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);
        //   }
        if (data.type == "humiture") {
            store.changeHumiture(data.msg);
        }

        if (data.type == "dust") {
            store.changeDust(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()
    getpipeDatafun()
    getconsumeDetailfun()
    gethumitureData()
    getPmData()
    connectWebsocket(null, null, getWebsocket, errWebsocket);
})
onUnmounted(() => {
    closeWebsocket();
})
</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: 340px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.top-box-item {
    width: 12%;
    height: 300px;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    justify-content: space-evenly;
}

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