<template>
  <a-menu class="spectra-list-in-menu">
    <a-menu-item v-for="item in list" :key="item.sampleId" @click="handleClick(item)">
      <span class="checkbox">
        <a-icon v-if="item.checked" type="check" style="color: #0de30d" />
      </span>
      <span class="name">{{ getFileName(item.inputFileName) }}</span>
      <a-icon type="delete" @click.stop="handleRemove(item)" />
    </a-menu-item>
  </a-menu>
</template>

<script>
export default {
  props: {
    list: {
      type: Array,
      default: () => []
    }
  },
  methods: {
    handleClick(spectraItem) {
      this.list.forEach(item => (item.checked = false))
      spectraItem && (spectraItem.checked = true)
      this.$emit('change', spectraItem)
      this.$forceUpdate()
    },

    handleRemove(spectraItem) {
      const index = this.list.findIndex(item => item == spectraItem)
      this.list.splice(index, 1)
      // 如果删除了一个选中的
      if (spectraItem.checked) {
        if (index == 0) {
          // 如果是第一个，则选中下一个
          this.handleClick(this.list[0])
        } else {
          // 如果不是第一个，则选中上一个
          this.handleClick(this.list[index - 1])
        }
      }
      this.$forceUpdate()
    },

    /**
     * 获取文件名
     * @param {String} inputFileName
     */
    getFileName(inputFileName) {
      if (inputFileName) {
        const arr = inputFileName.split('/')
        return arr[arr.length - 1]
      }
    }
  },
  watch: {
    list(newVal) {
      if (newVal.length) {
        this.handleClick(newVal[0])
      }
    }
  }
}
</script>

<style lang="less" scoped>
.spectra-list-in-menu {
  .checkbox {
    width: 14px;
    height: 14px;
    display: inline-block;
  }

  .name {
    display: inline-block;
    width: 300px;
    margin: 0 5px;
    overflow: hidden;
    text-overflow: ellipsis;
    vertical-align: top;
  }
}
</style>
