<template>
    <div class="default-main" ref="HomeHight">
        <el-row style="margin: 0px;">
            <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 class="cardBtn">
                                <el-radio-group v-model="overviewSlotData">
                                    <el-radio value="">全部</el-radio>
                                    <el-radio value="一期">一期</el-radio>
                                    <el-radio value="二期">二期</el-radio>
                                </el-radio-group>
                            </div>
                            <div class="headerRight">
                                <el-row>
                                    <el-col>
                                        <div class="overviewItem">
                                            <div class="small-base">平均风速:<span>{{ realData.attributeMap.windfarmavgwindspeed}}m/s</span></div>
                                            <div class="small-base">实时有功:<span>{{ realData.attributeMap.windfarmactivepower}}kW</span></div>
                                            <div class="small-base">实时无功:<span>{{ realData.attributeMap.windfarmreactivepower}}kVar</span></div>
                                            <div class="small-base">日发电量:<span>{{ realData.attributeMap.windfarmdayprodenergy}}万kWh</span></div>
                                            <div class="small-base">月发电量:<span>{{ realData.attributeMap.windfarmmonthprodenergy}}万kWh</span></div>
                                            <div class="small-base">年发电量:<span>{{ realData.attributeMap.windfarmyearprodenergy}}万kWh</span></div>
                                        </div>
                                        <div class="overviewItem" style="border: none;">
                                            <div class="small-base">并网:<span>{{ realData.attributeMap.turbinecountpowerprod}}台</span></div>
                                            <div class="small-base">停机/待机:<span>{{ realData.attributeMap.turbinecountidle}}台</span></div>
                                            <div class="small-base">故障:<span>{{ realData.attributeMap.turbinecountfaulted}}台</span></div>
                                            <div class="small-base">维护:<span>{{ realData.attributeMap.turbinecountservice}}台</span></div>
                                            <div style="padding: 0;" class="small-base">无通讯:<span>{{ realData.attributeMap.turbinecountdisconnected}}台</span></div>
                                        </div>
                                    </el-col>
                                </el-row>
                            </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 {  onMounted, reactive, ref, onUnmounted } from 'vue'
import { useI18n } from 'vue-i18n'
import WindContent from '/@/views/backend/home/windMatrixpage.vue'
import { getWindFarmRealData, getWindTurbineMatrixData } from '/@/api/backend/dashboard.ts'
import { dayjs, ElMessage, ElMessageBox, TableInstance } from 'element-plus'
import { getRealTimeState,malFunctionKeys } from '/@/views/backend/equipment/airBlower/utils.ts'
import { useRoute } from 'vue-router'
import { getParamList } from '/@/api/backend/SystemParam/request'
import { queryfaultCodeDict } from '/@/api/backend/theoreticalpowerCurve/request'
import { useEnumStore } from '/@/stores/enums'
import {equipList} from "/@/api/backend/realData/request";


const route = useRoute()
const enumStore = useEnumStore()
const d = new Date()
const { t } = useI18n()
let timer: any = null
let myTable = ref<TableInstance>()
const windList=ref([])

const overviewSlotData= ref('')

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

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

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/10000)
            res.data.attributeMap.windfarmmonthprodenergy = formatAttributeValue(res.data.attributeMap.windfarmmonthprodenergy/10000)
            res.data.attributeMap.windfarmyearprodenergy = formatAttributeValue(res.data.attributeMap.windfarmyearprodenergy/10000)
            res.data.attributeMap.turbinecountpowerprod =
                res.data.attributeMap.turbinecountpowerprod !== undefined
                    ? res.data.attributeMap.turbinecountpowerprod % 1 === 0
                        ? res.data.attributeMap.turbinecountpowerprod
                        : res.data.attributeMap.turbinecountpowerprod.toFixed(0)
                    : '0'
            res.data.attributeMap.turbinecountidle =
                res.data.attributeMap.turbinecountidle !== undefined
                    ? res.data.attributeMap.turbinecountidle % 1 === 0
                        ? res.data.attributeMap.turbinecountidle
                        : res.data.attributeMap.turbinecountidle.toFixed(0)
                    : '0'
            res.data.attributeMap.turbinecountdisconnected =
                res.data.attributeMap.turbinecountdisconnected !== undefined
                    ? res.data.attributeMap.turbinecountdisconnected % 1 === 0
                        ? res.data.attributeMap.turbinecountdisconnected
                        : res.data.attributeMap.turbinecountdisconnected.toFixed(0)
                    : '0'
            res.data.attributeMap.turbinecountservice =
                res.data.attributeMap.turbinecountservice !== undefined
                    ? res.data.attributeMap.turbinecountservice % 1 === 0
                        ? res.data.attributeMap.turbinecountservice
                        : res.data.attributeMap.turbinecountservice.toFixed(0)
                    : '0'
            res.data.attributeMap.turbinecountfaulted =
                res.data.attributeMap.turbinecountfaulted !== undefined
                    ? res.data.attributeMap.turbinecountfaulted % 1 === 0
                        ? res.data.attributeMap.turbinecountfaulted
                        : res.data.attributeMap.turbinecountfaulted.toFixed(0)
                    : '0'
            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,
                    turbinecountpowerprod: res.data.attributeMap.turbinecountpowerprod,
                    turbinecountidle: res.data.attributeMap.turbinecountidle,
                    turbinecountdisconnected: res.data.attributeMap.turbinecountdisconnected,
                    turbinecountservice: res.data.attributeMap.turbinecountservice,
                    turbinecountfaulted: res.data.attributeMap.turbinecountfaulted,
                },
            }

            realData.value = data
        } else {
            ElMessage.error({
                message: res.msg,
                type: 'error',
            })
        }
    })
}
const PARAM_COLOR = 'paramColor';
const PARAM_LAYOUT = 'paramLayout';
const paramColorData=ref([])
const paramLayoutData=ref([])
const getList=()=>{
    getParamList().then((res)=>{
        res.data.forEach((item, index) => {
            if (item.paramName === PARAM_COLOR && res.data && res.data[index]) {
                paramColorData.value = res.data[index].paramValueJson;
            }
            if (item.paramName === PARAM_LAYOUT && res.data && res.data[index]) {
                paramLayoutData.value = res.data[index].paramValueJson;
            }
        });
    })
}
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(
        {
            objectType: 10002,
            belongProject: overviewSlotData.value,
            attributesList: [
                'iwindspeed',
                'iturbineoperationmode',
                'iyplevel',
                'gridlostdetected',
                'ibplevel',
                'igenpower',
                'ikwhthisday',
                'Locked',
                'ProcessedOperationMode',
                'iRotorSpeed',
                'ActiveStatusCode01',
                'ActiveStatusCode02',
                'ActiveStatusCode03',
                'ActiveStatusCode04',
                'ActiveStatusCode05',
                'ActiveStatusCode06',
                'ActiveStatusCode07',
                'ActiveStatusCode08',
                'FirstTriggeredCode'
            ]
        }
    ).then((res) => {
        if (res.code == 200) {
            currentDayStatus.value.windTurbineNum = res.data.length
            const data = res.data.map((item, index) => {
                let color:any=''
                const state = getRealTimeState(item.attributeMap)
                let firsttriggeredcode=item.attributeMap.firsttriggeredcode
                if (enumStore.keys.includes('FirstTriggeredCode')) {
                    firsttriggeredcode = enumStore.data['FirstTriggeredCode'][firsttriggeredcode]
                }
                /*if (malFunctionKeys.includes('FirstTriggeredCode')) {
                    firsttriggeredcode = malFunctionEnums?.[firsttriggeredcode] ?? firsttriggeredcode
                }
*/
                paramColorData.value.forEach((item, index) => {
                    if (item.state == state) {
                        color = item.color
                    }
                })

                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 ?? '-',
                    deviceCode:item.deviceCode,
                    model: item.model || '-',
                    modelId: item.modelId,
                    belongLine: item.belongLine || '-',
                    standard: item.standard,
                    layout:paramLayoutData.value[0],
                    madeinFactory: item.madeinFactory || '-',
                    attributeMap: {
                        iwindspeed: item.attributeMap.iwindspeed,
                        igenpower: item.attributeMap.igenpower,
                        ikwhthisday: item.attributeMap.ikwhthisday,
                        iturbineoperationmode: state,
                        processedoperationmode: state,
                        color:color,
                        locked: item.attributeMap.locked,
                        irotorspeed: item.attributeMap.irotorspeed,
                        firsttriggeredcode:firsttriggeredcode,
                        //firsttriggeredcode:item.attributeMap.firsttriggeredcode,
                    },
                }
            })
            FanList.value = data
        } else {
            ElMessage.error({
                message: res.msg,
                type: 'error',
            })
        }
    })
}
let malFunctionEnums: any = {}
/*const getMalfunctionEnums = () => {
    windList.value.forEach((item)=> {
        console.log({madeinfactory: item.madeinfactory, model: item.model })
        queryfaultCodeDict({madeinfactory: item.madeinfactory, model: item.model }).then((res) => {
            if (res.code == 200) {
                const data: any = {}
                res.data.forEach((item: any) => {
                    data[item.code] = item.description
                })
                malFunctionEnums = data
            }  else {
                console.warn('查询故障代码字典失败:', res.message);
            }
        })
    })

}*/

/*const requestedParams = new Set<string>();

const fetchData = async (item: any) => {
    // 创建一个唯一的键来标识参数组合
    const key = `${item.madeinFactory}-${item.model}`;

    // 检查这个键是否已经在 Set 中
    if (requestedParams.has(key)) {
        console.log('Duplicate request detected, skipping...');
        return;
    }
    // 将键添加到 Set 中
    requestedParams.add(key);

    try {
        console.log({ madeinfactory: item.madeinFactory, model: item.model })
        const response = await queryfaultCodeDict({ madeinfactory: item.madeinFactory, model: item.model });
        if (response.code === 200) {
            const data: any = {};
            response.data.forEach((item: any) => {
                data[item.code] = item.description;
            });
            malFunctionEnums = data;
        } else {
            console.warn('查询故障代码字典失败:', response.message);
        }
    } catch (error) {
        console.error('请求出错:', error);
    }
};*/


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 - 0 + 'px'
    if (window.screen.width < 1360) {
        computedHeight.centerHeight = rect.height - 0 + 'px'
    }
    if (rect.width < 1360) {
        computedHeight.centerHeight = rect.height - 0 + 'px'
    }
}

onMounted(() => {
    getList()
    window.addEventListener('resize', sizeChange)
    sizeChange()
    equipList({ objectType: 10002 }).then((res) => {
        res.data.map((item: any) => {
            deviceCode.value.push(item.code)
        })
        windList.value=res.data.map((item: any) => {
            //fetchData(item)
            return {
                madeinfactory:item.madeinFactory,
                model: item.model ?? '-',
            }
        })
        //getMalfunctionEnums()
    })

    overviewList()
    StatusListData()
    autoUpdate()
})

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: 22px;
    }
    .homelabel {
        font-family: PingFangSC-Semibold;
        font-size: 18px;
        color: #4e5969;
        letter-spacing: 0;
        line-height: 18px;
        font-weight: 600;
        margin-bottom: 10px;
        display: block;
    }
    .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/bg3.png') no-repeat #ffffff;
            background-size: 100% 100%;
            width: 100%;
            height: v-bind('computedHeight.centerHeight');
            margin-bottom: 0;
            .el-scrollbar {
                height: calc(100% - 20px);
            }
            .homeHeader{
                display: flex;
                justify-content: space-between;
                .cardLabel{
                   margin-right: 10px;
                    white-space: nowrap;
                }
                .cardBtn{
                    white-space: nowrap;
                    :deep(.el-radio-group){
                        flex-wrap: nowrap;

                    }
                    :deep(.el-radio){
                        margin-right: 12px;
                    }
                }
                .headerRight{
                    width: 100%;
                    display: flex;
                    background: #F0F6FF;
                    border-radius: 8px;
                    line-height: 30px;
                    padding: 0 10px;
                    .overviewItem{
                        display: inline-block;
                        .small-base{
                            display: inline-block;
                            padding-right: 8px;
                            color: #4E5969;
                            span{
                                color: #000000;
                            }
                        }
                    }

                }

            }

        }
    }
}
@media screen and (max-width: 1280px) {
    .default-main {
        font-size: 12px !important;
        .content-number {
            font-size: 16px !important;
        }
        .overviewItem{
            .small-panel-pic{
                width: 40px!important;
                height: 40px!important;
            }

        }
    }
}


@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: 16px !important;
        }
        .overviewItem{
            .small-panel-pic{
                width: 60px!important;
                height: 60px!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>
