<template>
  <el-dialog
    :visible.sync="visible"
    title="拖拽排序"
    :close-on-click-modal="false"
    width="600"
    draggable
  >
    <div
      class="item"
      v-for="(item, i) in drag.list"
      :key="item.id"
      draggable="true"
      @dragstart="dragstart($event, i)"
      @dragenter="dragenter($event, i)"
      @dragend="dragend"
      @dragover="dragover"
    >
      {{ item.title }}
    </div>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
    </template>
  </el-dialog>
</template>
<script>
// import { sortCarouselImage } from "@/api/cloudStore.js";
import debounce from "lodash/debounce";
// import { provinceAndCityData, regionData } from "element-china-area-data";
export default {
  data() {
    return {
      visible: false,
      dataForm: {},
      drag: {
        list: [],
      },

      dragIndex: 0,
    };
  },
  computed: {},
  watch: {
    visible(newVal, oldVal) {
      if (newVal == false) {
      }
    },
  },
  methods: {
    init(row) {
      this.drag.list = JSON.parse(JSON.stringify(row));
      this.visible = true;
    },
    dragstart(e, index) {
      e.stopPropagation();
      this.dragIndex = index;
      setTimeout(() => {
        e.target.classList.add("moveing");
      }, 0);
    },
    dragenter(e, index) {
      e.preventDefault();
      // 拖拽到原位置时不触发
      if (this.dragIndex !== index) {
        const source = this.drag.list[this.dragIndex];
        this.drag.list.splice(this.dragIndex, 1);
        this.drag.list.splice(index, 0, source);

        // 更新节点位置
        this.dragIndex = index;
      }
    },
    dragover(e) {
      e.preventDefault();
      e.dataTransfer.dropEffect = "move";
    },
    dragend(e) {
      e.target.classList.remove("moveing");
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        console.log(this.drag.list);
        let id = this.drag.list.map((item) => {
          return item.id;
        });
        console.log(id);
        this.$api.mer_admin.sortnotice({ ids: id }).then((res) => {
          console.log(res);
          this.$emit("queryList");
          this.visible = false;
        });
      },
      1000,
      { leading: true, trailing: false }
    ),
  },
};
</script>
<style scoped>
.item {
  width: 500px;
  height: 40px;
  line-height: 40px;
  /* // background-color: #f5f6f8; */
  background-color: skyblue;
  text-align: center;
  margin: 10px;
  color: #fff;
  font-size: 18px;
}

.container {
  position: relative;
  padding: 0;
}

.moveing {
  opacity: 0;
}
</style>
