<template>
  <div>
    <template v-for="(item, index) in options">
      <template v-if="isValueMatch(item.value)">
        <span
          v-if="(item.elTagType == 'default' || item.elTagType == '') && (item.elTagClass == '' || item.elTagClass == null)"
          :key="item.value" :index="index" :class="item.elTagClass">{{ item.label + " " }}</span>
        <a-tag v-else :disable-transitions="true" :key="item.value + ''" :index="index" :color="getColor(item.elTagType)"
          :class="item.elTagClass + ' ' + size">{{ item.label + " " }}</a-tag>
      </template>
    </template>
    <template v-if="unmatch && showValue">
      {{ unmatchArray || handleArray }}
    </template>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'

interface DictOption {
  label: string;
  value: string;
  elTagType?: string;
  elTagClass?: string;
}

// 记录未匹配的项
const unmatchArray = ref<any>([])

const props = defineProps({
  // 数据
  options: {
    type: Array as () => Array<DictOption>,
    default: null,
  },
  // 当前的值
  value: [Number, String, Array],
  // 当未找到匹配的数据时，显示value
  showValue: {
    type: Boolean,
    default: true,
  },
  separator: {
    type: String,
    default: ",",
  },
  size: {
    type: String,
    default: 'mini',
  },
})

const values = computed(() => {
  if (props.value === null || typeof props.value === 'undefined' || props.value === '') return []
  if (typeof props.value === 'number' || typeof props.value === 'boolean') return [props.value]
  return Array.isArray(props.value) ? props.value.map(item => '' + item) : String(props.value).split(props.separator)
})

const unmatch = computed(() => {
  unmatchArray.value = []
  // 没有value不显示
  if (props.value === null || typeof props.value === 'undefined' || props.value === '' || !Array.isArray(props.options) || props.options.length === 0) return false
  // 传入值为数组
  let unmatch = false // 添加一个标志来判断是否有未匹配项
  values.value.forEach(item => {
    if (!props.options.some(v => v.value == item)) {
      unmatchArray.value.push(item)
      unmatch = true // 如果有未匹配项，将标志设置为true
    }
  })
  return unmatch // 返回标志的值
})

function handleArray(array: string[]) {
  if (array.length === 0) return ""
  return array.reduce((pre, cur) => {
    return pre + " " + cur
  })
}

function isValueMatch(itemValue: string) {
  return values.value.some(val => val == itemValue)
}

function getColor(tagType: string | undefined) {
  switch (tagType) {
    case 'primary':
      return 'processing'
    case 'success':
      return 'success'
    case 'info':
      return 'info'
    case 'warning':
      return 'warning'
    case 'danger':
      return 'error'
    default:
      return 'default'
  }
}
</script>

<style scoped>
.ant-tag+.ant-tag {
  margin-left: 10px;
}

.ant-tag{
  &.large {
    font-size: 18px;
    line-height: 28px;
  }
  &.medium {
    font-size: 16px;
    line-height: 24px;
  }
  &.mini {
    font-size: 12px;
    line-height: 20px;
  }
}
</style>
