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

<script>
import { clearSampleCache } from '../clearSampleCache'

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, index) {
      // 如果删除了一个选中的
      if (spectraItem.checked) {
        // // 如果是倒数第一个，则选中上一个
        if (index == this.list.length - 1) {
          this.handleClick(this.list[index - 1])
        }
        // 否则选中下一个
        else {
          this.handleClick(this.list[index + 1])
        }
      }
      const deleted = this.list.splice(index, 1)
      clearSampleCache(deleted)
      this.$forceUpdate()
    },
  },
  watch: {
    list(newVal) {
      if (newVal.length && !newVal.find((item) => item.checked)) {
        this.handleClick(newVal[0])
      }
    },
  },
}
</script>

<style lang="less" scoped>
.spectra-list-in-menu {
  &-item {
    display: flex !important;
    align-items: center;
  }

  .checkbox {
    width: 14px;
  }

  .name {
    flex: 1;
    margin: 0 5px;
  }
}
</style>
