<template>
    <div class="page">
        <HeaderComponent title="烛式过滤器--模拟器"></HeaderComponent>
        <div class="content_page">
            <!-- 左侧操作栏 -->
            <!-- <div class="left_operation">
                <el-switch v-model="isControl" active-text="控制" inactive-text="展示" size="large" />
            </div> -->


            <!-- 右下 -->
            <!-- <div class="left_bottom">
                <el-card class="button_card" shadow="hover">
                    <template #header>
                        操作按钮
                    </template>
                    <div class="button_grid">
                        <el-button type="primary" class="grid_button" @click="lightControl(0)">
                            初始化
                        </el-button>
                        <el-button type="danger" class="grid_button" @click="lightSceneControl(1)">
                            分离模块罐体<br>
                            液体泄漏
                        </el-button>
                        <el-button type="primary" class="grid_button" @click="lightSceneControl(2)">
                            料仓加料模块<br>
                            物料短缺
                        </el-button>
                        <el-button type="info" class="grid_button" @click="lightSceneControl(3)">
                            分离模块罐体<br>
                            试验测试
                        </el-button>
                        <el-button type="warning" class="grid_button" @click="lightSceneControl(4)">
                            韫珠车间<br>
                            开关异常
                        </el-button>
                        <el-button type="primary" class="grid_button" @click="lightSceneControl(5)">
                            热交换模块<br>
                            液体开关检修维护
                        </el-button>
                    </div>
                </el-card>
            </div> -->
            <!-- 阀门 -->
            <div class="valves">
                <component v-for="item in deviceConfigGroup.VALVES" :key="item.id" :is="getComponentName(item.modelId)"
                    :title="getEquipmentTitle(item.equipmentName)"
                    :valveStatusArr="getDataArrByCode(item.equipmentName)" :rotateAngle="item.rotate || 0"
                    :iconSize="item.size" :style="getComponentStyle(item)" @click="clickValves(item.code)" />
            </div>

            <!-- 罐体 -->
            <div class="tanks">
                <component v-for="item in deviceConfigGroup.TANKS" :key="item.id" :is="getComponentName(item.modelId)"
                    :title="getEquipmentTitle(item.equipmentName)" :iconSize="item.size"
                    :style="getComponentStyle(item)" />
            </div>

            <!-- 传感器 -->
            <div class="sensors">
                <component v-for="item in deviceConfigGroup.SENSORS" :key="item.id" :is="getComponentName(item.modelId)"
                    :sensorValue="sensorHelper.getDataArrByCode(item.code)" :sensorWidth="item.width"
                    :sensorHeight="item.height" :sensorSize="item.size" :style="getComponentStyle(item)" />
            </div>

            <!-- 管道  -->
            <div class="pipelines">
                <component v-for="item in pipeConfig" :key="item.id" :is="getComponentName(item.modelId)"
                    :pipeStatus="evaluateCondition(item.flowCondition)" :strokeWidth="item.pipeWidth"
                    :style="getPipelineStyle(item, evaluateCondition(item.reverseCondition))"
                    :class="getPipelineClass(item.pipeClass, getPipeType(item.dynamicPipelineCondition))" />
            </div>
            <!-- 大箭头指向 -->
            <div class="arrows">
                <Arrow flexDir="row" :iconFirst="false" arrowDir="right" arrowText="进气口" class="arrow_pos1" />
                <Arrow flexDir="row" :iconFirst="false" arrowDir="right" arrowText="母液入口" class="arrow_pos2" />
                <Arrow flexDir="row" arrowDir="right" arrowText="出液口1" class="arrow_pos3" />
                <Arrow flexDir="row" arrowDir="right" arrowText="出液口2" class="arrow_pos4" />
                <Arrow flexDir="row" arrowDir="up" arrowText="排气" class="arrow_pos5" />
                <Arrow flexDir="row" arrowDir="right" arrowText="出液口" class="arrow_pos6" />
                <Arrow flexDir="row" arrowDir="down" arrowText="固体出口" class="arrow_pos7" />

            </div>
        </div>
    </div>
</template>

<script setup>
import Arrow from '@/components/HnyzDcs/ArrowComponent.vue';
import { useValveHelper } from '@/hooks/useValveHelper'
import { computed, onMounted, onBeforeUnmount, reactive, ref } from 'vue';
import { useRoute } from 'vue-router';
import { stompClient } from '@/utils/ws/stompClient';
import { updateZTPageConfig } from '@/api/dcs/configurePage';
import { setValues } from '@/api/dcs/flowControl';
import { getMainSetParam } from '@/api/hnyz/param'
import { openInfoElNotification } from '@/utils/message'
import { useEquipmentLayout } from '@/hooks/useEquipmentLayout'
import { useComponentHelper } from '@/hooks/useComponentHelper'

const route = useRoute();
const pageCode = route.name;

// 获取设备布局
// 获取设备布局 
const {
    pipeConfig,//管道配置信息
    deviceConfigGroup,//设备配置分组
    modelMap,//设备模型映射
    pageParams,//页面参数
    fetchPageConfig,//获取页面配置
} = useEquipmentLayout(pageCode)

// 组件渲染辅助方法
const {
    getComponentName,
    getComponentStyle,
    getIconClass,
    getEquipmentTitle,
    getPipelineClass,
    getPipelineStyle,
} = useComponentHelper(modelMap)


onMounted(async () => {
    await fetchPageConfig(pageCode).then(res => {
        updatePageConfig()
    })
})

onBeforeUnmount(() => {
    // 页面销毁时取消订阅
    stompClient.unsubscribeFromPage(pageCode);
});

const valveArr = [
    {
        code: 'FM1',
        value: [false]
    },
    {
        code: 'FM2',
        value: [false]
    },
    {
        code: 'FM3',
        value: [false]
    },
    {
        code: 'FM4',
        value: [false]
    },
    {
        code: 'FM5',
        value: [false]
    },
    {
        code: 'FM6',
        value: [false]
    },
    {
        code: 'FM7',
        value: [false]
    },
    {
        code: 'FM8',
        value: [false]
    },
    {
        code: 'FM9',
        value: [false]
    },
    {
        code: 'FM10',
        value: [false]
    },
    {
        code: 'FM11',
        value: [false]
    },
]
//传感器状态
const sensorArr = [
    {
        code: 'PT1001',
        value: [0.66]
    },
    {
        code: 'PT1002',
        value: [1]
    },
    {
        code: 'PT1003',
        value: [1]
    },
]


//设备数据分组
const deviceDataGroup = reactive({
    VALVES: valveArr,
    // PUMPS: pumpArr,
    SENSORS: sensorArr,
})

//更新页面配置
function updatePageConfig() {
    updateZTPageConfig(pageCode, pageParams.value)
        .then(res => {
            stompClient.subscribeToPage(pageCode, (data) => {
                deviceDataGroup.VALVES = Object.values(data.VALVES)
                // deviceDataGroup.PUMPS = Object.values(data.PUMPS)
                deviceDataGroup.SENSORS = Object.values(data.SENSORS)
            });
        })
        .catch(err => {
            console.log('页面配置失败：', err);
        });
}
// const pumpHelper = useValveHelper(computed(() => deviceDataGroup.PUMPS))
const { getDataArrByCode, getValveStatusArr, getValveAndStatus, getValveOrStatus, evaluateCondition, getPipeType } = useValveHelper(computed(() => deviceDataGroup.VALVES))
const sensorHelper = useValveHelper(computed(() => deviceDataGroup.SENSORS))

const isControl = ref(false)

// const lightList = [100, 0]// 灯控配置
const lightList = [
    '00', // 0 白色
    '01', // 韫珠办公楼
    '02', // 雪豹办公室
    '03', // 分离模块
    '04', // 吸附模块
    '05', // 加料模块
    '06', // 公共模块
    '07', 
    '08', 
    '09', 
    '10', 
    '11', 
    '12'
]// 灯控配置
// 0 白色 1 绿色 2 红色 3橙色 4 蓝色 5紫色 6 彩虹色 7 青色 8黄色
const lightColor = [
    'ffffff', // 0 白色
    '00ff00', // 1 绿色 正常运行
    'ff0000', // 2 红色 严重异常/生产线停止
    'ffa500', // 3 橙色 告警/预警
    '0000ff', // 4 蓝色 物料请求/投料
    '800080', // 5 紫色 质检/审核
    'ff69b4', // 6 彩虹色 粉色识别为彩虹色 测试/实验
    '00ffff', // 7 青色 待启动
    'ffff00'  // 8 黄色 保养中
]
const lightState = ref(0)// 当前灯光状态

// 6种情景场景定义，存储在lightScene数组中
const lightScene = [
    [
        {id: 1, color: 6}, {id: 7, color: 6},
        {id: 2, color: 6}, {id: 8, color: 6},
        {id: 3, color: 6}, {id: 9, color: 6},
        {id: 4, color: 6}, {id: 10, color: 6},
        {id: 5, color: 6}, {id: 11, color: 6},
        {id: 6, color: 6}, {id: 12, color: 6}
    ],
    // 情景1：分离模块罐体液体泄露
    [
        {id: 10, color: 2}, {id: 4, color: 2},
        {id: 6, color: 2},
    ],
    // 情景2：料仓加料模块的物料短缺
    [
        {id: 12, color: 4}, {id: 5, color: 4},
    ],
    // 情景3：分离模块罐体1进行试验测试
    [
        {id: 10, color: 6}, {id: 3, color: 6},
    ],
    // 情景4：韫珠车间开关异常
    [
        {id: 8, color: 3}, {id: 1, color: 3},
    ],
    // 情景5：热交换模块液体开关检修维护
    [
        {id: 8, color: 7}, {id: 3, color: 7},
    ],
]
function lightControl(e, colorItem) {
    if (e == 0) {
        setValues({
            "dataType": "string",
            "lengthOrQos": 1,
            "unitId": 0,
            "offsetOrIndex": 0,
            "protocol": 3,
            "data": [
                '00 00 000000', "ygtx", "T!8dFz$kW3#pRgM2"
            ],
            "ipAddress": "222.243.138.146",
            "port": 1883,
            "resource": "yzkj/zkshi/esp32/12led",
        })
        return
    }
    if (e == 99) {
        console.log('99')
        asyncLightControl(
            ...lightScene[0]
        )
        return
    }
    lightChange(e)
}

function lightSceneControl(e) {
    asyncLightControl(
        ...lightScene[e]
    )
}

function asyncLightControl(...e) {
    if (e.length === 0) return;
    lightChange(e[0].id, e[0].color);
    if (e.length > 1) {
        setTimeout(() => {
            asyncLightControl(...e.slice(1));
        }, 100);
    }
}

function lightChange(i, colorItem) {
    lightState.value = i
    const light = lightList[i]
    const color = colorItem == undefined ? lightColor[i<=8?i:i-8] : lightColor[colorItem]
    const state = color == 'ff69b4' ? '02' : '01'

    console.log('灯控', light, state, color)

    const data = {
        "dataType": "string",
        "lengthOrQos": 1,
        "unitId": 0,
        "offsetOrIndex": 0,
        "protocol": 3,
        "data": [
            light + " " + state + " " + color, "ygtx", "T!8dFz$kW3#pRgM2"
        ],
        "ipAddress": "222.243.138.146",
        "port": 1883,
        "resource": "yzkj/zkshi/esp32/12led",
    }
    setValues(data)
}

function clickValves(code) {
    if (isControl.value) {
        getMainSetParam(code).then(res => {
            const registerData = res.data
            // console.log('获取设备参数成功：', registerData)
            const data = {
                protocol: registerData.protocolId,                    // MODBUS_TCP 协议
                unitId: registerData.unitId,                      // 从站 ID
                dataType: registerData.dataType,                 // 1 表示布尔型
                resource: '05',                  // 功能码，05 是写单个线圈
                offsetOrIndex: registerData.address,   // 起始地址
                lengthOrQos: 1,                // 数量
                data: [!getDataArrByCode(code)[0]],                 // 写入的值，例如 [true]
                ipAddress: registerData.ipAddress,    // 你的 Modbus TCP 服务地址
                port: registerData.port                      // 默认端口
            }
            setValues(data)
        }).catch(err => {
            console.log('获取设备参数失败：', err);
        });

    }
}

</script>

<style lang="scss" scoped>
.page {
    width: 1920px;
    height: 1080px;
    background-color: #0b172c;

    .content_page {
        position: relative;
        width: 100%;
        height: 1000px;

        .left_operation {
            position: absolute;
            top: 2%;
            left: 2%;

            :deep(.el-switch__label) {
                color: #fff;
            }

        }

        .left_bottom,
        .right_bottom {
            position: absolute;
            bottom: 5%;
            left: 10%;

            .button_card {
                width: 100%;

                .el-card__header {
                    font-weight: bold;
                    font-size: 16px;
                    text-align: center;
                }

                .button_grid {
                    display: grid;
                    grid-template-columns: repeat(3, 1fr); // 每行3个
                    gap: 12px; // 按钮间距

                    .el-button+.el-button {
                        margin-left: 0;
                    }
                }

                .grid_button {
                    width: 100%;
                }
            }
        }

        .left_bottom {
            bottom: 70%;
            left: 3%;
        }

        .right_bottom{
            left: unset;
            right: 10%;
        }



        .arrows {
            .arrow_pos1 {
                position: absolute;
                top: 42%;
                left: 15%;
            }

            .arrow_pos2 {
                position: absolute;
                top: 56%;
                left: 20%;
            }

            .arrow_pos3 {
                position: absolute;
                top: 9%;
                left: 83%;
            }

            .arrow_pos4 {
                position: absolute;
                top: 41%;
                left: 83%;
            }

            .arrow_pos5 {
                position: absolute;
                top: 15%;
                left: 42.5%;
            }

            .arrow_pos6 {
                position: absolute;
                top: 56%;
                left: 68%;
            }

            .arrow_pos7 {
                position: absolute;
                top: 90%;
                left: 47.3%;
            }

        }

    }
}
</style>