<template>
    <div class="default-main" ref="HomeHight">
        <el-row style="margin: 0px;">
            <el-col :md="24" :lg="24" class="col-top">
                <el-row class="overview">
                    <el-col :xs="12" :sm="8" :md="8" :lg="4">
                        <div class="overviewItem" style="margin-left: 0px;">
                            <img class="small-panel-pic" src="~assets/dashboard/overview01.png" alt="" />
                            <div class="small-base">
                                <div class="small-title">全场平均风速</div>
                                <div class="small-value">
                                    <span class="content-number">{{realData.attributeMap.windfarmavgwindspeed}}</span>
                                    <span>m/s</span>
                                </div>
                            </div>
                        </div>
                    </el-col>
                    <el-col :xs="12" :sm="8" :md="8" :lg="4">
                        <div class="overviewItem">
                            <img class="small-panel-pic" src="~assets/dashboard/overview02.png" alt="" />
                            <div class="small-base">
                                <div class="small-title">全场实时有功</div>
                                <div class="small-value">
                                    <span class="content-number">{{realData.attributeMap.windfarmactivepower}}</span>
                                    <span>kW</span>
                                </div>
                            </div>
                        </div>
                    </el-col>

                    <el-col :xs="12" :sm="8" :md="8" :lg="4">
                        <div class="overviewItem">
                            <img class="small-panel-pic" src="~assets/dashboard/overview03.png" alt="" />
                            <div class="small-base">
                                <div class="small-title">全场实时无功</div>
                                <div class="small-value">
                                    <span class="content-number">{{realData.attributeMap.windfarmreactivepower}}</span>
                                    <span>kvar</span>
                                </div>
                            </div>
                        </div>
                    </el-col>

                    <el-col :xs="12" :sm="8" :md="8" :lg="4">
                        <div class="overviewItem">
                            <img class="small-panel-pic" src="~assets/dashboard/overview04.png" alt="" />
                            <div class="small-base">
                                <div class="small-title">日发电量</div>
                                <div class="small-value">
                                    <span class="content-number">{{realData.attributeMap.windfarmdayprodenergy}}</span>
                                    <span>kWh</span>
                                </div>
                            </div>
                        </div>
                    </el-col>

                    <el-col :xs="12" :sm="8" :md="8" :lg="4">
                        <div class="overviewItem">
                            <img class="small-panel-pic" src="~assets/dashboard/overview05.png" alt="" />
                            <div class="small-base">
                                <div class="small-title">本月发电量</div>
                                <div class="small-value">
                                    <span class="content-number">{{realData.attributeMap.windfarmmonthprodenergy}}</span>
                                    <span>kWh</span>
                                </div>
                            </div>
                        </div>
                    </el-col>
                    <el-col :xs="12" :sm="8" :md="8" :lg="4">
                        <div class="overviewItem" style="margin-right: 0px;">
                            <img class="small-panel-pic" src="~assets/dashboard/overview06.png" alt="" />
                            <div class="small-base">
                                <div class="small-title">年发电量</div>
                                <div class="small-value">
                                    <span class="content-number">{{realData.attributeMap.windfarmyearprodenergy}}</span>
                                    <span>kWh</span>
                                </div>
                            </div>
                        </div>
                    </el-col>
                </el-row>
            </el-col>
            <el-col :md="24" :lg="24">
                <div class="AlertPart">
                    <div class="AlertPic">
                        <img src="~assets/dashboard/alert01.png" alt="">
                    </div>
                    <div class="realAlert"
                         ref="scrollRef"
                         @mouseover.native="clearScroll"
                         @mouseleave.native="createScroll"
                         >
                        <p v-for="(item,index) in tableData"
                           :key="index"
                           @mouseover="showButton"
                           @mouseout="hideButton"
                           >
                            <span>{{item.eventTimeFormate}}</span>
                            <span>{{item.deviceName}}</span>
                            <span>{{item.eventText}}</span>
                            <span v-show="showConfirmButton" >
                                <a style="color: #0277b3; cursor: pointer;" @click="open(item)" >确认</a>
                            </span>
                        </p>
                    </div>
                </div>

            </el-col>
            <el-col :md="24" :lg="24" class="col-center" style="padding-right: 10px;">
                <div class="grid-content ep-bg-purple-light">
                    <!--风机矩阵-->
                    <div class="matrix panelBg">
                        <div class="homeHeader">
                            <div class="cardLabel">风机矩阵</div>
                        </div>

                        <el-scrollbar>
                            <WindContent :parentData="FanList" @StatusListData="StatusListData"></WindContent>
                        </el-scrollbar>
                    </div>
                </div>
            </el-col>
        </el-row>
    </div>
</template>

<script setup lang="ts">
import { nextTick, onActivated, onMounted, reactive, ref, onBeforeMount, onUnmounted, VNodeRef } from 'vue'
import * as echarts from 'echarts'
import { useTemplateRefsList, useEventListener } from '@vueuse/core'
import { useI18n } from 'vue-i18n'
import WindContent from '/@/views/backend/home/windMatrix.vue'
import { equipList } from '/@/api/backend/realData/request'
import { getWindFarmRealData, getWindTurbineMatrixData, getHistoryData } from '/@/api/backend/dashboard.ts'
import { dayjs, ElMessage, ElMessageBox, TableInstance } from 'element-plus'
import { getRealTimeState } from '/@/views/backend/equipment/airBlower/utils.ts'
import { useRoute } from 'vue-router'
import { getAlarmListReq, eventComfirm } from '/@/api/backend/alarms/request'
const route = useRoute()

const d = new Date()
const { t } = useI18n()
let timer: any = null
let myTable = ref<TableInstance>()

const realData = ref({
    windFarmId: '',
    attributeMap: {},
})

const attributeList = ref({
    attributesList:[
        'windfarmactivepower',
        'windfarmreactivepower',
        'windfarmavgwindspeed',
        'windfarmdayprodenergy',
        'windfarmmonthprodenergy',
        'windfarmyearprodenergy',
    ]
})

const formatAttributeValue = (value: any) => {
    if (value === undefined) {
        return '-'
    }
    if (typeof value !== 'number') {
        throw new Error('Invalid data type for attribute value')
    }
    return value % 1 === 0 ? value : value.toFixed(2)
}
const overviewList = () => {
    getWindFarmRealData(attributeList.value).then((res) => {
        if (res.code == 200) {
            res.data.attributeMap.windfarmactivepower = formatAttributeValue(res.data.attributeMap.windfarmactivepower)
            res.data.attributeMap.windfarmreactivepower = formatAttributeValue(res.data.attributeMap.windfarmreactivepower)
            res.data.attributeMap.windfarmavgwindspeed = formatAttributeValue(res.data.attributeMap.windfarmavgwindspeed)
            res.data.attributeMap.windfarmdayprodenergy = formatAttributeValue(res.data.attributeMap.windfarmdayprodenergy)
            res.data.attributeMap.windfarmmonthprodenergy = formatAttributeValue(res.data.attributeMap.windfarmmonthprodenergy)
            res.data.attributeMap.windfarmyearprodenergy = formatAttributeValue(res.data.attributeMap.windfarmyearprodenergy)
            const data: any = {
                windFarmId: res.data.windFarmId,
                attributeMap: {
                    windfarmactivepower: res.data.attributeMap.windfarmactivepower,
                    windfarmreactivepower: res.data.attributeMap.windfarmreactivepower,
                    windfarmavgwindspeed: res.data.attributeMap.windfarmavgwindspeed,
                    windfarmdayprodenergy: res.data.attributeMap.windfarmdayprodenergy,
                    windfarmmonthprodenergy: res.data.attributeMap.windfarmmonthprodenergy,
                    windfarmyearprodenergy: res.data.attributeMap.windfarmyearprodenergy
                },
            }

            realData.value = data
        } else {
            ElMessage.error({
                message: res.msg,
                type: 'error',
            })
        }
    })
}
const currentDayStatus = ref({
    windTurbineNum: 0,
    installedCapacity: 0,
    runCapacityTotal: 0,
    runNum: 0,
    standbyCapacityTotal: 0,
    standbyNum: 0,
    faultCapacityTotal: 0,
    faultNum: 0,
    offlineCapacityTotal: 0,
    offlineNum: 0,
    StandCapacityTotal: 0,
    StandNum: 0,
    StartCapacityTotal: 0,
    StarteNum: 0,
})
const deviceCode = ref([])
const FanList = ref([])
const StatusListData = () => {
    getWindTurbineMatrixData().then((res) => {
        if (res.code == 200) {
            currentDayStatus.value.windTurbineNum = res.data.length
            const data = res.data.map((item, index) => {
                const state = getRealTimeState(item.attributeMap)
                item.attributeMap.iwindspeed =
                    item.attributeMap.iwindspeed !== undefined
                        ? item.attributeMap.iwindspeed % 1 === 0
                            ? item.attributeMap.iwindspeed
                            : item.attributeMap.iwindspeed.toFixed(2)
                        : '--'
                item.attributeMap.igenpower =
                    item.attributeMap.igenpower !== undefined
                        ? item.attributeMap.igenpower % 1 === 0
                            ? item.attributeMap.igenpower
                            : item.attributeMap.igenpower.toFixed(2)
                        : '--'
                item.attributeMap.ikwhthisday =
                    item.attributeMap.ikwhthisday !== undefined
                        ? item.attributeMap.ikwhthisday % 1 === 0
                            ? item.attributeMap.ikwhthisday
                            : item.attributeMap.ikwhthisday.toFixed(2)
                        : '--'
                // 初始化计数器和累加器
                if (index === 0) {
                    currentDayStatus.value.runNum = 0
                    currentDayStatus.value.standbyNum = 0
                    currentDayStatus.value.StandNum = 0
                    currentDayStatus.value.StarteNum = 0
                    currentDayStatus.value.offlineNum = 0
                    currentDayStatus.value.faultNum = 0

                    currentDayStatus.value.runCapacityTotal = 0
                    currentDayStatus.value.standbyCapacityTotal = 0
                    currentDayStatus.value.StandCapacityTotal = 0
                    currentDayStatus.value.StartCapacityTotal = 0
                    currentDayStatus.value.offlineCapacityTotal = 0
                    currentDayStatus.value.faultCapacityTotal = 0
                    currentDayStatus.value.installedCapacity = 0
                }

                // 更新容量
                if (item.nominalCapacity !== undefined) {
                    currentDayStatus.value.installedCapacity += item.nominalCapacity
                }

                // 根据运行模式更新状态和数量
                //const mode = item.attributeMap.iturbineoperationmode
                if ([7, 8, 17, 18, 19, 20, 21].includes(state)) {
                    currentDayStatus.value.runCapacityTotal += item.nominalCapacity
                    currentDayStatus.value.runNum += 1
                } else if ([1, 2, 3, 4, 5, 6].includes(state)) {
                    currentDayStatus.value.standbyCapacityTotal += item.nominalCapacity
                    currentDayStatus.value.standbyNum += 1
                } else if ([9, 10, 12, 13, 14, 15].includes(state)) {
                    currentDayStatus.value.StandCapacityTotal += item.nominalCapacity
                    currentDayStatus.value.StandNum += 1
                } else if (state === 16) {
                    currentDayStatus.value.StartCapacityTotal += item.nominalCapacity
                    currentDayStatus.value.StarteNum += 1
                } else if (state === 0) {
                    currentDayStatus.value.offlineCapacityTotal += item.nominalCapacity
                    currentDayStatus.value.offlineNum += 1
                } else if (state === 11) {
                    currentDayStatus.value.faultCapacityTotal += item.nominalCapacity
                    currentDayStatus.value.faultNum += 1
                }
                const propertiesToFormat = [
                    'runCapacityTotal',
                    'standbyCapacityTotal',
                    'StandCapacityTotal',
                    'StartCapacityTotal',
                    'offlineCapacityTotal',
                    'faultCapacityTotal',
                    'installedCapacity',
                ]

                propertiesToFormat.forEach((property) => {
                    if (currentDayStatus.value[property] !== null && currentDayStatus.value[property] !== undefined) {
                        currentDayStatus.value[property] = Number(currentDayStatus.value[property].toFixed(1))
                    }
                })
                return {
                    irn: item.irn,
                    name: item.name ?? '-',
                    model: item.model || '-',
                    modelId: item.modelId,
                    belongLine: item.belongLine || '-',
                    standard: item.standard,
                    attributeMap: {
                        iwindspeed: item.attributeMap.iwindspeed,
                        igenpower: item.attributeMap.igenpower,
                        ikwhthisday: item.attributeMap.ikwhthisday,
                        iturbineoperationmode: state,
                        locked: item.attributeMap.locked,
                        irotorspeed: item.attributeMap.irotorspeed,
                    },
                }
            })
            FanList.value = data
        } else {
            ElMessage.error({
                message: res.msg,
                type: 'error',
            })
        }
    })
}




const timestampToTime = (timestamp: any) => {
    timestamp = timestamp ? timestamp : null
    let date = new Date(timestamp)
    let Y = date.getFullYear() + '-'
    let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
    let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
    let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
    let m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
    return Y + M + D + h + m
}
const tableData = ref()

const getTableData = (deviceCode) => {
    const data: any = {
        startTime: new Date(new Date().toLocaleDateString()).getTime(),
        endTime: Date.now(),
        deviceCode: deviceCode,
        limit: 100,
        eventLevel:2
    }
   // console.log(JSON.stringify(data))
    getAlarmListReq(data).then((res) => {
        if (res.code == 200) {
            //tableData.value = res.rows
            tableData.value = res.rows.map((item: any) => {
                return {
                    ...item,
                    eventTimeFormate: timestampToTime(item.eventTime),
                }
            })
        } else {
            ElMessage.error(res.msg ?? '查询失败')
        }
    })
}
const open = (val: any) => {
    ElMessageBox.confirm('是否确认?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            okSubmit(val)
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消确认',
            })
        })
}

const okSubmit = (val: any) => {
    const reqData: any = [
        {
            eventTime: val.eventTime,
            eventId: val.eventId,
            confirmed: 1,
            deviceId: val.deviceId,
        },
    ]
    eventComfirm(reqData)
        .then((res: any) => {
            if (res.code == 200) {
                ElMessage.success(res.msg ?? '确认成功')
                getTableData(deviceCode.value)
            } else {
                ElMessage.error(res.msg ?? '查询失败')
            }
        })
        .catch((err) => {
            ElMessage.error(err?.response?.data?.msg ?? '查询失败')
        })
}

const scrollRef=ref()
const showConfirmButton = ref(false)
const showButton = () => {
    showConfirmButton.value = true;
}
const hideButton = () => {
    showConfirmButton.value = false;
}
const clearScroll = () => {
    clearInterval(timer)
}
const createScroll = () => {
    clearScroll()
    timer =setInterval(() => {
        scrollRef.value.scrollLeft += 1;
        if (scrollRef.value.clientWidth + scrollRef.value.scrollLeft == scrollRef.value.scrollWidth) {
            scrollRef.value.scrollLeft = 0
        }
        //scrollRef.value.scrollTop += 1
       /* if (scrollRef.value.clientHeight + scrollRef.value.scrollTop == scrollRef.value.scrollHeight) {
            scrollRef.value.scrollTop = 0
        }*/
    }, 30);
}



let autoUpdateForSecondTimer: any = null
const autoUpdate = () => {
    if (!autoUpdateForSecondTimer) {
        autoUpdateForSecondTimer = setInterval(() => {
            StatusListData()
            overviewList()
        }, 2000)
    }

}
const HomeHight = ref()
const computedHeight = reactive({
    powerHeight: '298px',
    centerHeight: '1100px',
    alarmHeight: '350px',
})
const sizeChange = () => {
    const rect = HomeHight.value?.getBoundingClientRect()
    if (!rect) return
    computedHeight.centerHeight = rect.height - 190 + 'px'
    if (window.screen.width < 1360) {
        computedHeight.centerHeight = rect.height - 0 + 'px'
    }
    if (rect.width < 1360) {
        computedHeight.centerHeight = rect.height - 0 + 'px'
    }
}

onMounted(() => {
    window.addEventListener('resize', sizeChange)
    sizeChange()
    //getAllChartData()
    createScroll()
    overviewList()
    StatusListData()
    autoUpdate()

    equipList({ objectType: 10002 }).then((res) => {
        res.data.map((item: any) => {
            deviceCode.value.push(item.code)
        })

        getTableData(deviceCode.value)
    })
})

onUnmounted(() => {
    window.removeEventListener('resize', sizeChange)
    clearInterval(timer)
    autoUpdateForSecondTimer && clearInterval(autoUpdateForSecondTimer)
})
</script>

<style scoped lang="scss">
$marginNum: 10px;
$labelHeight: 30px;
@mixin cardDefaultStyle {
    margin-top: $marginNum;
    margin-bottom: $marginNum;
    padding: 10px;
    border-radius: 10px;
    background-color: #fff;
}
@mixin cardlabel {
    .cardLabel {
        height: $labelHeight;
        font-size: 18px;
        font-weight: 600;
        color: #4e5969;
        line-height: 30px;
       /* padding-left: 10px;*/
    }
}
.default-main {
    width: 100%;
    height: 100%;
   /* min-height: 920px;*/
    padding: 0;
    margin: 0;
    color: #4e5969;
    background-color: #f2f3f5;
    .el-row {
        width: calc(100% - 0px);
        .el-col {
            height: calc(100% - 10px);
        }
    }
    .content-number {
        color: #333333;
        font-size: 28px;
    }
    .homelabel {
        font-family: PingFangSC-Semibold;
        font-size: 18px;
        color: #4e5969;
        letter-spacing: 0;
        line-height: 18px;
        font-weight: 600;
        margin-bottom: 10px;
        display: block;
    }
    .overview {
        width: calc(100% - 10px);
        height: 100%;
        .overviewItem{
            height: 100px;
            display: flex;
            background: #FFFFFF;
            border-radius: 6px;
            margin: 5px;
            align-items: center;
            color: #4E5969;
            .small-panel-pic{
                width: 80px;
                height: 80px;
            }
        }

    }
    .AlertPart{
        width: calc(100% - 10px);
        height: 60px;
        margin: 10px 0;
        background-image: linear-gradient(90deg, #FFE3E3 0%, #FBFDFF 100%);
        border: 2px solid #FFFFFF;
        border-radius: 6px;
        display: flex;
        align-items: center;
        .AlertPic{
            width: 50px;
            text-align: center;
            img{
                width: 24px;
                height: 24px;
            }
        }
        .realAlert{
            overflow: hidden;
            white-space: nowrap;
            cursor: pointer;
            font-size: 20px;
            color: #333333;
            width: 100%;
            p{
                padding-right: 30px;
                display: inline-block;
                span{
                    padding-right: 10px;
                }
            }
        }
    }
    .grid-content {
        /* overflow-x: hidden;*/
        width: 100%;
        height: 100%;
        .panelBg {
            background-color: #ffffff;
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 10px;
        }


        .matrix {
            @include cardlabel;
            background: url('/@/assets/dashboard/bg2.png') no-repeat #ffffff;
            background-size: 100% 100%;
           /* min-height: 900px;*/
            width: 100%;
            height: v-bind('computedHeight.centerHeight');
            margin-bottom: 0;
            .el-scrollbar {
                height: calc(100% - 20px);
            }
            .homeHeader{
                display: flex;
                .cardLabel{
                    width: 100px;
                }
            }

        }
    }
}



@media screen and (max-width: 1360px) {
    .default-main {
        font-size: 11px !important;
    }
}
@media screen and (max-width: 1480px) {
    .default-main {
        font-size: 12px !important;
        .content-number {
            font-size: 16px !important;
        }
    }
}
@media screen and (max-width: 1680px) {
    .default-main {
        /*font-size: 12px !important;*/
        .content-number {
            font-size: 18px !important;
        }

        .homelabel {
            font-size: 16px !important;
            margin-bottom: 10px !important;
        }
        .grid-content {
            .cardLabel {
                font-size: 16px !important;
            }
            .panelBg {
                /* padding: 10px !important;*/
                margin-bottom: 10px !important;
            }
        }
    }
}
</style>
