<script lang="ts" setup>
import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { Icon } from '#/components/icon';

import { message } from 'ant-design-vue';

import { getSpecialPrescriptionCategoryList, updateSpecialPrescriptionCategorySortOrder } from '../api';

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    const ids = sortableList.value.map((item) => item.id);
    if (!ids.length) {
      message.warning('没有可排序的数据');
      return;
    }
    modalApi.setState({ loading: true, confirmLoading: true });
    updateSpecialPrescriptionCategorySortOrder({ ids })
      .then(() => {
        message.success('排序更新成功');
        const gridApi = modalApi.getData()?.gridApi;
        if (gridApi) {
          gridApi.query();
        }
        modalApi.close();
      })
      .catch(() => {
        message.error('排序更新失败');
      })
      .finally(() => {
        modalApi.setState({ loading: false, confirmLoading: false });
      });
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      loadList();
    } else {
      sortableList.value = [];
    }
  },
});

const sortableList = ref<any[]>([]);
const draggedIndex = ref(-1);
const dragOverIndex = ref(-1);

const loadList = async () => {
  try {
    const res = await getSpecialPrescriptionCategoryList({
      page: 1,
      pageSize: 1000,
    });
    const data = Array.isArray(res?.items) ? res.items : [];
    if (!data.length) {
      message.warning('暂无数据可排序');
    }
    sortableList.value = [...data].sort((a, b) => (a.sort || 0) - (b.sort || 0));
  } catch (error) {
    console.error('加载分类失败:', error);
    message.error('加载数据失败');
  }
};

const onDragStart = (event: DragEvent, index: number) => {
  draggedIndex.value = index;
  dragOverIndex.value = -1;
  if (event.dataTransfer) {
    event.dataTransfer.effectAllowed = 'move';
  }
};

const onDragEnter = (index: number) => {
  if (draggedIndex.value !== -1 && draggedIndex.value !== index) {
    dragOverIndex.value = index;
  }
};

const onDragOver = (event: DragEvent) => {
  event.preventDefault();
  if (event.dataTransfer) {
    event.dataTransfer.dropEffect = 'move';
  }
};

const onDrop = (event: DragEvent, targetIndex: number) => {
  event.preventDefault();
  if (draggedIndex.value === -1 || draggedIndex.value === targetIndex) {
    draggedIndex.value = -1;
    dragOverIndex.value = -1;
    return;
  }
  const list = [...sortableList.value];
  const itemToMove = list[draggedIndex.value];
  list.splice(draggedIndex.value, 1);
  let finalIndex = targetIndex;
  if (draggedIndex.value < targetIndex) {
    finalIndex = targetIndex - 1;
  }
  list.splice(finalIndex, 0, itemToMove);
  sortableList.value = list;
  draggedIndex.value = -1;
  dragOverIndex.value = -1;
};

const onDragEnd = () => {
  draggedIndex.value = -1;
  dragOverIndex.value = -1;
};
</script>

<template>
  <Modal title="分类拖拽排序" class="w-[600px]">
    <div class="py-5">
      <div class="mb-5 rounded-md border-l-4 border-blue-500 bg-blue-50 px-4 py-3">
        <p class="m-0 text-sm text-gray-600">提示：拖拽列表项可调整分类排序，排在前面的分类在小程序中优先展示</p>
      </div>
      <div class="max-h-[500px] overflow-y-auto">
        <template v-for="(item, index) in sortableList" :key="item.id">
          <div
            v-if="dragOverIndex === index && draggedIndex !== -1 && draggedIndex !== index"
            class="mb-3 rounded-lg border-2 border-dashed border-blue-500 bg-blue-50/50"
            @dragenter="onDragEnter(index)"
            @dragover="onDragOver"
            @drop="onDrop($event, index)"
          >
            <div class="pointer-events-none flex items-center gap-4 p-4 opacity-60">
              <Icon icon="ant-design:menu-outlined" class="text-xl text-blue-500" />
              <div class="flex-1">{{ sortableList[draggedIndex]?.name }}</div>
              <div class="text-sm text-blue-600">释放以插入此处</div>
            </div>
          </div>

          <div
            class="mb-3 flex cursor-move items-center gap-4 rounded-lg border border-gray-200 bg-white p-4 shadow-sm transition-all hover:border-blue-400"
            draggable="true"
            @dragstart="onDragStart($event, index)"
            @dragenter="onDragEnter(index)"
            @dragover="onDragOver"
            @drop="onDrop($event, index)"
            @dragend="onDragEnd"
          >
            <Icon icon="ant-design:menu-outlined" class="text-xl text-gray-400" />
            <div class="flex-1 font-medium">{{ item.name }}</div>
            <div class="rounded-full bg-gray-100 px-3 py-1 text-sm text-gray-600">{{ index + 1 }}</div>
          </div>
        </template>
      </div>
    </div>
  </Modal>
</template>
