<template>
  <div class="filter-dropdown">
    <div class="selected-filter" @click="toggleDropdown">
      {{ selectedOption }}
      <span class="arrow-down"></span>
    </div>
    <div class="dropdown-menu" v-show="isOpen">
      <div 
        v-for="(option, index) in options" 
        :key="index" 
        class="menu-item"
        @click="selectOption(option)"
      >
        {{ option.label }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onBeforeUnmount } from 'vue';

const props = defineProps({
  options: {
    type: Array,
    required: true,
    default: () => []
  },
  modelValue: {
    type: [String, Number, Object],
    default: ''
  },
  placeholder: {
    type: String,
    default: '全部'
  }
});

const emit = defineEmits(['update:modelValue', 'change']);

const isOpen = ref(false);
const selectedOption = ref(props.placeholder);

// 初始化选中项
onMounted(() => {
  if (props.modelValue) {
    const option = props.options.find(opt => opt.value === props.modelValue);
    if (option) {
      selectedOption.value = option.label;
    }
  }
  
  // 添加点击外部关闭下拉菜单的事件监听
  document.addEventListener('click', handleClickOutside);
});

onBeforeUnmount(() => {
  // 移除事件监听
  document.removeEventListener('click', handleClickOutside);
});

// 监听modelValue变化
watch(() => props.modelValue, (newValue) => {
  if (newValue) {
    const option = props.options.find(opt => opt.value === newValue);
    if (option) {
      selectedOption.value = option.label;
    }
  } else {
    selectedOption.value = props.placeholder;
  }
});

// 切换下拉菜单显示状态
function toggleDropdown(event) {
  event.stopPropagation();
  isOpen.value = !isOpen.value;
}

// 选择选项
function selectOption(option) {
  selectedOption.value = option.label;
  isOpen.value = false;
  emit('update:modelValue', option.value);
  emit('change', option);
}

// 点击外部关闭下拉菜单
function handleClickOutside(event) {
  const dropdown = event.target.closest('.filter-dropdown');
  if (!dropdown) {
    isOpen.value = false;
  }
}
</script>

<style scoped>
.filter-dropdown {
  position: relative;
  display: flex;
  align-items: center;
  background: rgba(19, 26, 36, 0.5);
  border-radius: 4px;
  padding: 5px 10px;
  cursor: pointer;
  font-size: 12px;
  color: #fff;
}

.selected-filter {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.arrow-down {
  width: 0;
  height: 0;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-top: 5px solid #fff;
  margin-left: 5px;
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  left: 0;
  background: #3B4047;
  border-radius: 4px;
  width: 100%;
  z-index: 10;
  margin-top: 2px;
}

.menu-item {
  padding: 8px 10px;
  font-size: 13px;
  white-space: nowrap;
}

.menu-item:hover {
  background: #464C55;
}
</style> 