<template>
  <view class="app-content">
   
    <view class="list-wrap">
      <block v-if="!$util.isEmpty(list.data)">
        <block v-for="(item, index) in list.data" :key="item.id">
          <view
            class="list"
            :class="{
              dragging: draggedIndex === index,
              'target-position': targetIndex === index && isDragging && targetIndex !== draggedIndex
            }"
            :style="{
              transform: transformStyle(index),
              transition: isDragging ? 'none' : 'transform 0.3s ease',
              zIndex: draggedIndex === index ? 999 : targetIndex === index && isDragging ? 888 : 1
            }"
          >
            <view class="list-img">
              <view v-if="item.stock <= 0" class="sold-out">
                <view class="sold-out-xj">已下架</view>
              </view>
              <image :src="item.miniCover" mode="aspectFit"></image>
            </view>
            <view class="list-det" style="position: absolute; top: 10upx; left: 125upx">
              <view class="app-size-28 app-color-0" style="font-size: 28upx; font-weight: bold">{{ item.name || item.goodsName }}</view>
            </view>

            <view class="list-det" style="position: absolute; bottom: 15upx; left: 122upx">
              <view v-if="item.priceType == 1" class="app-size-28 app-color-0" style="font-size:30upx;color:red;font-weight:bold;">¥{{ item.price?parseFloat(item.price):0 }}</view>
              <view v-else></view>
            </view>
            <view
              v-if="index > 0"
              style="right: 375upx; top: 87upx"
              class="move-btn move-btn-top"
              :class="{ disabled: isOperating }"
              @click.stop="topFn(item.id)"
              title="置顶"
            >
              <zui-svg-icon icon="general-top-line" color="#fff" :width="22" :height="22" style="margin-top: 10upx" />
            </view>

            <view
              v-if="index < list.data.length - 1"
              style="right: 290upx; top: 87upx"
              class="move-btn move-btn-bottom"
              :class="{ disabled: isOperating }"
              @click.stop="bottomFn(item.id)"
              title="置底"
            >
              <zui-svg-icon icon="general-bottom-line" color="#fff" :width="22" :height="22" style="margin-top: 10upx" />
            </view>

            <text style="right: 205upx; top: 87upx" class="move-btn move-btn-up" :class="{ disabled: isOperating }" @click.stop="upFn(item.id)" title="上移一位"
              >↑</text
            >
            <text
              style="right: 120upx; top: 87upx"
              class="move-btn move-btn-down"
              :class="{ disabled: isOperating }"
              @click.stop="downFn(item.id)"
              title="下移一位"
              >↓</text
            >

            <view
              class="drag-handle"
              :data-index="index"
              :data-id="item.id"
              @touchstart="dragStart"
              @touchmove="dragMove"
              @touchend="dragEnd"
            >
              <text class="drag-tip">按住</text>
              <text class="drag-tip">拖拽</text>
            </view>
          </view>
        </block>
      </block>
      <block v-else>
        <app-wrapper-empty title="暂无数据" :is-empty="$util.isEmpty(list.data)" />
      </block>
    </view>
  </view>
</template>
<script>
import AppWrapperEmpty from '@/components/app-wrapper-empty';
import { list } from '@/mixins';
import { getListB, sort } from '@/api/goods';
export default {
  name: 'goodsSort',
  components: {
    AppWrapperEmpty
  },
  mixins: [list],
  data() {
    return {
      draggedIndex: -1,
      draggedItem: null,
      dragOffsetY: 0,
      isDragging: false,
      itemHeight: 160, // 列表项高度，单位upx（与CSS中的height保持一致）
      startY: 0,
      scrollTop: 0, // 页面滚动高度
      originalOrder: [], // 原始顺序，用于拖拽失败时恢复
      targetIndex: -1, // 目标交换位置的索引
      isOperating: false, // 防止快速点击操作按钮
      totalNum: 0 // 总数量
    };
  },
  onPageScroll(e) {
    // 拖拽期间禁止更新滚动高度
    if (!this.isDragging) {
      this.scrollTop = e.scrollTop;
    }
  },
  onPullDownRefresh() {
    this.resetList();
    this.getGoodsList()
      .then((res) => {
        uni.stopPullDownRefresh();
      })
      .catch((err) => {
        console.error('下拉刷新失败:', err);
        uni.stopPullDownRefresh();
      });
  },
  onReachBottom() {
    if (!this.list.finished) {
      this.getGoodsList().then((res) => {
        uni.stopPullDownRefresh();
      });
    } else {
      uni.stopPullDownRefresh();
    }
  },
  methods: {
    async init() {
      // 确保list.data是数组
      if (!Array.isArray(this.list.data)) {
        this.list.data = [];
      }
      this.getGoodsList();

      if(this.option.name){
        uni.setNavigationBarTitle({ title: this.option.name+" 排序" })
      }

    },
    getGoodsList() {
      // 传递分类ID参数和分页参数到API
      const params = {
        cId: this.option.id,
        page: this.list.page,
        pageSize: this.list.pageSize
      };

      return getListB(params)
        .then((res) => {
          // 使用mixin提供的completes方法处理分页数据
          this.completes(res);
          this.totalNum = Number(res.data.total);
        })
        .catch((err) => {
          console.error('API请求失败:', err);
          this.list.loading = false;
        });
    },
    // 响应 touchmove 事件并实时更新 transform 样式
    transformStyle(index) {
      if (index === this.draggedIndex) {
        // #ifdef APP-PLUS
        // 在 App 端，为与小程序保持一致，拖拽时项目保持原位
        return 'translateY(0upx)';
        // #endif

        //return `translateY(${this.dragOffsetY}upx)`;
        return 'translateY(0upx)';
      }
      return 'translateY(0upx)';
    },

    dragStart(e) {
      // 防止重复触发
      if (this.isDragging) return;

      this.isDragging = true;

      const index = parseInt(e.currentTarget.dataset.index);
      if (isNaN(index) || index < 0 || index >= this.list.data.length) {
        this.isDragging = false;
        return;
      }

      this.draggedIndex = index;
      this.draggedItem = this.list.data[index];
      this.startY = e.touches[0].clientY;
      this.targetIndex = index; // 初始化目标位置为当前位置

      // 保存原始顺序，用于拖拽失败时恢复
      this.originalOrder = [...this.list.data];

      // 添加拖拽模式样式，防止页面滚动
      this.toggleDragMode(true);

      // 阻止默认行为，防止页面滚动（兼容微信端与H5）
      if (e.preventDefault) {
        e.preventDefault();
      }
      if (e.stopPropagation) {
        e.stopPropagation();
      }
      return false;
    },

    dragMove(e) {
      if (!this.isDragging || this.draggedIndex === -1) return;

      // 验证触摸点是否存在
      if (!e.touches || !e.touches[0]) return;

      // 阻止默认行为，防止页面滚动（兼容微信端与H5）
      if (e.preventDefault) {
        e.preventDefault();
      }
      if (e.stopPropagation) {
        e.stopPropagation();
      }

      const currentY = e.touches[0].clientY;
      const deltaY = currentY - this.startY;

      // 根据设备像素比例转换为upx单位，确保在不同设备上表现一致
      const systemInfo = uni.getSystemInfoSync();
      const pixelRatio = 750 / systemInfo.windowWidth;
      const deltaYupx = deltaY * pixelRatio;

      // 限制拖拽范围，防止超出列表边界
      const maxOffset = (this.list.data.length - 1 - this.draggedIndex) * this.itemHeight;
      const minOffset = -this.draggedIndex * this.itemHeight;
      const limitedOffset = Math.max(minOffset, Math.min(maxOffset, deltaYupx));

      this.dragOffsetY = limitedOffset;

      // 实时计算目标位置，让用户看到将要交换的元素
      const moveItems = Math.round(limitedOffset / this.itemHeight);
      this.targetIndex = Math.max(0, Math.min(this.list.data.length - 1, this.draggedIndex + moveItems));
    },

    dragEnd() {
      if (!this.isDragging) return;

      // 计算最终位置
      const moveItems = Math.round(this.dragOffsetY / this.itemHeight);
      const targetIndex = Math.max(0, Math.min(this.list.data.length - 1, this.draggedIndex + moveItems));

      // 如果位置有变化，则更新数组
      if (targetIndex !== this.draggedIndex) {
        const newData = [...this.list.data];
        const draggedItem = newData[this.draggedIndex];

        // 移除拖拽项
        newData.splice(this.draggedIndex, 1);
        // 插入到新位置
        newData.splice(targetIndex, 0, draggedItem);

        this.list.data = newData;

        // 更新排序值并发送到后端
        this.updateSortOrder();
      }

      // 移除拖拽模式样式
      this.toggleDragMode(false);

      // 重置拖拽状态
      this.draggedIndex = -1;
      this.draggedItem = null;
      this.dragOffsetY = 0;
      this.isDragging = false;
      this.startY = 0;
      this.originalOrder = [];
      this.targetIndex = -1; // 重置目标位置
    },

    updateSortOrder() {
      // 更新每个项目的inTurn值，从大到小排序（值越大越靠前）
      const sortData = this.list.data.map((item, index) => ({
        id: item.id,
        inTurn: this.totalNum - index // 反向索引，使第一个项目有最大值
      }));
      // console.log('排序数据:', sortData)

      // 调用API更新排序
      sort({ cId: this.option.id, items: sortData })
        .then((res) => {
          if (res.code === 1) {

          } else {
            this.$msg('排序更新失败');
            // 恢复原始顺序
            this.list.data = this.originalOrder;
          }
        })
        .catch((err) => {
          console.error('更新排序失败:', err);
          this.$msg('排序更新失败');
          // 恢复原始顺序
          this.list.data = this.originalOrder;
        });
    },

    // 切换拖拽模式，防止页面滚动
    toggleDragMode(isDragging) {
      // #ifdef H5
      // H5平台：直接操作body样式
      if (isDragging) {
        document.body.classList.add('dragging-mode');
      } else {
        document.body.classList.remove('dragging-mode');
      }
      // #endif

      // #ifdef MP-WEIXIN
      // 微信小程序：使用页面样式和滚动API
      if (typeof uni.setPageStyle !== 'function') {
        console.warn('uni.setPageStyle is not available on this platform.');
        return;
      }
      
      if (isDragging) {
        uni.setPageStyle({
          style: {
            overflow: 'hidden',
            position: 'fixed',
            width: '100%',
            top: `-${this.scrollTop}px`,
            left: '0',
            right: '0'
          }
        });
      } else {
        uni.setPageStyle({
          style: {
            overflow: '',
            position: '',
            width: '',
            top: '',
            left: '',
            right: ''
          }
        });
        uni.pageScrollTo({
          scrollTop: this.scrollTop,
          duration: 0
        });
      }
      // #endif

      // #ifdef APP-PLUS
      const systemInfo = uni.getSystemInfoSync();
      
        // --- iOS 与 Android App 平台替代方案 ---
        // 通过操作 webview 内的 body 样式来禁止滚动
        const webview = this.$scope.$getAppWebview();
        if (!webview) {
          console.warn('uni.setPageStyle 在当前环境不可用，且无法获取 webview。');
          return;
        }

        if (isDragging) {
          webview.evalJS(`
            var body = document.body;
            body.style.overflow = 'hidden';
            body.style.position = 'fixed';
            body.style.width = '100%';
            body.style.left = '0';
            body.style.right = '0';
            body.style.top = '-${this.scrollTop}px';
          `);
        } else {
          webview.evalJS(`
            var body = document.body;
            body.style.overflow = '';
            body.style.position = '';
            body.style.width = '';
            body.style.left = '';
            body.style.right = '';
            body.style.top = '';
          `);
          // 恢复滚动位置
          uni.pageScrollTo({
            scrollTop: this.scrollTop,
            duration: 0
          });
        }
        return; // iOS 平台处理完毕
      // #endif
    },

    // 原有的上移下移方法
    upFn(id) {
      if (this.isOperating) return;
      this.isOperating = true;
      const index = this.list.data.findIndex((item) => item.id === id);
      if (index > 0) {
        const newData = [...this.list.data];
        const temp = newData[index];
        newData[index] = newData[index - 1];
        newData[index - 1] = temp;
        this.list.data = newData;
        this.updateSortOrder();
      }

      // 防抖延迟
      setTimeout(() => {
        this.isOperating = false;
      }, 300);
    },

    downFn(id) {
      if (this.isOperating) return;
      this.isOperating = true;
      const index = this.list.data.findIndex((item) => item.id === id);
      if (index < this.list.data.length - 1) {
        const newData = [...this.list.data];
        const temp = newData[index];
        newData[index] = newData[index + 1];
        newData[index + 1] = temp;
        this.list.data = newData;
        this.updateSortOrder();
      }

      // 防抖延迟
      setTimeout(() => {
        this.isOperating = false;
      }, 300);
    },

    // 置顶
    topFn(id) {
      if (this.isOperating) return;
      this.isOperating = true;
      const index = this.list.data.findIndex((item) => item.id === id);
      if (index > 0) {
        const newData = [...this.list.data];
        const targetItem = newData[index];

        // 将目标项移到第一位
        newData.splice(index, 1);
        newData.unshift(targetItem);

        this.list.data = newData;
        this.updateSortOrder();
      }

      // 防抖延迟
      setTimeout(() => {
        this.isOperating = false;
      }, 300);
    },

    // 置底
    bottomFn(id) {
      if (this.isOperating) return;
      this.isOperating = true;
      const index = this.list.data.findIndex((item) => item.id === id);
      if (index < this.list.data.length - 1) {
        const newData = [...this.list.data];
        const targetItem = newData[index];

        // 将目标项移到最后一位
        newData.splice(index, 1);
        newData.push(targetItem);

        this.list.data = newData;
        this.updateSortOrder();
      }

      // 防抖延迟
      setTimeout(() => {
        this.isOperating = false;
      }, 300);
    }
  }
};
</script>
<style lang="scss" scoped>
.app-content {
  min-height: calc(100vh - 100upx);
  padding-bottom: 100upx;
}
/* 现代化标签样式 */
.modern-tabs-container {
  padding: 0;
  background-color: #f8f9fa;
  width: 100%;
}

.modern-tabs {
  display: flex;
  background-color: #ffffff;
  padding: 6upx;
  box-shadow: 0 2upx 12upx rgba(0, 0, 0, 0.06);
  border: 2upx solid #f0f2f5;
  position: relative;
  z-index: 5;
  width: 100%;
}

.modern-tab {
  flex: 1;
  text-align: center;
  padding: 14upx 0;
  position: relative;
  transition: all 0.35s cubic-bezier(0.25, 1, 0.5, 1);
  border-radius: 12upx;
  margin: 0 2upx;
  background-color: #fafafa;
  border: 2upx solid #f2f4f7;
  box-shadow: none;
  .tab-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
  .tab-icon {
    font-size: 32upx;
    margin-bottom: 4upx;
    display: block;
    opacity: 0.8;
  }
  &.active .tab-icon {
    filter: brightness(1.15);
    opacity: 1;
  }
  .tab-text {
    font-size: 26upx;
    color: #666;
    font-weight: 600;
  }
  &.active {
    background: linear-gradient(135deg, #10b981 0%, #09C567 100%);
    box-shadow: 0 4upx 12upx rgba(16, 185, 129, 0.25);
    transform: none;
    border-color: rgba(16, 185, 129, 0.25);
    .tab-text {
      color: #ffffff;
      font-weight: 700;
      font-size: 28upx;
    }
  }
  /* 未选中态悬停（H5 生效，其它端无影响） */
  &:not(.active):hover {
    background-color: #f6f7f9;
    border-color: #e9ecef;
  }
  &:active {
    transform: scale(0.98);
  }
}
.list-wrap {
  position: relative;
  background-color: #fff;
  .list {
    height: 160upx;
    @include disFlex(center, flex-start);
    padding: 30upx 0;
    margin: 0 30upx;
    color: $fontColor3;
    border-bottom: 1px solid $borderColor;
    position: relative;
    .list-img {
      width: 130upx;
      height: 130upx;
      image {
        width: 130upx;
        height: 130upx;
        border-radius: 20upx;
      }

      .sold-out {
        z-index: 10;
        width: 130upx;
        height: 52upx; /* 130 * (2/5) = 52upx */
        background-color: black;
        position: absolute;
        top: 92upx;
        left: 0;
        opacity: 0.48;
        color: white;
        text-align: center;
        border-radius: 0 0 20upx 20upx;
        .sold-out-xj {
          line-height: 52upx;
          font-size: 24upx;
          font-weight: bold;
        }
      }
    }
    .list-det {
      margin-left: 20upx;
      & > div {
        margin-top: 14upx;
        &:first-child {
          margin-top: 0;
        }
      }
    }
  }
}
.move-btn {
  position: absolute;
  top: 88upx;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 60upx;
  height: 60upx;
  color: #fff;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  font-size: 28upx; /* 增大20% */
  font-weight: bold;
  box-shadow: 0 4upx 12upx rgba(102, 126, 234, 0.3);
  transition: all 0.2s ease;
  z-index: 9999;
  cursor: pointer;

  /* 触摸反馈 */
  &:active {
    transform: scale(0.95);
    box-shadow: 0 2upx 8upx rgba(102, 126, 234, 0.5);
  }

  /* 悬停效果 */
  &:hover {
    transform: translateY(-2upx);
    box-shadow: 0 6upx 20upx rgba(102, 126, 234, 0.4);
  }
}

/* 置顶按钮 - 红色渐变 */
.move-btn-top {
  // background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
  // box-shadow: 0 4upx 12upx rgba(255, 107, 107, 0.3);
  background: linear-gradient(135deg, #feca57 0%, #ff9ff3 100%);
  box-shadow: 0 4upx 12upx rgba(254, 202, 87, 0.3);

  &:hover {
    box-shadow: 0 6upx 20upx rgba(255, 107, 107, 0.4);
  }

  &:active {
    box-shadow: 0 2upx 8upx rgba(255, 107, 107, 0.5);
  }
}

/* 置底按钮 - 橙色渐变 */
.move-btn-bottom {
  background: linear-gradient(135deg, #feca57 0%, #ff9ff3 100%);
  box-shadow: 0 4upx 12upx rgba(254, 202, 87, 0.3);

  &:hover {
    box-shadow: 0 6upx 20upx rgba(254, 202, 87, 0.4);
  }

  &:active {
    box-shadow: 0 2upx 8upx rgba(254, 202, 87, 0.5);
  }
}

/* 上移按钮 - 绿色渐变 */
.move-btn-up {
  background: linear-gradient(135deg, #48dbfb 0%, #0abde3 100%);
  box-shadow: 0 4upx 12upx rgba(72, 219, 251, 0.3);

  &:hover {
    box-shadow: 0 6upx 20upx rgba(72, 219, 251, 0.4);
  }

  &:active {
    box-shadow: 0 2upx 8upx rgba(72, 219, 251, 0.5);
  }
}

/* 下移按钮 - 紫色渐变 */
.move-btn-down {
  // background: linear-gradient(135deg, #a55eea 0%, #8854d0 100%);
  // box-shadow: 0 4upx 12upx rgba(165, 94, 234, 0.3);
  background: linear-gradient(135deg, #48dbfb 0%, #0abde3 100%);
  box-shadow: 0 4upx 12upx rgba(72, 219, 251, 0.3);

  &:hover {
    box-shadow: 0 6upx 20upx rgba(165, 94, 234, 0.4);
  }

  &:active {
    box-shadow: 0 2upx 8upx rgba(165, 94, 234, 0.5);
  }
}

/* 按钮禁用状态 */
.move-btn.disabled {
  opacity: 0.5;
  transform: none !important;
  box-shadow: 0 2upx 6upx rgba(0, 0, 0, 0.1) !important;
  pointer-events: none;
  cursor: not-allowed;
  &:hover,
  &:active {
    transform: none !important;
    box-shadow: 0 2upx 6upx rgba(0, 0, 0, 0.1) !important;
  }
}
// 拖拽相关样式
.list.dragging {
  border: 2px dashed #007aff !important;
  box-shadow: 0 8upx 40upx rgba(0, 122, 255, 0.25) !important;
  background-color: rgba(0, 122, 255, 0.08) !important;
  opacity: 0.9;
  border-radius: 16upx;
  transform: scale(1.02);
  transition: none !important; /* 拖拽时禁用过渡动画 */
}

.list.target-position {
  border: 3px solid #52c41a !important; /* 使用绿色边框区别于拖拽元素 */
  box-shadow: 0 6upx 30upx rgba(82, 196, 26, 0.3) !important;
  background-color: rgba(82, 196, 26, 0.1) !important;
  opacity: 0.95;
  border-radius: 16upx;
  transform: scale(1.01);
  transition: all 0.2s ease !important; /* 目标位置保持平滑过渡 */

  /* 添加一个内部指示器 */
  &::before {
    content: '移动到这儿';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    padding: 8upx 22upx;
    background: linear-gradient(90deg, #52c41a, #73d13d);
    border-radius: 8upx;
    color: #fff;
    font-size: 26upx;
    font-weight: bold;
    opacity: 0.9;
    z-index: 99990;
  }
}

.drag-handle {
  position: absolute;
  top: 75upx;
  right: 12upx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 76upx;
  height: 76upx;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 4upx 16upx rgba(102, 126, 234, 0.4);
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  user-select: none;
  touch-action: none;
  border: 2px solid rgba(255, 255, 255, 0.3);
  transition: all 0.2s ease;
  cursor: grab;

  &:active {
    transform: scale(0.92);
    cursor: grabbing;
    box-shadow: 0 2upx 10upx rgba(102, 126, 234, 0.5);
  }

  &:hover {
    transform: translateY(-3upx);
    box-shadow: 0 6upx 20upx rgba(102, 126, 234, 0.45);
  }

  .drag-tip {
    font-size: 19upx;
    color: rgba(255, 255, 255, 0.95);
    font-weight: 700;
    letter-spacing: 0.5upx;
    line-height: 1.4;
    text-align: center;
    word-break: break-word;
    display: block;
  }
}

/* 防止拖拽时页面滚动 */
.dragging-mode {
  overflow: hidden !important;
  touch-action: none !important;
  -webkit-overflow-scrolling: auto !important;
}
</style>
