<template>
    <div class="colorMap">
        <div class="item" effect="dark" :title="$t('trials:lugano:button:colormap')">
            <div class="colorBar"
                style="display:flex;justify-content: flex-start;align-items: center;position: relative;"
                @mouseleave="isSlideMoving = false">
                <div class="tool-wrapper" style="margin-right:0px" @click.stop="showColorBarPanel($event)"
                    @mouseleave="handleColorBarMouseout">
                    <div>
                        <div class="dropdown">
                            <div id="colorBar" class="icon" style="display: flex;align-items: center;width:266px">
                                <canvas id="colorBarCanvas" />

                            </div>
                            <!-- 伪彩 -->
                            <div class="text">{{ $t('trials:lugano:button:colormap') }}</div>
                            <div class="dropdown-content" style="width:266px">
                                <ul>
                                    <li v-for="(colorMap, index) in colorMaps" :key="colorMap"
                                        style="display: flex;align-items: center;margin-bottom:5px;padding:0 5px;justify-content: space-between;"
                                        :class="{ activeLi: rgbPresetName === colorMap }"
                                        @click="setColorMap(colorMap)">
                                        <canvas :id="`colorBarCanvas${index}`" />
                                        <span style="margin-left:5px;font-size: 10px;">{{ colorMap
                                        }}</span>

                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                <div v-if="modality !== 'NM'" style="margin-left:-1px;border: 1px solid #424242;">
                    <el-input v-model="range" size="mini" style="width:120px" :maxlength="maxLength"
                        oninput="if(value){value=value.replace(/[^\d]/g,'')} if(value<=0){value=''}"
                        @change="upperRangeChange">
                        <template slot="append">g/ml</template>
                    </el-input>
                </div>
                <div id="slider" style="position: absolute;left: 6px;top:5px;cursor: pointer;">
                    <div id="sliderBox" class="slider" style="height: 17px;width: 10px;background-color: #909399;" />
                    <div id="slider-position" style="color:#ddd;font-size: 12px;">0</div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import {
    utilities as csUtils,
} from '@cornerstonejs/core'
import colormaps from '@/views/trials/trials-panel/reading/dicoms/components/Fusion/js/colormaps'
import vtkColorMaps from '@kitware/vtk.js/Rendering/Core/ColorTransferFunction/ColorMaps'
const { registerColormap, getColormapNames, getColormap } = csUtils.colormap
export default {
    name: "colorMap",
    props: {
        modality: {
            type: String,
            default: ''
        },
        maxLength: {
            type: [Number, String],
            default: 6
        }
    },
    data() {
        return {
            colorMaps: [],
            rgbPresetName: 'siemens',
            range: 40,
            upper: 6,
            isSlideMoving: false,
            req: null
        }
    },
    mounted() {
        colormaps.forEach(colormap => {
            registerColormap(colormap)
        })
        this.colorMaps = getColormapNames()
        this.colorMaps.unshift('hsv')
        this.$nextTick(() => {
            this.renderColorMaps()
            this.upperRangeChange(this.range)
            this.initSlider()
            // this.syncSliderPosition()
        })
    },
    methods: {
        syncSliderPosition(retry = 0) {
            var sliderBox = document.getElementById('sliderBox')
            var container = document.getElementById('colorBarCanvas')
            if (!sliderBox || !container) return

            var maxLeft = container.clientWidth - sliderBox.clientWidth
            if (maxLeft <= 0) {
                if (retry < 30) {
                    requestAnimationFrame(() => this.syncSliderPosition(retry + 1))
                }
                return
            }
            this.updateSliderPosition()
        },
        renderColorMaps() {
            this.createColorBar(this.rgbPresetName, 'colorBarCanvas', 256, 15)
            this.colorMaps.forEach((e, index) => {
                this.createColorBar(e, `colorBarCanvas${index}`, 180, 15)
            })
        },
        voiChange(v) {
            this.$emit('voiChange', v)
        },
        changeVoi(v) {
            // 被外部组件调窗同步时调用
            if (v === this.upper) return

            var range = Number(this.range) || 0
            var upper = Number(v) || 0
            if (range <= 0) {
                upper = 0
            } else if (upper > range) {
                upper = range
            } else if (upper < 0) {
                upper = 0
            }
            this.upper = upper
            this.syncSliderPosition()
        },
        initSlider() {
            var slider = document.getElementById('slider')
            var sliderBox = document.getElementById('sliderBox')
            var container = document.getElementById('colorBarCanvas')
            if (!slider || !sliderBox || !container) return

            slider.addEventListener('mousedown', () => {
                this.isSlideMoving = true
            })
            document.addEventListener('mousemove', (e) => {
                if (this.isSlideMoving) {
                    if (this.req) return;
                    this.req = requestAnimationFrame(() => {
                        this.req = null;
                        var containerWidth = container.clientWidth
                        var sliderWidth = sliderBox.clientWidth
                        var maxLeft = containerWidth - sliderWidth
                        if (maxLeft <= 0) return

                        var left = e.clientX - container.getBoundingClientRect().left
                        if (left < 0) {
                            left = 0
                        } else if (left > maxLeft) {
                            left = maxLeft
                        }
                        var position = left

                        slider.style.left = (left + 6) + 'px'
                        var positionValue = document.getElementById('slider-position')
                        var upper = Number(this.range) || 0
                        position = parseInt((position / maxLeft) * upper)
                        if (position > upper) position = upper
                        if (position < 0) position = 0
                        
                        if (this.modality === 'NM') {
                            positionValue.textContent = upper > 0 ? Math.round((position / upper) * 100) + '%' : '0%'
                        } else {
                            positionValue.textContent = position
                        }
                        this.upper = position
                        this.voiChange(position)
                    });
                }
            })
            document.addEventListener('mouseup', () => {
                this.isSlideMoving = false
            })
        },
        updateSliderPosition() {
            var sliderBox = document.getElementById('sliderBox')
            var container = document.getElementById('colorBarCanvas')
            if (!sliderBox || !container) return

            var containerWidth = container.clientWidth
            var sliderWidth = sliderBox.clientWidth
            var maxLeft = containerWidth - sliderWidth
            if (maxLeft <= 0) return

            var range = Number(this.range) || 0
            var upper = Number(this.upper) || 0
            if (range <= 0) {
                upper = 0
            } else if (upper > range) {
                upper = range
            } else if (upper < 0) {
                upper = 0
            }
            if (upper !== this.upper) {
                this.upper = upper
            }

            var left = range > 0 ? (upper / range) * maxLeft : 0
            if (left < 0) {
                left = 0
            } else if (left >= maxLeft) {
                left = maxLeft
            }
            var slider = document.getElementById('slider')
            if (slider) {
                slider.style.left = (left + 6) + 'px'
            }
            var positionValue = document.getElementById('slider-position')
            if (positionValue) {
                if (this.modality === 'NM') {
                    positionValue.textContent = range > 0 ? Math.round((upper / range) * 100) + '%' : '0%'
                } else {
                    positionValue.textContent = upper
                }
            }
        },
        upperRangeChange(v) {
            if (this.upper === v) return
            var nextRange = Number(v) || 0
            if (nextRange <= 0) {
                this.upper = 0
                this.updateSliderPosition()
                this.voiChange(0)
                return
            }
            this.range = nextRange
            if (this.upper > nextRange) {
                this.upper = nextRange
                this.voiChange(this.upper)
            }
            this.syncSliderPosition()
        },
        createColorBar(rgbPresetName, elId, width, height) {
            var colorMap = null
            if (rgbPresetName === 'hsv') {
                colorMap = vtkColorMaps.getPresetByName(rgbPresetName)
            } else {
                colorMap = getColormap(rgbPresetName)
            }

            const rgbPoints = colorMap.RGBPoints
            const canvas = document.getElementById(elId)
            const ctx = canvas.getContext('2d')
            const canvasWidth = width
            const canvasHeight = height
            const rectWidth = width
            const rectHeight = canvasHeight
            canvas.width = canvasWidth
            canvas.height = canvasHeight
            const gradient = ctx.createLinearGradient(0, 0, rectWidth, 0)
            for (let i = 0; i < rgbPoints.length; i += 4) {
                let position = 0
                if (rgbPoints[0] === -1) {
                    position = (rgbPoints[i] + 1) / 2
                } else {
                    position = rgbPoints[i]
                }
                const color = `rgb(${parseInt(rgbPoints[i + 1] * 255)}, ${parseInt(rgbPoints[i + 2] * 255)}, ${parseInt(rgbPoints[i + 3] * 255)})`
                gradient.addColorStop(position, color)
            }
            ctx.fillStyle = gradient
            ctx.fillRect(0, 0, rectWidth, rectHeight)
        },
        async setColorMap(rgbPresetName) {
            this.rgbPresetName = rgbPresetName
            this.createColorBar(this.rgbPresetName, 'colorBarCanvas', 256, 15)
            this.$emit("setColorMap", rgbPresetName)
        },
        showColorBarPanel(e) {
            e.currentTarget.firstChild.firstChild.lastChild.style.display = 'block'
        },
        handleColorBarMouseout(e) {
            e.currentTarget.firstChild.firstChild.lastChild.style.display = 'none'
        },
        init() {
            this.createColorBar(this.rgbPresetName, 'colorBarCanvas', 256, 15)
            this.$emit("setColorMap", this.rgbPresetName)
            this.syncSliderPosition()
        }
    }
}
</script>
<style lang="scss" scoped>
.activeLi {
    background-color: #919295;
}

.tool-wrapper {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-right: 30px;

    .icon {
        padding: 5px;
        border: 1px solid #404040;
        cursor: pointer;
        text-align: center;

        .svg-icon {
            font-size: 25px;
            color: #ddd;
        }
    }

    .text {
        position: relative;
        font-size: 12px;
        margin-top: 5px;
        color: #d0d0d0;
        display: none;
    }
}

.dropdown {
    position: relative;
    display: inline-block;

    .icon-content {
        display: flex;
        align-items: center;
        border: 1px solid #404040;
    }

    .text {
        text-align: center;
    }

    .tool-icon {
        padding: 5px;
        cursor: pointer;
        text-align: center;

        .svg-icon {
            font-size: 20px;
            color: #ddd;
        }
    }

    .arrow-icon {
        cursor: pointer;
        padding: 7px 2px 7px 0px;
    }

    .arrow-icon:hover {
        background-color: #607d8b;
    }

    .icon-content-d:hover {
        background-color: #607d8b;
    }

    .tool-icon-d {
        padding: 5px;

        .svg-icon {
            font-size: 20px;
            color: #ddd;
        }
    }

}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: #383838;
    color: #fff;
    box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
    z-index: 9999;
    font-size: 12px;

    ul {
        list-style: none;
        margin: 0;
        padding: 0;
        text-align: center;

        li {
            a {
                display: block;
                padding: 5px;
            }
        }
    }

    ul li:hover {
        background-color: #727272;
        cursor: pointer;
    }
}

.item {
    box-sizing: border-box;
    position: relative;
    border: 1px solid rgba(255, 255, 255, 0.21);
    position: relative;

    &_active {
        // border: 2px solid #ffeb3b;fff
        border: 1px dashed rgb(250, 250, 0);

    }
}

.colorBar {
    ::v-deep .el-input--mini .el-input__inner {
        height: 25px;
        line-height: 25px;
        border: none;
        background-color: transparent;
        color: #ddd;
    }
}
</style>
