<script setup lang="ts">
import type { CSelectItem } from '@/types/HomeTypes'
import { CSelectType } from '@/types/HomeTypes'

interface Props {
  selectInfo: {
    [key: string]: CSelectItem
  }
  selectStyle?: string
}

withDefaults(defineProps<Props>(), {
  selectStyle: 'width: 150px; margin-right: 10px',
})

const emits = defineEmits(['changeSelect'])

/**
 * @description: 选择改变，向外抛出事件
 * @param {*} newVal 新值
 * @param {*} name 新值对应的字段名
 * @param {*} item 当前选择项
 * @return {*}
 */
const changeSelect = (newVal: any, name: string, item: CSelectItem) => {
  // 这里如果有图例的话需要去同步一下cnName
  if (item.label) {
    item.label = item.options.find(item => item.value === newVal)?.label
  }
  emits('changeSelect', newVal, name)
}
</script>

<template>
  <div style="display: flex; align-items: center">
    <template v-for="selectItem in selectInfo">
      <div style="display: inline-flex; align-items: center">
        <div
          class="legendColor"
          v-if="selectItem.type === CSelectType.RadioLegend"
          :style="{ backgroundColor: selectItem.color }"
        ></div>
        <!-- 对于值为对象的选项需要给value-key，默认为value -->
        <el-select
          v-model="selectItem.value"
          placeholder=""
          @change="changeSelect(selectItem.value, selectItem.name, selectItem)"
          v-bind="$attrs"
          :multiple="
            selectItem.type === CSelectType.Multiple ||
            selectItem.type === CSelectType.MultipleTag
          "
          collapse-tags
          :style="selectStyle"
          :value-key="typeof selectItem.value === 'object' ? 'name' : 'value'"
        >
          <el-option
            v-for="listItem in selectItem.options"
            :key="listItem.value"
            :label="listItem.label"
            :value="listItem.value"
          />
          <template #tag v-if="selectItem.type === CSelectType.MultipleTag">
            <span style="font-size: 14px; color: #606266; padding-left: 5px">{{
              selectItem.tagText
            }}</span>
          </template>
        </el-select>
      </div>
    </template>
  </div>
</template>

<style scoped>
.legendColor {
  width: 20px;
  height: 15px;
  margin-right: 8px;
  border-radius: 3px;
}
</style>
