<template>
    <div class="flow_single flow_others">
        <div class="flow_single_title">{{ title }}</div>
        <div class="flow_single_show">
            <!-- 状态区域（方形指示灯） -->
            <div class="show_body">
                <div class="show_body_left">状态</div>
                <div class="show_body_right">
                    <div class="show_detail status_indicator_container">
                        <!-- 绿色方形灯（启动） -->
                        <div class="indicator square green" :class="{ active: pumpStatus === 'start' }"></div>
                        <!-- 红色方形灯（停止） -->
                        <div class="indicator square red" :class="{ active: pumpStatus === 'stop' }"></div>
                        <!-- 黄色方形灯（故障） -->
                        <div class="indicator square yellow" :class="{ active: pumpStatus === 'fault' }"></div>
                    </div>
                </div>
            </div>

            <!-- 独立操作行 -->
            <div class="show_body operation_row">
                <div class="show_body_left">操作</div>
                <div class="show_body_right">
                    <div class="show_detail operation_buttons">
                        <el-button size="small" type="success" :disabled="!pumpSetArr.length || pumpStatus === 'start'"
                            @click="setPump(pumpSetArr[0], true)">
                            启动
                        </el-button>
                        <el-button size="small" type="danger" :disabled="!pumpSetArr.length || pumpStatus === 'stop'"
                            @click="setPump(pumpSetArr[0], false)">
                            停止
                        </el-button>
                    </div>
                </div>
            </div>

            <!-- 转速（优化布局） -->
            <div class="show_body speed_section" v-if="pumpDataArr.length > 1">
                <div class="show_body_left">转速</div>
                <div class="show_body_right speed_container">
                    <div class="speed_item">
                        <div class="text">实时值</div>
                        <div class="body_show">
                            <div class="body_show_value">
                                {{ (pumpDataArr[1] / 50) || 0 }}
                            </div>
                            <div class="body_show_unit">{{ pumpSetArr[1]?.unitType || '%' }}</div>
                        </div>
                    </div>
                    <div class="speed_item">
                        <div class="text">设定值</div>
                        <div class="body_show">
                            <!-- 使用原生input并自定义样式 -->
                            <input v-model="speedValue" type="number" :min="0" :max="100" class="custom-input"
                                @blur="onSpeedInputBlur" placeholder="输入值">
                            <div class="body_show_unit">{{ pumpSetArr[1]?.unitType || '%' }}</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 进料量（与实时值样式统一） -->
            <div class="show_body speed_section" v-if="pumpDataArr.length > 2">
                <div class="show_body_left">进料</div>
                <div class="show_body_right speed_container">
                    <div class="speed_item">
                        <div class="text">进料量</div>
                        <div class="body_show">
                            <div class="body_show_value">
                                {{ (pumpDataArr[2]) || 0 }}
                            </div>
                            <div class="body_show_unit">kg</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { openElWarnMessage } from '@/utils/message';
import { getAllSetParam } from '@/api/hnyz/param'
import { setValues } from '@/api/dcs/flowControl';

const props = defineProps({
    title: String,
    dataArr: {
        type: Array,
        default: () => []
    },
    code: String,
});

const pumpDataArr = computed(() => props.dataArr || [3, 0]);
const pumpSetArr = ref([])

const loadPumpSetParams = async (code) => {
    try {
        const res = await getAllSetParam(code);
        pumpSetArr.value = res.data || [];
    } catch (err) {
        console.log("获取设备参数失败：", err);
        pumpSetArr.value = [];
    }
}

onMounted(() => {
    if (props.code) {
        loadPumpSetParams(props.code);
    }
});

watch(() => props.code, (newCode) => {
    if (newCode) {
        loadPumpSetParams(newCode);
    }
});

const speedValue = ref();
const statusWord = ref(['', '正转', '反转', '停机', '故障'])

const pumpStatus = computed(() => {
    const code = pumpDataArr.value[0];
    if (code === 1 || code === 2) return 'start';  // 启动状态
    if (code === 3) return 'stop';                 // 停止状态
    if (code === 4) return 'fault';                // 故障状态
    return 'stop';
});

const frequencyOptions = [
    { value: 1, label: '正转' },
    { value: 2, label: '反转' },
    { value: 5, label: '停止' }
]

function setPump(registerData, value) {
    const open = 0;
    const close = 2;
    const setValue = value ? frequencyOptions[open].value : frequencyOptions[close].value;
    setPumpVaule(registerData, setValue);
    if (!value && pumpSetArr.value[1]) {
        setPumpVaule(pumpSetArr.value[1], 0);
    }
}

function setPumpVaule(registerData, value) {
    if (!registerData) {
        openElWarnMessage('未获取到设定地址');
        return;
    }
    const data = {
        protocol: registerData.protocolId,
        unitId: registerData.unitId,
        dataType: registerData.dataType,
        offsetOrIndex: registerData.address,
        lengthOrQos: 1,
        data: [value],
        ipAddress: registerData.ipAddress,
        port: registerData.port
    }
    setValues(data).catch(err => {
        openElWarnMessage('设置失败：' + (err.message || '未知错误'));
    });
}

function onSpeedInputBlur() {
    if (!pumpSetArr.value.length) {
        openElWarnMessage('未获取到设定地址');
        return;
    }
    // 验证输入值范围
    if (speedValue.value < 0) speedValue.value = 0;
    if (speedValue.value > 100) speedValue.value = 100;
    if (speedValue.value !== undefined && speedValue.value !== null) {
        setPumpVaule(pumpSetArr.value[1], speedValue.value * 50);
    }
}
</script>

<style scoped lang="scss">
.flow_single {
    display: flex;
    padding: 6px;
    flex-direction: column;
    border-radius: 5px;
    border: 1px solid #72E0FF;
    background: linear-gradient(to bottom, #0e1a2d, #11243e);


    .flow_single_title {
        padding: 4px 8px;
        text-align: center;
        color: #76E1FF;
        font-size: 20px;
        font-weight: bold;
        border-radius: 0px 0px 5px 5px;
        background: #192846;
    }

    .flow_single_show {
        display: flex;
        flex-direction: column;
        color: #FFF;
        gap: 8px;
        padding-top: 5px;
        width: 100%;
    }
}

.flow_others {
    width: 300px;
    margin: 10px;
}

.show_body {
    display: flex;
    align-items: center;
    gap: 10px;
    width: 100%;

    .show_body_left {
        margin: auto;
        width: 50px;
        text-align: center;
        padding: 7px 0;
        font-size: 14px;
        background: #0e2b60;
        border-radius: 5px;
        color: #63c8c7;
        flex-shrink: 0;
        /* 固定宽度不收缩 */
    }

    .show_body_right {
        flex-grow: 1;
        /* 占满剩余宽度 */
        display: flex;
        align-items: center;
        margin: 0;
    }

    .show_detail {
        display: flex;
        align-items: center;
        width: 100%;
    }
}

/* 状态指示灯样式 */
.status_indicator_container {
    justify-content: space-around;
    padding: 5px 0;
    width: 100%;
}

.indicator {
    width: 24px;
    height: 24px;
    opacity: 0.3;
    transition: all 0.3s ease;
    border: 2px solid rgba(255, 255, 255, 0.3);
    flex: 1;
    max-width: 30px;
}

.indicator.square {
    border-radius: 3px;
}

.indicator.active {
    opacity: 1;
    box-shadow: 0 0 8px 1px currentColor;
}

.green {
    background-color: #4cd964;
    color: #4cd964;
}

.yellow {
    background-color: #ffcc00;
    color: #ffcc00;
}

.red {
    background-color: #ff3b30;
    color: #ff3b30;
}

/* 操作按钮区域样式 */
.operation_buttons {
    justify-content: space-around;
    width: 100%;
    gap: 10px;
    padding: 5px 0;
}

.operation_buttons :deep(.el-button) {
    flex: 1;
    max-width: 100px;
}

.operation_row {
    margin-top: 5px;
}

/* 转速和进料量共用样式 */
.speed_section {
    align-items: flex-start;
    padding: 5px 0;
}

.speed_container {
    flex-direction: column;
    align-items: stretch;
    gap: 6px;
    width: 100%;
}

.speed_item {
    display: flex;
    align-items: center;
    width: 100%;
    gap: 12px;
}

.speed_item .text {
    text-align: right;
    font-size: 13px;
    min-width: 55px;
    color: #b8cee5;
}

.speed_item .body_show {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-grow: 1;
}

.speed_item .body_show_value {
    text-align: center;
    flex-grow: 1;
    font-size: 14px;
    border: solid 1px #B8CEE5;
    border-radius: 5px;
    padding: 2px 8px;
    min-height: 24px;
    // line-height: 24px;
}

/* 自定义输入框样式 */
.custom-input {
    flex-grow: 1;
    height: 24px;
    padding: 0 8px;
    font-size: 14px;
    color: #fff;
    background-color: rgba(15, 36, 62, 0.5);
    border: 1px solid #B8CEE5;
    border-radius: 5px;
    text-align: center;
    outline: none;
    box-sizing: border-box;
    transition: all 0.2s ease;
}

.custom-input:focus {
    border-color: #72E0FF;
    box-shadow: 0 0 0 2px rgba(114, 224, 255, 0.2);
}

.custom-input::placeholder {
    color: #88a0b8;
    font-size: 12px;
}

/* 移除数字输入框的默认箭头 */
.custom-input::-webkit-outer-spin-button,
.custom-input::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

.custom-input[type=number] {
    -moz-appearance: textfield;
}

.body_show_unit {
    font-size: 13px;
    color: #b8cee5;
    white-space: nowrap;
}
</style>