<template>
  <!--  拖拽demo-->
  <transition-group name="drag" class="list" tag="ul">
    <template v-if="!disabled">
      <li v-for="(item, index) in selectedList" :key="item.groupId">
        <span>{{ `第${index + 1}志愿:` }}</span>
        <span class="list-item move"
              @dragenter="dragenter($event, index)"
              @dragover="dragover($event, index)"
              @dragstart="dragstart(index)"
              draggable="true"
        >{{ item.groupName }}</span>
        <el-button style="cursor: pointer" @click="del(index)" size="mini"  type="danger">删除</el-button>
      </li>
    </template>
    <template v-else>
      <li v-for="(item, index) in selectedList" :key="item.groupId">
        <span>{{ `第${index + 1}志愿:` }}</span>
        <span class="list-item">{{ item.groupName }}</span>
      </li>
    </template>

  </transition-group>
</template>
<script>
export default {
  props: {
    selectedList: Array,
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dragIndex: '',
      enterIndex: ''
    }
  },
  methods: {
    dragstart(index) {
      this.dragIndex = index
    },
    dragenter(e, index) {
      e.preventDefault()
      // 避免源对象触发自身的dragenter事件
      if (this.dragIndex !== index) {
        const source = this.selectedList[this.dragIndex]
        this.selectedList.splice(this.dragIndex, 1)
        this.selectedList.splice(index, 0, source)
        // 排序变化后目标对象的索引变成源对象的索引
        this.dragIndex = index
      }
    },
    del(index) {
      this.selectedList[index].selected = false
      this.selectedList.splice(index, 1)
    },
    dragover(e, index) {
      e.preventDefault()
    }
  }
}
</script>
<style lang="scss" scoped>
.list {
  padding-left: 0;
  list-style: none;

  .drag-move {
    transition: transform .3s;
  }

  li {
    font-size: 14px;
    margin-bottom: 6px;
  }

  .move {
    cursor: move;
  }

  .list-item {

    display: inline-block;
    margin: 0 10px;
    width: 160px;
    background: #42b983;
    border-radius: 4px;
    font-size: 14px;
    color: #FFF;
    height: 30px;
    line-height: 30px;
    text-align: center;
  }
}
</style>
