<template>
  <div class="mm-time-picker-panel-select">
    <ul
      class="mm-time-picker-list"
      @click="handleSelect">
      <li
        v-for="item of list"
        :key="item.value"
        :class="{
          'mm-time-picker-item--disabled': item.disabled,
          'mm-time-picker-item--active': item.value === value
        }"
        class="mm-time-picker-item">
        {{ `0${item.value}`.slice(-2) }}
      </li>
    </ul>
  </div>
</template>

<script>
import { scrollTop } from "../../utils/scroll"
import { getClassName } from "../../utils/helper"

// 不能滚到顶
const SCORLL_TOP_OFFSET = 5

export default {
  name: "mm-time-picker-panel-select",
  props: {
    value: [String, Number],
    list: Array,
    visible: Boolean,
  },
  watch: {
    visible(value) {
      if (value) {
        this.scrollToSelected()
      }
    },
  },
  mounted() {
    this.scrollToSelected()
  },
  methods: {
    handleSelect(e) {
      const { target } = e
      if (target.tagName !== "LI" || getClassName(target).indexOf("disabled") > -1) {
        return
      }
      const value = target.innerText.trim()
      this.$emit("input", Number(value))
      this.scrollToSelected()
    },
    scrollToSelected() {
      this.$nextTick(() => {
        const list = this.$el
        const active = list.querySelector(".mm-time-picker-item--active")

        if (active) {
          const current = list.scrollTop
          const target = active.offsetTop - SCORLL_TOP_OFFSET
          scrollTop(list, current, target, 60)
        }
      })
    },
  },
}
</script>
