<template>
  <!-- 下拉选项列表 -->
  <div class="nana-dropdown-wrapper">
    <div class="nana-dropdown" @click="isDropdownOpen=!isDropdownOpen">
      <text>{{ selectedLabel }}</text>
      <DropDownIcon :class="['arrow',isDropdownOpen?'open':'']" />
    </div>
    <div v-if="isDropdownOpen" class="nana-dropdown-options">
      <SimpleScrollView :scroll-y="true">
        <div
          v-for="(option, index) in options"
          :key="index"
          :class="[
            'option',
            selectedValue === option[valueKey] ? 'selected' : '',
          ]"
          @click="selectOption(option)"
        >
          <text>{{ option[labelKey] }}</text>
        </div>
      </SimpleScrollView>
    </div>
  </div>
  
</template>

<script setup lang="ts">
import { computed, ref, type PropType } from 'vue';
import DropDownIcon from './DropdownIcon.vue';
import SimpleScrollView from '../container/SimpleScrollView.vue';

const props = defineProps({
  options: {
    type: Array as PropType<any[]>,
    default: () => [],
  },
  labelKey: {
    type: String,
    default: 'title',
  },
  valueKey: {
    type: String,
    default: 'value',
  },
  placeholder: {
    type: String,
    default: '请选择',
  },
  selectedValue: {
    type: null
  },
})

const emit = defineEmits([ 'update:selectedValue' ])

const selectedLabel = computed(() => {
  const selectedOption = props.options.find(option => option[props.valueKey] === props.selectedValue);
  return selectedOption ? selectedOption[props.labelKey] : props.placeholder;
});
const isDropdownOpen = ref(false);

function selectOption(option: any) {
  isDropdownOpen.value = false;
  emit('update:selectedValue', option[props.valueKey]);
}

</script>

<style lang="scss">
@use "@/assets/scss/colors.scss" as *;;

.nana-dropdown-wrapper {
  position: relative;

  &.dark {
    .nana-dropdown {
      background-color: $box-dark-trans-color;
      border: 1px solid $border-dark-color; 
    }
  }
}
.nana-dropdown {
  position: relative;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding: 10px 15px;
  background-color: $box-inset-color;
  border: 1px solid $primary-color;
  user-select: none;
  cursor: pointer;

  .arrow {
    width: 15px;
    height: 15px;
    transition: transform 0.3s;  
    margin-left: 10px;

    &.open {
      transform: rotate(180deg);
    }
  }
  text {
    font-size: 17.5px;
    color: var(--nana-text-1);
  }
}
.nana-dropdown-options {
  position: absolute;
  top: 100%;
  left: 0;
  width: 300px;
  background-color: transparent;
  border: 1px solid $primary-color;
  z-index: 20;

  .nana-scroll-view {
    max-height: 50vh;
  }

  .option {
    padding: 8px 15px;
    background-color: $box-hover-color;
    user-select: none;
    cursor: pointer;

    &:hover, .selected {
      background-color: $box-hover-color;
    }
    text {
      font-size: rpx(24);
      color: $text-color;
    }
  }


}
</style>