<template>
  <div class="BI-board-content">
    <div class="BI-board-list">
      <table-no-data v-if="value.length===0" style="flex:1"/>
      <div
        class="BI-board-item-box"
        v-for="(item, index) in value"
        :key="item.BiDashboardDetailId"
        @dragover.prevent
        @drop="drop(index)"
      >
        <component :is="getCompType(item.Type)" :compData="item">
          <template v-slot:drag>
            <!-- Draggable icon -->
            <img
              v-if="canDrag"
              class="icon"
              src="~@/assets/img/data_m/move_ico.png"
              alt=""
              @mousedown="setDraggable(true, index)"
              @dragstart="dragStart(index)"
              @dragend="setDraggable(false, index)"
              style="cursor: move"
            />
          </template>
          <template v-slot:delete>
            <img class="icon" v-if="canDelete" src="~@/assets/img/icons/delete-red.png" alt="" @click="handleDel(index)"/>
          </template>
        </component>
      </div>
    </div>
  </div>
</template>

<script>
import TableNoData from '../../../components/tableNoData.vue';
import ChartBox from './ChartBox.vue';
import TableBox from './TableBox.vue';

export default {
  components: { ChartBox, TableBox, TableNoData },
  props: {
    value: {
      type: Array,
      default: () => []
    },
    canDrag: {//能否拖动
      type: Boolean,
      default: true
    },
    canDelete:{//能否删除
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      draggedIndex: null,
    };
  },
  methods: {
    getCompType(type) {
      return type === 1 ? ChartBox : TableBox;
    },
    handleDel(index){
      this.value.splice(index,1)
      this.$emit('delete',this.value)
    },
    setDraggable(draggable, index) {
      const box = this.$el.querySelectorAll('.BI-board-item-box')[index];
      box.draggable = draggable;
    },
    dragStart(index) {
      this.draggedIndex = index;
    },
    drop(index) {
      if (this.draggedIndex === null) return
      // Swap the two items
      const temp = this.value[this.draggedIndex];
      this.$set(this.value, this.draggedIndex, this.value[index]);
      this.$set(this.value, index, temp);
      this.draggedIndex = null;
      this.$emit('input',this.value)
      this.$emit('change',this.value)
    },
  }
};
</script>

<style lang="scss" scoped>
.BI-board-content {
  padding: 20px;
  .BI-board-list {
    height: calc(100vh - 300px);
    overflow-y: auto;
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    .BI-board-item-box {
      width: calc(50% - 14px);
      height: 560px;
      border: 1px solid #dcdfe6;
      box-shadow: 0px 2px 8px 0px #00000014;
    }
  }
}
</style>
