<template>
  <q-modal v-model="visible" maximized>
    <q-modal-layout>
        <q-toolbar slot="header">
            <q-btn flat round dense @click="close" icon="reply" />
            <q-toolbar-title>
                应用排序
            </q-toolbar-title>
        </q-toolbar>
        <q-toolbar slot="footer">
            <q-toolbar-title></q-toolbar-title>
            <q-btn round color="red" @click="saveOrder">保存</q-btn>
            <q-btn round @click="close">取消</q-btn>
        </q-toolbar>
        <div>
          <q-card style="min-width: 400px;padding: 10px 30%;">
            <q-card-section>
              <div class="q-mt-md">
                <ul class="sort-list" ref="list">
                  <li v-for="(item, index) in apps" :key="item.id" class="sort-item"
                      :class="{ dragging: index === draggingIndex }"
                      draggable="true"
                      @dragstart="onDragStart($event, index)"
                      @dragover.prevent="onDragOver($event, index)"
                      @drop="onDrop($event, index)">
                    <div class="sort-item-inner row no-wrap items-center">
                      <div class="handle q-mr-sm" title="拖动排序">
                        <q-icon name="drag_indicator" />
                      </div>
                      <div class="col sort-title" style="min-width:0">
                        <div class="text-subtitle2 ellipsis">{{ item.title }}</div>
                        <!-- <div class="text-caption text-grey-6">编号: {{ item.num || '-' }}</div> -->
                      </div>
                      <div class="drag-indicator q-ml-sm">
                        <q-icon name="reorder" />
                      </div>
                    </div>
                  </li>
                </ul>
              </div>
            </q-card-section>
          </q-card>
        </div>
    </q-modal-layout>
  </q-modal>
</template>

<script>
import { getAllApps, updateOrder } from '@/service/permission/platformapplications';
export default {
  name: 'SortApplications',
  props: {
    value: { type: Boolean, default: false }
  },
  data() {
    return {
      visible: this.value,
      apps: [],
      draggingIndex: null
    }
  },
  watch: {
    value(v) {
      this.visible = v;
      if (v) this.loadApps();
    },
    visible(v) {
      this.$emit('input', v);
    }
  },
  methods: {
    close() {
      this.visible = false;
    },
    async loadApps() {
      try {
        const res = await getAllApps();
        if (res && res.data) {
          // res.data.data expected list
          this.apps = (res.data.data || []).map(a => ({ ...a }));
          // 初始按 num 字段的数值升序排列，保证显示顺序与 item.num 一致
          this.apps.sort((x, y) => {
            const nx = parseInt(x.num, 10) || 0;
            const ny = parseInt(y.num, 10) || 0;
            return nx - ny;
          });
        }
      } catch (e) {}
    },
    onDragStart(e, index) {
      this.draggingIndex = index;
      e.dataTransfer.effectAllowed = 'move';
    },
    onDragOver(e, index) {
      e.preventDefault();
    },
    onDrop(e, index) {
      e.preventDefault();
      if (this.draggingIndex === null) return;
      const dragged = this.apps.splice(this.draggingIndex, 1)[0];
      this.apps.splice(index, 0, dragged);
      this.draggingIndex = null;
    },
    async saveOrder() {
      // assign num based on order (descending or ascending? we'll set num = index+1)
      const payload = this.apps.map((a, i) => ({ id: a.id, num: String(i + 1) }));
      try {
        await updateOrder(payload);
        this.$q.notify({ type: 'positive', message: '排序已保存' });
        this.$emit('saved');
        this.close();
      } catch (e) {
        this.$q.notify({ type: 'negative', message: '保存失败' });
      }
    }
  }
}
</script>

<style scoped>
.sort-list {
  list-style: none;
  padding: 0;
  margin: 0;
}
.sort-item {
  padding: 8px;
  border: 1px solid #eee;
  border-radius: 6px;
  margin-bottom: 8px;
  background: #fff;
  cursor: grab;
  transition: box-shadow 160ms ease, transform 120ms ease;
  box-shadow: 0 1px 2px rgba(16,24,40,0.04);
  display: flex;
  align-items: center;
  overflow: hidden;
}
.sort-item:hover {
  box-shadow: 0 6px 18px rgba(16,24,40,0.08);
  transform: translateY(-2px);
}
.sort-item.dragging {
  opacity: 0.72;
  transform: scale(0.99);
}
.sort-item-inner { width: 100%; display:flex; align-items:center; justify-content:space-between; }
.handle { width:28px; height:28px; display:flex; align-items:center; justify-content:center; color:#909399; }
.sort-title .ellipsis { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.drag-indicator { color: #c0c4cc; }
</style>


