<script setup lang="ts">
import { computed } from 'vue';
import { useDict } from '@/hooks/business/dict';
import DictText from './dict-text.vue';

defineOptions({ name: 'DictTag' });

type DictValue = string | number;
type DictTagType = 'primary' | 'success' | 'info' | 'warning' | 'danger';
type DictTagEffect = 'dark' | 'light' | 'plain';
type DictTagSize = 'large' | 'default' | 'small';

interface Props {
  dictCode: string;
  value?: DictValue | DictValue[] | null;
  fallback?: string;
  separator?: string;
  onlyEnabled?: boolean;
  /** 显式传入时优先；不传则按字典 item.colorType 自动取色 */
  type?: DictTagType;
  effect?: DictTagEffect;
  size?: DictTagSize;
  round?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  value: null,
  fallback: '--',
  separator: ' / ',
  onlyEnabled: false,
  type: undefined,
  effect: 'light',
  size: 'default',
  round: false
});

const { getItem } = useDict(() => props.dictCode);

// 单值才支持自动取色；多值（数组）走默认渲染避免歧义
const autoColorType = computed<string | null>(() => {
  if (Array.isArray(props.value)) return null;
  if (props.value === null || props.value === undefined || props.value === '') return null;
  return getItem(props.value, { onlyEnabled: props.onlyEnabled })?.colorType ?? null;
});

// props.type 优先（向后兼容）；其次字典 colorType（hex）；都没有时回落到原生 ElTag 默认
const hexColor = computed(() => (props.type ? null : autoColorType.value));

const tagStyle = computed<Record<string, string> | null>(() => {
  if (!hexColor.value) return null;
  // light 效果：浅底 + 主色字 + 中浅边；plain/dark 同样的色调思路，仅明度差异
  const fg = hexColor.value;
  if (props.effect === 'dark') {
    return {
      color: '#fff',
      background: fg,
      borderColor: fg
    };
  }
  if (props.effect === 'plain') {
    return {
      color: fg,
      background: 'transparent',
      borderColor: `color-mix(in srgb, ${fg} 50%, white)`
    };
  }
  // light（默认）
  return {
    color: fg,
    background: `color-mix(in srgb, ${fg} 12%, white)`,
    borderColor: `color-mix(in srgb, ${fg} 30%, white)`
  };
});
</script>

<template>
  <ElTag
    :type="props.type"
    :effect="props.effect"
    :size="props.size"
    :round="props.round"
    :style="tagStyle ?? undefined"
  >
    <DictText
      :dict-code="props.dictCode"
      :value="props.value"
      :fallback="props.fallback"
      :separator="props.separator"
      :only-enabled="props.onlyEnabled"
      tag="span"
    />
  </ElTag>
</template>

<style scoped></style>
