<template>
  <text class="dict-label" :style="labelStyle">{{ displayText || '-' }}</text>
</template>

<script setup>
import { computed } from 'vue'
import dictUtil from '../../utils/dict.js'

const props = defineProps({
  modelValue: {
    type: [String, Number, Boolean],
    default: ''
  },
  type: {
    type: String,
    required: true
  },
  dataRange: {
    type: Array,
    default: () => []
  }
})

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

const hexToRgb = (hex) => {
  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 labelInfo = computed(() => {
  if (props.dataRange && props.dataRange.length > 0) {
    const data = props.dataRange.find(k => k.value == props.modelValue)
    if (data) {
      return { text: data.label, color: data.color || '#000000' }
    }
    return { text: '', color: '' }
  }

  const dictList = dictUtil.getDictList(props.type)
  const dict = dictList.find(k => k.value == props.modelValue || k.value === String(props.modelValue))
  if (dict) {
    const colorIndex = (dict.value || 0) % 8
    return { text: dict.name || dict.label, color: dict.color || colorList[colorIndex] }
  }
  return { text: '', color: '' }
})

const displayText = computed(() => labelInfo.value.text)

const labelStyle = computed(() => {
  const color = labelInfo.value.color || '#000000'
  const { r, g, b } = hexToRgb(color)
  return {
    backgroundColor: `rgba(${r},${g},${b},0.15)`,
    color: `rgb(${r},${g},${b})`
  }
})
</script>

<style scoped>
.dict-label {
  display: inline-block;
  padding: 4rpx 16rpx;
  font-size: 22rpx;
  font-weight: 600;
  line-height: 1.6;
  text-align: center;
  white-space: nowrap;
  border-radius: 6rpx;
}
</style>
