<template>
  <span class="status-label" :style="state.style">{{ state.text || "-" }}</span>
</template>

<script setup lang="ts">
import { onMounted, reactive, watch } from "vue";
import dictUtil from "@/utils/dict";

defineOptions({ name: "ExtDLabel" });

const props = defineProps({
  modelValue: {
    type: [Number, String, Boolean]
  },
  type: {
    type: String,
    required: true
  },
  dataRange: {
    type: Array as () => Array<{ label: string; value: any; color?: string }>,
    default: () => []
  }
});

const state = reactive({
  text: "" as string,
  style: {} as Record<string, string>
});

const colorList = [
  "#FFB800",
  "#009688",
  "#1E9FFF",
  "#00C7D2",
  "#599CDE",
  "#FF5722",
  "#eb2f96",
  "#4a5055"
];

const hexToRgb = (hex: string) => {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result
    ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
      }
    : { r: 0, g: 0, b: 0 };
};

const setupColorStyle = (hex: string = "#000000") => {
  const { r, g, b } = hexToRgb(hex);
  return {
    "background-color": `rgba(${r},${g},${b},0.2)`,
    color: `rgb(${r},${g},${b})`
  };
};

const setupLabel = () => {
  if (props.dataRange && props.dataRange.length > 0) {
    const data = props.dataRange.find(k => k.value == props.modelValue);
    if (data) {
      state.text = data.label;
      state.style = setupColorStyle(data.color || "#000000");
    }
  } else {
    const dictList = dictUtil.getDictList(props.type);
    const dict = dictList.find(
      (k: any) => k.value == props.modelValue || k.value === String(props.modelValue)
    );
    if (dict) {
      state.text = dict.name || dict.label;
      const colorIndex = (dict.value || 0) % 8;
      state.style = setupColorStyle(colorList[colorIndex]);
    }
  }
};

watch(() => props.modelValue, setupLabel);

onMounted(() => {
  setupLabel();
});
</script>

<style scoped lang="scss">
.status-label {
  display: inline-block;
  padding: 5px 6px 1px 6px;
  font-size: 12px;
  font-weight: 600;
  line-height: 1;
  height: 20px;
  text-align: center;
  white-space: nowrap;
  vertical-align: baseline;
  border-radius: 2px;
  margin-top: 3px;
  width: auto;
}
</style>
