<template>
  <div class="c-select flex items-center justify-between relative" ref="select">
    <div class="c-selected-name">
      {{ selectedName }}
    </div>
    <div class="c-arrow">
      <div
        class="c-img transform transition-transform bg-cover"
        :class="{
          '-rotate-180': open,
        }"
        :style="{
          backgroundImage: `url(${arrowDownIcon})`,
        }"
      ></div>
    </div>
    <transition name="slide">
      <div
        class="absolute top-full z-50 c-optionList w-full left-0 mt-1"
        v-if="open"
      >
        <div
          v-for="(option, i) in optionList"
          :key="i"
          class="relative px-5 h-9 leading-9 text-text-color"
          :class="{
            ' text-footer-color': option.value === selectedValue,
          }"
          @click="$emit('change', option.value)"
        >
          {{ option.name }}
          <div
            class="absolute w-full h-full top-0 left-0 hover:bg-footer-color"
            style="opacity: 0.03;"
            :class="{
              ' bg-footer-color': option.value === selectedValue,
            }"
          ></div>
        </div>
      </div>
    </transition>
  </div>
</template>
<script lang="ts">
import Vue, { PropType } from 'vue'
import arrowDownIcon from '@/assets/images/blockChainBrowser/arrow-down-dark.png'

export default Vue.extend({
  props: {
    optionList: Array as PropType<
      {
        name: string
        value: string | number
      }[]
    >,
    selectedValue: [String, Number],
  },
  data() {
    return {
      arrowDownIcon,
      open: false,
    }
  },
  mounted() {
    window.addEventListener('click', this.clickGrobal)
  },
  beforeDestroy() {
    window.removeEventListener('click', this.clickGrobal)
  },
  methods: {
    clickGrobal(e: MouseEvent) {
      const selectEl = this.$refs.select as HTMLElement
      const clickoutside = !selectEl.contains(e.target as HTMLElement)
      if (clickoutside) {
        this.open = false
      } else {
        this.open = !this.open
      }
    },
  },
  computed: {
    selectedName(): string {
      return (
        this.optionList.find((i) => i.value === this.selectedValue)?.name || ''
      )
    },
  },
})
</script>
<style lang="scss" scoped>
.c-select {
  padding: 0 20px;
  height: 30px;
  background: #ffffff;
  border-radius: 15px;
  border: 1px solid #d9dcde;
  .c-img {
    width: 9px;
    height: 6px;
  }
  .c-optionList {
    min-height: 0px;
    max-height: calc(36px * 5);
    background: #ffffff;
    box-shadow: 0px 2px 15px 0px rgba(31, 52, 112, 0.06);
    border-radius: 4px;
    border: 1px solid #ebeff1;
  }

  .fade-enter-active,
  .fade-leave-active {
    transition: opacity 5s;
  }
  .fade-enter,
  .fade-leave-to {
    opacity: 0;
  }

  .slide-enter-active {
    transition: all 0.3s ease-in-out;
  }
  .slide-enter {
    opacity: 0;
  }
}
</style>
