<template>
  <div class="legend-container">
    <div class="legend-big">
      <div class="color-bar-big" v-if="background" :style="{ background: background }"></div>
    </div>
    <div class="legend">
      <div class="color-bar" v-if="background" :style="{ background: background }"></div>
      <div class="labels">
        <div
            class="level"
            v-for="(level, index) in levels"
            :key="index"
            :style="{ left: `${(index / (levels.length - 1)) * 100}%` }"
        >
          <div class="tick"></div> <!-- 添加刻度 -->
          <div class="label">{{ level }}</div> <!-- 将标签内容放入一个新的div中 -->
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import eventBus from "@/api/eventBus";
import {ref} from "vue";
let colorsRef = ref([]);
let levels = ref([]);
let background = ref("");
let legendImg = ref(null);
function gradientListener() {
  const colorStops = colorsRef.value.map((color, index) => {
    const percentage = (index / (colorsRef.value.length - 1)) * 100;
    return `${color} ${percentage}%`;
  });
  background.value = `linear-gradient(to right, ${colorStops.join(", ")})`;
  console.log(background.value)

}

function updateColors({colors,labels,name, legendUrl}) {
  if(legendUrl){
    legendImg.value = legendUrl
    return
  }
  legendImg.value = null
  if(colors === undefined || colors.length === 0) return;
  colorsRef.value = colors;
  levels.value = colors.map((color, index) => {
    return labels[index];
  });
  gradientListener()
}

eventBus.off("alarmList:changeMapLayer", updateColors)
eventBus.on("alarmList:changeMapLayer", updateColors)
</script>

<style lang="scss" scoped>
.legend-container {
  display: flex;
  flex-direction: column;
  align-items: center;background: #fff;
  padding: 10px 10px 30px 10px;
  opacity: 0.6;
}
.legend-big{
  width: 100%;
}

.legend {
  margin-top: 10px;
  width: 50%;
}
.color-bar-big{
  width: 100%;
  height: 30px;
}

.color-bar {
  width: 100%;
  height: 10px;
  border: 1px solid #000;
}

.labels {
  position: relative;
  margin-top: 5px;
  .level {
    position: absolute;
    top: 50%; /* 将水平标签居中 */
    transform: translateY(-50%);
    width: 2px; /* 设置刻度条的宽度 */
    height: 100%;
    color: #000;
    font-size: 12px;
  }

  .tick {
    position: absolute;
    top: -5px; /* 调整刻度的位置，使其位于标签上方 */
    height: 10px; /* 刻度的高度 */
    width: 2px; /* 刻度的宽度 */
    background-color: black; /* 刻度的颜色 */
  }

  .label {
    position: absolute;
    top: 10px; /* 调整标签的位置，使其位于刻度下方 */
    left: 0px; /* 通过调整这个值来使标签居中于刻度 */
    transform: translateX(-50%);
    white-space: nowrap;
  }
}


</style>
