<template>
  <view>
    <text v-if="label" :class="['dict-tag', tagClass]">{{ label }}</text>
    <text v-else class="dict-tag dict-tag-empty">{{ placeholder }}</text>
  </view>
</template>

<script>
import { getDicts } from '@/api/oa/dict.js'

export default {
  name: 'DictTag',
  props: {
    dictType: {
      type: String,
      required: true
    },
    value: {
      type: [String, Number],
      default: ''
    },
    placeholder: {
      type: String,
      default: ''
    },
    colorMap: {
      // 可选，传入字典值与颜色的映射
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      options: [],
      label: ''
    }
  },
  computed: {
    tagClass() {
      if (!this.value) return ''
      const color = this.colorMap[this.value]
      return color ? `dict-tag-${color}` : ''
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.setLabel(val)
      }
    },
    dictType: {
      immediate: true,
      handler() {
        this.fetchOptions()
      }
    }
  },
  methods: {
    async fetchOptions() {
      if (!this.dictType) return
      const res = await getDicts(this.dictType)
      this.options = res.data || []
      this.setLabel(this.value)
    },
    setLabel(val) {
      const item = this.options.find(item => item.dictValue == val)
      this.label = item ? item.dictLabel : ''
    }
  }
}
</script>

<style scoped>
.dict-tag {
  display: inline-block;
  padding: 4rpx 16rpx;
  border-radius: 16rpx;
  font-size: 26rpx;
  background: #f5f5f5;
  color: #333;
  margin-right: 8rpx;
}
.dict-tag-empty {
  color: #bbb;
  background: #fafafa;
}
/* 可自定义颜色映射样式 */
.dict-tag-blue { background: #e6f7ff; color: #1890ff; }
.dict-tag-green { background: #f6ffed; color: #52c41a; }
.dict-tag-red { background: #fff1f0; color: #f5222d; }
.dict-tag-orange { background: #fff7e6; color: #fa8c16; }
.dict-tag-gray { background: #f5f5f5; color: #888; }
</style>
