<template>
  <view class="drop-down">
    <button class="btn" plain @click="openPicker" >
      <view class="flex btn-label">
        <view :style="{ color }">{{ label }}</view>
        <uv-icon name="arrow-down-fill" :color="color" size="14rpx"></uv-icon>
      </view>
    </button>

    <template v-if="popupVisible">
      <view class="drop-down-overlay" @click="closePicker"></view>
      
      <view class="card drop-down-popup" :style="popupStyle">
        <view 
          v-for="item in options" 
          class="flex drop-down-option" 
          :class="[item.value === value ? 'is-active' : '']"
          :key="item.value"
          @click="onSelect(item.value)"
        >
          <text>{{ item.label }}</text>
        </view>
      </view>
    </template>
  </view>
</template>


<script>
	export default {
    props: {
      value: {
        type: String | Number,
        default: null,
      },
      options: {
        type: Array,
        default() {
          return []
        }
      },
      label: {
        type: String,
        default: ''
      },
    },
		data() {
      return {
        popupVisible: false,
        popupStyle: {},
      }
    },
    computed: {
      isActive() {
        return this.options.find(option => option.value === this.value)
      },
      color() {
        return this.isActive ? '#4883F9' : '#000000'
      }
    },
    methods: {
      openPicker() {
        console.log('openPicker', this.label)
        this.popupVisible = true
      },
      closePicker() {
        console.log('closePicker', this.label)
        this.popupVisible = false
      },
			onSelect(val) {
				const selected = this.value
        const newVal = selected === val ? '' : val
        
        this.$emit('input', newVal)
        this.$emit('change', newVal)

        this.closePicker()
			},
    },
  }
</script>

<style scoped lang="scss">
.drop-down {
  position: relative;
  clear: both;

  .btn {
    width: 213rpx;
    padding: 27rpx 0;
    font-size: 24rpx;
    background: transparent;
    border: none;

    &-label {
      column-gap: 9rpx;
    }
  }

  &-overlay {
    position: fixed;
    width: 100vw;
    height: calc(100vh - #{$navbar-height} - var(--status-bar-height) - 20rpx);
    background: transparent;
    bottom: 0;
    left: 0;
    z-index: 98;
    font-size: 0;
  }

  &-popup {
    position: absolute;
    z-index: 99;
    width: 213rpx;
    background: #FFFFFF;
    border-radius: 15rpx;
    transform: translateY(-15rpx);
  }

  &-option {
    color: #000000;
    font-size: 24rpx;
    padding: 7rpx 0;
    text-align: center;

    &.is-active {
      color: #4883F9;
    }

    & + & {
      border-top: 1rpx solid #EFEFEF;
    }
  }
}
</style>