<template>
    <div class="slider_demo_block">
        <!-- pH计 -->
        <el-slider :model-value="safeSensorValue[0]" vertical disabled :max="14" :min="0" :marks="marks"
            class="ph_slider" :class="getPhClass" :style="sliderStyle" />
    </div>
</template>

<script setup>
import { computed } from 'vue'

const props = defineProps({
    sensorValue: {
        type: Array,
        default: () => [6.6] // 默认值设为 [6.6]
    },
    sensorWidth: {
        type: Number,
        default: 10,
    },
    sensorHeight: {
        type: Number,
        default: 100,
    },
})

// 安全处理 sensorValue，避免传空数组或无效值
const safeSensorValue = computed(() => {
    return Array.isArray(props.sensorValue) && props.sensorValue.length > 0
        ? props.sensorValue
        : [6.6]
})

// 获取颜色和 class
function getPhColor(val) {
    if (val >= 9) return { class: 'ph_purple', color: '#9C27B0' } // 强碱
    if (val >= 7) return { class: 'ph_blue', color: '#2196F3' }   // 弱碱
    if (val >= 6) return { class: 'ph_green', color: '#4CAF50' }  // 中性
    if (val >= 4) return { class: 'ph_orange', color: '#FF9800' } // 弱酸
    return { class: 'ph_red', color: '#F44336' }                  // 强酸
}

// class
const getPhClass = computed(() => getPhColor(safeSensorValue.value[0]).class)

// 刻度 marks
const marks = computed(() => {
    const temp = safeSensorValue.value[0]
    if (temp == null || isNaN(temp)) return {}

    const { color } = getPhColor(temp)
    const valueNum = Number(temp)
    const valueLabel = valueNum.toFixed(1)

    return {
        [valueNum]: {
            style: { color, fontWeight: 'bold' },
            label: `pH: ${valueLabel}`,
        },
    }
})

// 动态样式
const sliderStyle = computed(() => ({
    '--marks-font-size': `${Math.max(props.sensorWidth * 0.9, 18)}px`,
    '--runway-width': `${props.sensorWidth}px`,
    '--slider-height': props.sensorHeight ? `${props.sensorHeight}px` : '0.5em',
}))
</script>

<style scoped lang="scss">
.slider_demo_block {
    max-width: 600px;
    display: flex;
    align-items: center;
}

:deep(.ph_slider) {
    height: var(--slider-height, 0.5em);

    .el-slider__button {
        display: none;
    }

    .el-slider__marks-text {
        font-size: var(--marks-font-size);
        left: 130%;
    }

    .el-slider__runway {
        width: var(--runway-width);
    }

    .el-slider__bar,
    .el-slider__marks-stop {
        width: 100%;
    }
}

// pH 颜色样式
:deep(.ph_green .el-slider__bar) {
    background-color: #4CAF50;
}

:deep(.ph_orange .el-slider__bar) {
    background-color: #FF9800;
}

:deep(.ph_red .el-slider__bar) {
    background-color: #F44336;
}

:deep(.ph_blue .el-slider__bar) {
    background-color: #2196F3;
}

:deep(.ph_purple .el-slider__bar) {
    background-color: #9C27B0;
}
</style>
