<template lang="pug">
ul.kit(v-show="refPopper" ref="kit")
  li.kit-item(
    v-for="(item, i) in list"
    :key="i"
    :class="{ 'kit-item--active': i === index }"
    @click="onClick(i)"
  )
    img(:src="getImgSrc(item)")
    .kit-item__info
      .kit-item__title
        span {{ item.abbr }}
        //- 装备才显示星级
        template(v-if="item.itemNO && item.type && item.type !== ''")
          span(
            v-for="index in Number(item.type)"
            :index="index"
          ) ★
      .kit-item__name
        span(v-if="item.title") {{ item.title }} ·
        span {{ item.name }}

    .kit-item__version {{ item.versionName }}
</template>

<script>
import PopperJS from "popper.js"

import { deps } from "../deps"
import api from "../api"
import { getKitType, getKitNO } from "../plugins/hotkey"
import { getKitAssetURL } from "../util"
import db from "../db"

export default {
  data() {
    return {
      list: [],
      keyword: "",
      close: null,
      open: () => {},
      confirm: null,
      refPopper: null,
      index: 0,
      end: null,
      gameID: deps.gameID,
    }
  },

  mounted() {
    this.init()
  },

  watch: {
    index(val) {
      this.$nextTick(() => {
        const $item = document.querySelector(".kit-item--active")
        $item && $item.scrollIntoView(false)
      })
    },

    keyword(val) {
      if(val === "") {
        this.init()
      } else {
        this.fetchList()
      }
    },

    gameID() {
      this.init()
    },
  },

  methods: {
    getImgSrc(item) {
      const type = {
        champion: "champions_avatar",
        item: "items",
        synergy: "synergies",
        talent: "talents",
      }[getKitType(item)]
      return getKitAssetURL(this.gameID, type, item.img)
    },

    onClick(i) {
      this.index = i
      this.confirm()
    },

    destroyPopper() {
      this.refPopper && this.refPopper.destroy()
      this.refPopper = null
    },

    updatePopper() {
      this.destroyPopper()

      const rect = window.getSelection().getRangeAt(0).getBoundingClientRect()
      this.refPopper = new PopperJS(
        {
          getBoundingClientRect() {
            return rect
          },
        },
        this.$refs.kit,
        {
          placement: "bottom-start",
          modifiers: {
            offset: {
              offset: "0, 10",
            },
            preventOverflow: {
              boundariesElement: "viewport",
            },
          },
        },
      )
    },

    init() {
      let l
      try {
        l = db.kitCache[deps.userID][this.gameID] || []
      } catch(_) {
        l = []
      }

      if(l.length < 10) {
        api.fetchKitHotData(this.gameID)
          .then(res => {
            const hot = Object.keys(res)
              .reduce((acc, cur) => acc.concat(res[cur]), [])
              // 过滤掉缓存在 db 里的数据
              .filter(item => !l.map(getKitNO).includes(getKitNO(item)))

            const hotLen = 10 - l.length
            this.list = l.concat(hot.slice(0, hotLen))
            this.updatePopper()
          })
      } else {
        this.list = l
      }
    },

    fetchList() {
      api.searchKit(this.gameID, this.keyword)
        .then(res => {
          this.list = res && Object.keys(res)
            .reduce((acc, cur) => acc.concat(res[cur]), [])

          this.index = 0
          if(!this.list || this.list.length === 0) {
            this.close()
          } else {
            this.open()
            this.updatePopper()
          }
        })
    },
  },
}
</script>

<style lang="stylus">
.kit
  display: flex
  flex-direction: column
  width: 300px
  max-height: 226px
  overflow: auto
  border: 1px solid $gray-3
  border-radius: 4px
  background-color: $white

.kit-item
  padding: 10px 20px
  min-height: 40px
  display: flex

  img
    width: 32px
    height: 32px

  &:hover
    background-color: $gray-4

.kit-item--active
  background-color: $gray-4

.kit-item__info
  margin-left: 10px
  display: flex
  flex-direction: column
  justify-content: space-between

.kit-item__title
  font-size: $base

.kit-item__name
  font-size: $small
  color: $gray-2

.kit-item__version
  margin-left: auto
  font-size: $small
  color: $gray-2
  display: flex
  align-items: center
</style>
