<template>
  <a-tag :closable="closable" :color="color">{{ value || placeholder }}</a-tag>
</template>

<script>
import { ajaxGetDictItems, getDictItemsFromCache } from '@/api/api'

export default {
  name: 'JDictTag',
  props: {
    dictCode: String,
    text: String,
    placeholder: {
      type: String,
      default: '--'
    },
    closable: Boolean,
    color: String,
  },
  data() {
    return {
      value: '',
    }
  },
  watch: {
    dictCode: {
      immediate: true,
      handler() {
        this.initDictData()
      },
    },
  },
  methods: {
    initDictData() {
      console.log(this.dictCode, this.text)
      // 如果没有dictCode或text，直接返回
      if (!this.dictCode || !this.text) {
        this.value = this.placeholder
        return
      }

      // 优先从缓存中读取字典配置
      const dictOptions = getDictItemsFromCache(this.dictCode)
      if (dictOptions) {
        this.setDictValue(dictOptions)
        return
      }

      // 从后端获取字典数据
      ajaxGetDictItems(this.dictCode, null).then((res) => {
        if (res.success && Array.isArray(res.result)) {
          this.setDictValue(res.result)
        }
      }).catch(error => {
        console.error('获取字典数据失败:', error)
        this.value = this.placeholder
      })
    },
    setDictValue(dictOptions) {
      const found = dictOptions.find((item) => item.value === this.text)
      this.value = found ? found.text : this.placeholder
    }
  },
}
</script>