<template>
  <view class="dict-tag" :class="tagClass">{{ label }}</view>
</template>

<script>
import dictMixin from '@/utils/mixins/dictMixin';

export default {
  name: 'DictTag',
  mixins: [dictMixin],
  props: {
    // 字典类型
    dictType: {
      type: String,
      required: true
    },
    // 字典值
    value: {
      type: [String, Number],
      required: true
    },
    // 是否带颜色样式
    colored: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      dictTypeList: [] // 将通过created动态设置
    };
  },
  computed: {
    // 字典标签
    label() {
      return this.getDictLabel(this.dictType, this.value, '');
    },
    // 标签样式类
    tagClass() {
      if (!this.colored) return '';
      const className = this.getDictClass(this.dictType, this.value, '');
      return className ? `tag-${className}` : '';
    }
  },
  created() {
    // 检查父组件是否已加载此字典
    let parentWithDict = this.findParentWithDict(this.dictType);
    
    if (parentWithDict) {
      // 父组件已加载此字典，使用父组件的字典数据
      if (parentWithDict.dictData && parentWithDict.dictData[this.dictType]) {
        this.$set(this.dictData, this.dictType, parentWithDict.dictData[this.dictType]);
      }
    } else {
      // 父组件未加载此字典，自己加载
      this.dictTypeList = [this.dictType];
      this.loadDict();
    }
  },
  methods: {
    // 查找已加载指定字典类型的父组件
    findParentWithDict(dictType) {
      let parent = this.$parent;
      while (parent) {
        if (parent.dictData && parent.dictData[dictType]) {
          console.log(`[DictTag] Found parent with dictionary ${dictType} already loaded`);
          return parent;
        }
        parent = parent.$parent;
      }
      console.log(`[DictTag] No parent found with dictionary ${dictType}, loading it independently`);
      return null;
    }
  }
};
</script>

<style scoped>
.dict-tag {
  display: inline-block;
  padding: 0 10rpx;
  height: 40rpx;
  line-height: 40rpx;
  font-size: 26rpx;
  color: #666;
  border-radius: 20rpx;
  text-align: center;
  white-space: nowrap;
}

.tag-primary {
  color: #fff;
  background-color: #409EFF;
}

.tag-success {
  color: #fff;
  background-color: #67C23A;
}

.tag-info {
  color: #fff;
  background-color: #909399;
}

.tag-warning {
  color: #fff;
  background-color: #E6A23C;
}

.tag-danger {
  color: #fff;
  background-color: #F56C6C;
}

.tag-secondary {
  color: #fff;
  background-color: #8A69F9;
}

.tag-default {
  color: #333;
  background-color: #E9E9E9;
}
</style> 