if (window.$ === undefined) {
  // 如果$未定义或不可用，将jQuery赋值给$
  window.$ = jQuery;
}
// 本帖子的ID
var ID = luntan_single_Script_ID.ID;
console.log(ID);
// 随机字符串
console.log("当前 Nonce 是：", luntan_nonce);
// 简化请求
const request = (data = {}, options = {}) => {
  return new Promise((resolve, reject) => {
    const { loading = true, success, error } = options;
    $.ajax({
      url: luntan_ajax,
      type: 'POST',
      data: data,
      dataType: 'json',
      success: (response) => {
        // if (loading) $('.uploading').hide();
        typeof success === 'function' && success(response);
        resolve(response);
      },
      error: (xhr) => {
        // if (loading) $('.uploading').hide();
        console.error('请求失败:', xhr);
        typeof error === 'function' && error(xhr);
        reject(xhr);
      }
    });
  });
};
// 节流函数
const throttle = (func, wait, immediate = true) => {
  let timeout = null;
  return function (...args) {
    const context = this;
    const later = () => {
      timeout = null;
      if (!immediate) func.apply(context, args);
    };
    const callNow = immediate && !timeout;

    clearTimeout(timeout);
    timeout = setTimeout(later, wait);

    if (callNow) func.apply(context, args);
  };
};
// 手写message消息提示
(function ($) {
  $.fn.message = function (options) {
    // 默认设置
    var settings = $.extend({
      messageText: '这是一个消息提示',
      duration: 3000, // 消息显示的时间长度，单位为毫秒
      type: 'info', // 类型可以是 info, success, warning, error 等
      appendToSelector: 'body' // 消息要追加到哪个选择器
    }, options);

    return this.each(function () {
      var $this = $(this);

      // 创建消息元素
      var $messageBox = $('<div>', {
        class: 'message-box ' + settings.type,
        text: settings.messageText
      }).appendTo($(settings.appendToSelector));

      // 显示消息
      $messageBox.slideToggle("fast");

      // 设置自动隐藏
      setTimeout(function () {
        $messageBox.fadeOut('slow', function () {
          $(this).remove(); // 动画结束后移除元素
        });
      }, settings.duration);
    });
  };
})(jQuery);

// 手写messageBox消息弹框
function customMessageBox(options) {

  // 默认参数
  var settings = $.extend({
    title: '提示',
    message: '',
    cancelButtonText: '取消',
    confirmButtonText: '确定',
    closeOnClickOverlay: true // 新增遮罩层关闭配置
  }, options);

  // 创建弹框HTML结构
  var $overlay = $('<div class="custom-overlay"></div>');
  var $box = $('<div class="custom-message-box"></div>');
  var $title = $('<div class="message-box-title">' + settings.title + '</div>');
  var $message = $('<div class="message-box-content">' + settings.message + '</div>');
  var $buttonBar = $('<div class="message-box-button-bar"></div>');
  var $cancelButton = $('<button class="message-box-cancel-button">' + settings.cancelButtonText + '</button>');
  var $confirmButton = $('<button class="message-box-confirm-button">' + settings.confirmButtonText + '</button>');

  // 组装弹框
  $buttonBar.append($cancelButton).append($confirmButton);
  $box.append($title).append($message).append($buttonBar);
  $overlay.append($box)
  $('body').append($overlay);

  // 禁用页面滚动
  $('body').css('overflow', 'hidden');

  // 事件委托处理
  var result;
  var $document = $(document);

  // 点击遮罩层关闭（可配置）
  if (settings.closeOnClickOverlay) {
    $overlay.on('click', function (e) {
      e.preventDefault();
      e.stopPropagation();
      close();
    });
  }

  // 阻止弹窗内点击冒泡
  $box.on('click', function (e) {
    e.stopPropagation();
  });

  // 按钮点击事件
  $cancelButton.click(function (e) {
    e.preventDefault();
    result = false;
    close();
  });

  $confirmButton.click(function (e) {
    e.preventDefault();
    result = true;
    close();
  });

  // 关闭函数
  function close() {
    $overlay.remove();
    $box.fadeOut(function () {
      $box.remove();
      $('body').css('overflow', ''); // 恢复滚动
    });
  }

  // 返回Promise
  return new Promise((resolve) => {
    $confirmButton.one('click', function () { resolve(true); });
    $cancelButton.one('click', function () { resolve(false); });
  });

}

// 获取帖子的具体信息
const articleDetail = await request({
  action: "luntan_post_detail",
  nonce: luntan_nonce,
  id: ID
})
console.log(articleDetail);

// 获取用户的具体信息
const userDetail = await request({
  action: 'luntan_get_user',
  nonce: luntan_nonce
})
console.log(userDetail);

//登录处理
async function loginVerification() {
  const userDetail = await request({
    action: 'luntan_get_user',
    nonce: luntan_nonce
  })

  if (userDetail.code != 1) {
    //调用消息提示
    $(document).message({
      messageText: '请先登录',
      duration: 3000,
      type: 'info'
    });

  }
}

//获取当前时间（格式：2025-08-02 12:26:42）
function getFormattedDate() {
  const date = new Date();

  const year = date.getFullYear();
  // 在月份、日期、小时、分钟和秒前面补零
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  // 返回格式化后的日期字符串
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 页面禁止滚动
function disableScroll() {
  $('body').css('overflow', 'hidden');
}

// 页面恢复滚动
function enableScroll() {
  $('body').css('overflow', '');
}

// DOM加载完成后
$(document).ready(async function () {

  //更新页面的点赞和点踩情况、板块选中情况、置顶精华情况
  $(document).ready(function () {

    // 一、遍历所有点赞按钮
    $(".pinglunlist").find(".dianzan, .zan").each(function () {
      const $this = $(this);
      const commentId = $this.data("id"); // 获取评论ID

      // 根据 localStorage 判断状态
      if (localStorage.getItem(`comment_like_${commentId}`)) {
        $this.addClass("active"); // 存在则激活
      } else {
        $this.removeClass("active"); // 不存在则移除
      }
    });

    // 二、遍历所有的点踩按钮
    $(".pinglunlist").find(".cai").each(function () {
      const $this = $(this);
      const commentId = $this.data("id");
      if (localStorage.getItem(`comment_dislike_${commentId}`)) {
        $this.addClass("active");
      } else {
        $this.removeClass("active");
      }
    });

    // 三、右侧板块选中当前的分类
    $('.fbr_other').find('a').each(function () {
      if ($(this).data('id') == localStorage.getItem('INDEX_LUNTAN')) {
        $(this).find('.ot_item').addClass('ot_item_act')
      }
    })

    // 四、管理帖子中的置顶/取消、精华/取消
    // 1、检测有没有当前置顶和精华
    const isSticky = $('.tzct_right .tag .zhiding').length
    const isJing = $('.tzct_right .tag .jing').length
    // 2、管理帖子中根据有无去除选项
    if (isSticky) {
      $('.menu-detail .top').css('display', 'none')
    } else {
      $('.menu-detail .untop').css('display', 'none')
    }
    if (isJing) {
      $('.menu-detail .hot').css('display', 'none')
    } else {
      $('.menu-detail .unhot').css('display', 'none')
    }
  });

  //------------------------------------------------------编辑帖子
  // 关闭编辑帖子按钮
  $('.fbDialogBox .close-btn, .btn-cancel').click(function () {
    $(".fbDialogBox").slideUp("fast");
    $('.fbDialogBox').css({
      'opacity': '0',
      'z-index': '-1'
    });
    $('#fbOverlay').fadeOut(200);
  })
  // 上传图片请求专用数组
  let imgAll = []

  // 装填图片
  const imagePathStr = articleDetail.data.detail.thumb
  // 拆分并处理路径
  imgAll = imagePathStr.split(',').map(path => path.trim()).filter(path => path !== '');
  // 点击添加图片按钮触发文件选择
  $('.fbDialogBox .addImg-btn').click(function () {

    if (imgAll.length >= 5) {
      alert('图片最多上传5张')
      return
    }
    // 创建隐藏的文件输入框
    const fileInput = $('<input type="file" accept="image/*" multiple style="display: none;">');
    $('body').append(fileInput);

    // 触发文件选择
    fileInput.click();

    // 监听文件选择事件
    fileInput.on('change', function (e) {
      const files = e.target.files;
      if (files.length > 0) {
        uploadImages(files);
      }
      // 移除临时文件输入框
      fileInput.remove();
    });
  });
  // 移除图片功能
  $(document).on('click', '.fbDialogBox .remove-img', function (e) {
    const $uploadedImg = $(this).closest('.uploaded-img');
    const index = $('.fbDialogBox .uploaded-img').index($uploadedImg);
    $uploadedImg.remove();
    imgAll.splice(index, 1);
  });
  // 图片上传函数
  function uploadImages(files) {
    // 计算还能上传多少张图片
    const remaining = 5 - imgAll.length;

    // 如果已经达到上限，直接提示
    if (remaining <= 0) {
      alert('图片最多上传5张');
      return;
    }

    // 如果选中的图片数量超过剩余可上传数量，提示并截断
    if (files.length > remaining) {
      alert(`最多还能上传${remaining}张图片`);
      // 只取前remaining个文件
      files = Array.from(files).slice(0, remaining);
    }
    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      if (!file.type.match('image.*')) {
        alert('请选择图片文件');
        continue;
      }

      // 创建FormData并添加所有字段
      const formData = new FormData();
      formData.append('nonce', luntan_nonce); // 添加 nonce 验证
      formData.append('action', 'luntan_post_img'); // 添加 nonce 验证
      formData.append('file', file, file.name); // 添加文件，包含文件名

      console.log(file);
      // 发送上传请求
      $.ajax({
        url: luntan_ajax,
        type: 'POST',
        data: formData,
        contentType: false,
        processData: false,
        dataType: 'json',
        success: function (response) {
          console.log(response);
          if (response.code == 1 && response.data) {
            imgAll.push(response.data)
            // 上传成功，显示图片
            const imgHtml = `
                <div class="uploaded-img">
                  <img src="${response.data}" alt="图片">
                  <div class="remove-img">×</div>
                </div>
              `;
            $('.fbDialogBox .imgBox').prepend(imgHtml);
          } else {
            alert('上传失败: ' + (response.msg || '未知错误'));
          }
        },
        error: function (xhr) {
          alert('网络错误，上传失败');
          console.error('AJAX错误:', xhr);
        },
        complete: function () {
          $('.uploading').remove();
        }
      });
    }
  }
  // 板块分类
  let flId = ''
  $(document).on('click', '.fbDialogBox .typeTab_item', function () {
    $('.typeTab_item').removeClass('typeTab_item_act');
    $(this).addClass('typeTab_item_act');
    flId = $(this).data('id');
  });
  let btnPrimary = 0;
  // 修改帖子 点击确认的按钮
  $('.fbDialogBox .dialog-footer .btn-primary').click(function () {
    // 只能点击一次，等待接口完成后，再能继续点击。
    if (btnPrimary != 0) { return }
    let formData = {
      action: 'luntan_post_edit',
      title: $('.dialog-body .title_input').val().trim(),
      content: $('.dialog-body .content_input').val().trim(),
      img: imgAll.join(','),
      id: ID,
      cate_id: flId + '',
      nonce: luntan_nonce // 添加 nonce 验证
    }
    // 请输入标题
    if (formData.title.length < 0) {
      alert('请输入标题内容')
      return
    }
    // 请输入正文
    if (formData.content.length < 0) {
      alert('请输入内容')
      return
    }
    // 请选择 板块分类
    if (formData.cate == '') {
      alert('请选择板块分类')
      return
    }
    ++btnPrimary;

    // 发送上传请求
    $.ajax({
      url: luntan_ajax,
      type: 'POST',
      data: formData,
      dataType: 'json',
      success: function (response) {
        if (response.code == 1) {
          alert('发布成功,等待管理员审核');
          // 关闭编辑
          $(".fbDialogBox").slideUp("fast");
          location.reload();
        } else {
          alert(response.msg);
        }
        btnPrimary = 0;
      },
      error: function (xhr) {
        console.error('AJAX错误:', xhr);
        btnPrimary = 0;
      },
      complete: function () {
        $('.uploading').remove();
      }
    });
  })


  // 2025.12.06 转换<br>为换行符 + 去除左右空格 + 赋值
  const content = $('.tzc_con .content').html()
    .replace(/<br\s*\/?>/gi, '\n') // 替换<br>为换行符
    .trim(); // 去除文本左右空格

  // 批量赋值到目标元素
  $('#pc_fbContent, #mo_fbContent').html(content);



  //-------------------------------------------帖子管理，下拉菜单的逻辑
  // 点击管理按钮切换菜单显示
  $(".dropdown").click(function (e) {
    e.stopPropagation(); // 阻止事件冒泡
    $(".menu-detail").slideToggle("fast"); // 使用滑动动画
  });
  // 点击页面其他区域时收起菜单
  $(document).click(function (e) {
    if (!$(e.target).closest(".dropdown").length) {
      $(".menu-detail").css("display", "none");
    }
  });
  // 点击菜单项时执行对应操作
  $(".menu-detail div").click(async function () {
    const action = $(this).attr("class");
    const $tag = $(".tzct_right .tag")

    switch (action) {
      case 'edit': //1、编辑
        // 1.1 控制弹窗的显示和隐藏
        // $(".fbDialogBox").slideToggle("fast"); // 使用滑动动画
        $('.fbDialogBox').css({
          'opacity': '1',
          'z-index': '9999',
          'display': 'block'
        });
        // 如果遮罩层不存在，则创建
        if ($('#fbOverlay').length === 0) {
          $('body').append('<div id="fbOverlay"></div>');
          $('#fbOverlay').css({
            'position': 'fixed',
            'top': 0,
            'left': 0,
            'width': '100%',
            'height': '100%',
            'background': 'rgba(0,0,0,0.5)',
            'z-index': '9998', // 遮罩层层级比弹窗低
            'display': 'none'
          });
        }

        // 显示遮罩层和弹窗
        $('#fbOverlay').fadeIn(200);
        // 点击遮罩层关闭弹窗
        $('#fbOverlay').click(function () {
          $('.fbDialogBox').css({
            'opacity': '0',
            'z-index': '-1'
          });
          $('#fbOverlay').fadeOut(200);
        });
        // 1.2 点亮板块分类
        $(".fbDialogBox .typeTab").find(".typeTab_item").each(function () {
          const $this = $(this);
          const cateId = $this.data("id"); // 获取分类ID
          if (articleDetail.data.detail.cate == cateId) {
            $this.addClass("typeTab_item_act"); // ID相同则激活点亮
          }
        });
        break;
      case 'top': // 2、置顶
        // 2.1添加置顶元素
        if ($('.tag .zhiding').length === 0) {
          $tag.prepend('<div class="zhiding">置顶</div>');
        }
        // 2.3显示和隐藏帖子管理项
        $('.menu-detail .top').css('display', 'none')
        $('.menu-detail .untop').css('display', 'flex')

        // 2.3发请求
        const topRes = await request({
          action: "luntan_post_top",
          nonce: luntan_nonce,
          type: '1',
          id: ID
        })
        // 2.4消息提示
        if (topRes.code == 1) {
          $(this).message({
            messageText: '已置顶',
            duration: 3000,
            type: 'success'
          });
        }
        break;
      case 'untop': //3、取消置顶
        // 3.1删除置顶标签
        if ($('.tag .zhiding').length) {
          $('.tag .zhiding').remove();
        }
        // 3.2显示隐藏管理项
        $('.menu-detail .untop').css('display', 'none')
        $('.menu-detail .top').css('display', 'flex')
        // 3.3发请求
        const untopRes = await request({
          action: "luntan_post_top",
          nonce: luntan_nonce,
          type: '2',
          id: ID
        })
        // 3.4消息提示
        $(this).message({
          messageText: '已取消置顶',
          duration: 3000,
          type: 'info'
        });
        break;
      case 'hot': //4、精华
        // 4.1添加精华标签
        if ($('.tag .jing').length === 0) {
          $tag.append('<div class="jing">精</div>');
        }
        // 4.2显示隐藏管理项
        $('.menu-detail .hot').css('display', 'none')
        $('.menu-detail .unhot').css('display', 'flex')
        // 4.3发请求
        const hotRes = await request({
          action: "luntan_post_top",
          nonce: luntan_nonce,
          type: '3',
          id: ID
        })
        // 4.4消息提示
        if (hotRes.code == 1) {
          $(this).message({
            messageText: '已设置精华',
            duration: 3000,
            type: 'success'
          });
        }
        break;
      case 'unhot': //5、取消精华
        // 5.1删除精华标签
        if ($('.tag .jing').length) {
          $('.tag .jing').remove();
          console.log('删除');
        }
        // 5.2显示隐藏管理项
        $('.menu-detail .unhot').css('display', 'none')
        $('.menu-detail .hot').css('display', 'flex')
        // 5.3发请求
        const unhotRes = await request({
          action: "luntan_post_top",
          nonce: luntan_nonce,
          type: '4',
          id: ID
        })
        // 5.4消息提示
        if (unhotRes.code == 1) {
          $(this).message({
            messageText: '已取消精华',
            duration: 3000,
            type: 'info'
          });
        }
        break;
      case 'cancel': //6、删除
        // 6.1弹窗确认
        const messageRes = await customMessageBox({
          title: '确认删除',
          message: '您确定永久删除此帖子吗？',
          cancelButtonText: '取消',
          confirmButtonText: '确认'
        })
        // 6.2发请求
        if (messageRes) {
          const cancelRes = await request({
            action: "luntan_delete_post",
            nonce: luntan_nonce,
            id: ID
          })
          // 6.3消息提示
          $(this).message({
            messageText: '已删除文章',
            duration: 3000,
            type: 'info'
          });
          // 6.4定时器跳转 - 跳转到上一级URL路径
          setTimeout(function () {
            // 获取当前路径
            const currentPath = window.location.pathname;

            // 处理路径，移除结尾的斜杠（如果有）
            const normalizedPath = currentPath.endsWith('/')
              ? currentPath.slice(0, -1)
              : currentPath;

            // 分割路径为数组（过滤空字符串）
            const pathSegments = normalizedPath.split('/').filter(segment => segment);

            // 如果有上级路径，则移除最后一个片段；否则保持根路径
            if (pathSegments.length > 0) {
              pathSegments.pop();
            }

            // 组合成上级路径
            const parentPath = '/' + pathSegments.join('/') + (pathSegments.length > 0 ? '/' : '');

            // 跳转到上级路径
            window.location.href = parentPath;
          }, 1000);
        }
        break;
      default: break;
    }
  });




  //----------------------------------------------------点赞、点踩功能

  // 应用节流点赞
  $(".pinglunlist").on("click", ".dianzan,.zan", throttle(async function () {
    const $this = $(this)
    const commentId = $(this).data("id");
    const $span = $(this).find("span"); // 获取点赞数显示的<span>
    let currentLikes = parseInt($span.text()); // 当前点赞数（从HTML获取）

    // 对于是否点赞，用本地存储解决
    if (localStorage.getItem(`comment_like_${commentId}`)) {
      // 这是取消点赞逻辑
      $this.removeClass("active");
      localStorage.removeItem(`comment_like_${commentId}`);
      //点赞数减1
      $span.text(--currentLikes);
      //发请求取消赞
      const res = await request({
        action: 'luntan_comment_like',
        nonce: luntan_nonce,
        id: commentId,
        type: '2'
      })
      console.log(res);
      if (res.code == 1) {
        // 消息提示
        // $this.message({
        //   messageText: '已取消点赞',
        //   duration: 3000,
        //   type: 'info'
        // });
      }


    } else {
      // 这是点赞逻辑
      $this.addClass("active");
      localStorage.setItem(`comment_like_${commentId}`, commentId)
      //点赞数加1
      $span.text(++currentLikes);

      //发请求确认点赞
      const res = await request({
        action: 'luntan_comment_like',
        nonce: luntan_nonce,
        id: commentId,
        type: '1'
      })
      if (res.code == 1) {
        // 消息提示
        // $this.message({
        //   messageText: '已点赞',
        //   duration: 3000,
        //   type: 'success'
        // });
      }

      //点赞和点踩不能同时进行，如果此条已点踩，取消点踩，删除本地存储
      if (localStorage.getItem(`comment_dislike_${commentId}`)) {
        const $cai = $this.siblings('.cai');
        $cai.removeClass("active");
        localStorage.removeItem(`comment_dislike_${commentId}`);
        //点踩数减1
        let num = Number($cai.find('span').text());
        $cai.find('span').text(--num);
        //发请求取消踩
        const res = await request({
          action: 'luntan_comment_like',
          nonce: luntan_nonce,
          id: commentId,
          type: '4'
        })
      }
    }
  }, 500, true));
  // 应用节流点踩
  $(".pinglunlist").on("click", ".cai", throttle(async function () {
    const $this = $(this)
    const commentId = $(this).data("id");
    const $span = $(this).find("span"); // 获取点赞数显示的<span>
    let currentLikes = parseInt($span.text()); // 当前点赞数（从HTML获取）

    // 对于是否点踩，用本地存储解决
    if (localStorage.getItem(`comment_dislike_${commentId}`)) {
      $this.removeClass("active");
      localStorage.removeItem(`comment_dislike_${commentId}`);
      //点踩数减1
      $span.text(--currentLikes);
      //发请求取消踩
      const res = await request({
        action: 'luntan_comment_like',
        nonce: luntan_nonce,
        id: commentId,
        type: '4'
      })
      if (res.code == 1) {
        // 消息提示
        // $this.message({
        //   messageText: '已取消点踩',
        //   duration: 3000,
        //   type: 'info'
        // });
      }
    } else {
      // 这是给评论点踩
      $this.addClass("active");
      localStorage.setItem(`comment_dislike_${commentId}`, commentId)
      //点赞踩加1
      $span.text(++currentLikes);

      //发请求确认点踩
      const res = await request({
        action: 'luntan_comment_like',
        nonce: luntan_nonce,
        id: commentId,
        type: '3'
      })
      if (res.code == 1) {
        // 消息提示
        // $this.message({
        //   messageText: '已点踩',
        //   duration: 3000,
        //   type: 'success'
        // });
      }

      //点赞和点踩不能同时进行，如果此条已点赞，取消点赞，删除本地存储
      if (localStorage.getItem(`comment_like_${commentId}`)) {
        // 因为类名不一致原因，元素不一样
        const $zan = $this.siblings('.zan')
        const $dianzan = $this.siblings('.dianzan')
        $zan.removeClass("active");
        $dianzan.removeClass("active");
        localStorage.removeItem(`comment_like_${commentId}`);

        //点赞数减1
        let num1 = Number($zan.find('span').text());
        let num2 = Number($dianzan.find('span').text());
        $zan.find('span').text(--num1)
        $dianzan.find('span').text(--num2)


        //发请求取消赞
        const res = await request({
          action: 'luntan_comment_like',
          nonce: luntan_nonce,
          id: commentId,
          type: '2'
        })
      }
    }
  }, 500, true));


  //---------------------------------------------------------删除评论
  $(document).on('click', '.pi_data .delete', async function () {
    // 获得评论ID
    const commentId = $(this).data("id");

    const res = await customMessageBox({
      title: '确认删除',
      message: '您确定永久删除此评论吗？',
      cancelButtonText: '取消',
      confirmButtonText: '确认'
    })
    // 点击弹窗确认按钮，才返回true
    if (res) {
      //发请求
      const res = await request({
        action: 'luntan_delete_pl',
        nonce: luntan_nonce,
        id: commentId,
      })
      if (res.code == 1) {
        //消息提示
        $(this).message({
          messageText: '已删除评论',
          duration: 3000,
          type: 'error'
        });

        //删除页面元素
        if ($(this).closest('.pid_item').length > 0) {
          $(this).closest('.pid_item').remove()
        }
        else {
          $(this).closest('.pinglun_item').remove()
        }

        //减去帖子评论数量
        let num = Number($('.tz_pl_box .tools .num').text().match(/\d+/g))
        $('.tz_pl_box .tools .num').text(`共${--num}条回复`)
      }
    }
  })


  //---------------------------------------------------------编辑评论
  // 文章--对它展开评论
  $(document).on('click', '.tz_pl_box .tools .t_right', function (e) {
    // 展开编辑区域
    $('.tz_pl_box .pinglun_box').slideToggle("fast");
    console.log("评论111111111111");
  })

  // 文章下的一级评论--对它展开评论
  $(document).on('click', '.pinglunlist .open', function (e) {
    // 获取该评论id
    const commentId = $(this).data("id")
    // 展开编辑区域
    $(`.pid_edit[data-id="${commentId}"]`).slideToggle("fast");
  })

  // 文章下的二级评论--对它展开评论
  $(document).on('click', '.pinglunlist .pid_list .pinglun', function (e) {
    // 获取该评论id
    const commentId = $(this).data("id")
    // 展开编辑区域
    $(`.pidi_pinglun[data-id="${commentId}"]`).slideToggle("fast");
  })


  // 上传评论图片专用数组
  class commentImgAllClass {
    constructor() {
      // 内部存储：每个 id 对应一个图片 URL 数组
      this.images = {};
    }

    // 只传一个 URL 字符串，自动添加到对应 id 的数组中
    addImage(id, url) {
      // 参数校验
      if (typeof url !== 'string' || !url.trim()) {
        console.warn('无效的图片 URL:', url);
        return this; // 返回 this 支持链式调用
      }

      // 如果该 id 还没有数组，自动创建一个空数组
      if (!this.images[id]) {
        this.images[id] = [];
      }

      // 将图片 URL 添加进去
      this.images[id].push(url);

      return this; // 支持链式调用
    }

    // 根据索引删除图片
    removeImageByIndex(id, index) {
      const imagesArray = this.images[id];
      if (!imagesArray) {
        console.warn(`ID ${id} 不存在`);
        return this;
      }
      if (index < 0 || index >= imagesArray.length) {
        console.warn(`索引 ${index} 超出范围`);
        return this;
      }
      imagesArray.splice(index, 1); // 使用 splice 方法移除指定索引的元素
      return this;
    }

    // 获取某个 id 的图片列表
    getImages(id) {
      return this.images[id] || [];
    }

    // 获取图片数量
    getCount(id) {
      return this.getImages(id).length;
    }

    // 检查图片是不是大于5
    hasEnoughImages(id, min = 5) {
      return this.getCount(id) >= min;
    }

    // 清空某个 id 的图片
    clearImages(id) {
      if (this.images[id]) {
        this.images[id] = [];
      }
      return this;
    }

    // 删除某个 id 的所有图片数据
    removeId(id) {
      delete this.images[id];
      return this;
    }
  }
  const commentImgAll = new commentImgAllClass

  // 点击添加图片按钮触发文件选择
  $('.pinglun_box .addImg, ' +
    '.pinglunlist .pid_edit .addImg,' +
    '.pinglunlist .pid_list .addImg').click(function () {
      // 拿到回复id
      const $this = $(this)
      const id = $this.data('id')
      // 图片限制
      if (commentImgAll.hasEnoughImages(id)) {
        alert('图片最多上传5张')
        return
      }
      // 创建隐藏的文件输入框
      const fileInput = $('<input type="file" accept="image/*" multiple style="display: none;">');
      $('body').append(fileInput);

      // 触发文件选择
      fileInput.click();

      // 监听文件选择事件
      fileInput.on('change', async function (e) {
        const files = e.target.files;
        if (files.length > 0) {
          uploadCommentImages(files, $this, id);
        }
        // 移除临时文件输入框
        fileInput.remove();
      });
    });

  // 移除图片功能
  $(document).on('click', '.pinglun_box .remove-img,' +
    '.pinglunlist .pid_edit .remove-img,' +
    '.pinglunlist .pid_list .remove-img', function (e) {
      //获取id
      const removeId = $(this).data('id');

      // 找到最近的 .uploaded-img 父元素
      const $parentImg = $(this).closest('.uploaded-img');

      // 定位父级容器（如 .gallery）
      const $gallery = $parentImg.parent();

      // 在容器内查找所有 .uploaded-img，计算索引
      const index = $gallery.find('.uploaded-img').index($parentImg);

      console.log('当前图片的索引为:', index);

      //移除图片
      $parentImg.remove();
      commentImgAll.removeImageByIndex(removeId, index)


      // const $uploadedImg = $(this).closest('.uploaded-img');
      // const index = $('.uploaded-img').index($uploadedImg);
      // $uploadedImg.remove();

      // commentImgAll.splice(index, 1);
      console.log(commentImgAll);
    });

  // 图片上传函数
  function uploadCommentImages(files, element, id) {
    // 限制图片
    if (commentImgAll.hasEnoughImages(id)) {
      alert('图片最多上传5张')
      return
    }
    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      if (!file.type.match('image.*')) {
        alert('请选择图片文件');
        continue;
      }

      // 创建FormData并添加所有字段
      const formData = new FormData();
      formData.append('nonce', luntan_nonce); // 添加 nonce 验证
      formData.append('action', 'luntan_post_img'); // 添加 nonce 验证
      formData.append('file', file, file.name); // 添加文件，包含文件名

      console.log(file);
      // 发送上传请求
      $.ajax({
        url: luntan_ajax,
        type: 'POST',
        data: formData,
        contentType: false,
        processData: false,
        dataType: 'json',
        success: function (response) {
          if (response.code == 1 && response.data) {
            // 上传成功，显示图片
            const imgHtml = `
                <div class="uploaded-img">
                  <img src="${response.data}" alt="图片">
                  <div class="remove-img" data-id="${id}">×</div>
                </div>
              `;
            // 找到.imgBox，添加html
            element.closest('.imgBox').append(imgHtml);

            // 给commentImgAll添加图片
            commentImgAll.addImage(id, response.data)
            console.log(commentImgAll);
          } else {
            alert('上传失败: ' + (response.msg || '未知错误'));
          }
        },
        error: function (xhr) {
          alert('网络错误，上传失败');
          console.error('AJAX错误:', xhr);
        },
        complete: function () {
          $('.uploading').remove();
        }
      });
    }
  }


  // 定义节流标志与延迟时间
  let commentSubmitLock = false;
  // 点击提交评论
  $(document).on('click', '.pinglun_box .submit,' +
    '.pinglunlist .pid_edit .submit,' +
    '.pinglunlist .pid_list .submit', async function () {

      if (commentSubmitLock) return;

      commentSubmitLock = true;

      // 拿到回复id
      const $this = $(this)
      const reviewID = $(this).data('id')
      console.log(reviewID);
      //拿到文本域
      var $textarea = $this.closest(':has(textarea)').find('textarea');
      // 收集表单
      let formData = {
        action: 'luntan_post_pl',
        content: $textarea.val().trim(),
        img: commentImgAll.getImages(reviewID).join(','),
        id: ID,//文章id
        parent: reviewID,
        nonce: luntan_nonce
      }
      // 请输入评论内容
      if (formData.content == "" || formData.content == null || formData.content == undefined) {
        alert('请输入评论内容')
        return
      }
      // 发请求
      const res = await request(formData)
      if (res.code == 1) {
        // 消息提示
        $(this).message({
          messageText: '已发布评论',
          duration: 3000,
          type: 'success'
        });
        commentSubmitLock = false;

        // 添加元素
        let newImgs = ''
        commentImgAll.getImages(reviewID).forEach(element => {
          newImgs += `<img data-watch="1" src="${element}" alt="">`
        });

        const newID = res.id
        console.log(newID);

        if ($this.closest('.pid_list').length > 0) {

          // 这是对二级评论的评论
          let oldAvatar = $this.closest('.pid_item').find('.hfr img').attr('src');
          let oldNickname = $this.closest('.pid_item').find('.hfr .nick').text();
          let newPid = `
      <div class="pid_item">
        <div class="pidi_top">
          <div class="people">
            <div class="hfr">
              <div class="avatar">
                <img src="${userDetail.avatar}" alt="">
              </div>

              <!-- @回复的人 -->
              <div class="nick">${userDetail.nickname}</div>
            </div>
            <div class="right_icon">
              <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 12 12" fill="none">
                <path d="M4.125 2.70711C4.125 2.26165 4.66357 2.03857 4.97855 2.35355L8.27145 5.64645C8.46671 5.84171 8.46671 6.15829 8.27145 6.35355L4.97855 9.64645C4.66357 9.96143 4.125 9.73835 4.125 9.29289L4.125 2.70711Z" fill="#777777"></path>
              </svg>
            </div>

            <div class="bhfr">
              <div class="avatar">
                <img src="${oldAvatar}" alt="">
              </div>

              <!-- @原评论人 -->
                <div class="nick">${oldNickname}</div>
              </div>
            </div>

            <!-- 回复时间 -->
            <div class="time">${getFormattedDate()}</div>
          </div>

          <div class="pidi_con">
            <!-- 回复内容 -->
            <div class="text">${$textarea.val().trim()}</div>
            <!-- 回复图片 -->
            <div class="imgs">
              ${newImgs}
            </div>

          </div>
          
          <div class="pidi_bom">
            <div class="mb_time">${getFormattedDate()}</div>
              <!-- @点赞 -->
              <div class="zan" data-id="${newID}">
              <svg width="18" height="18" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M27.6002 18.5998V11.3998C27.6002 8.41743 25.1826 5.99977 22.2002 5.99977L15.0002 22.1998V41.9998H35.9162C37.7113 42.0201 39.2471 40.7147 39.5162 38.9398L42.0002 22.7398C42.1587 21.6955 41.8506 20.6343 41.1576 19.8373C40.4645 19.0403 39.4564 18.5878 38.4002 18.5998H27.6002Z" stroke="#666" stroke-width="4" stroke-linejoin="round"></path>
                <path d="M15 22.0001H10.194C8.08532 21.9628 6.2827 23.7095 6 25.7994V38.3994C6.2827 40.4894 8.08532 42.0367 10.194 41.9994H15V22.0001Z" fill="none" stroke="#666" stroke-width="4" stroke-linejoin="round"></path>
              </svg>
              <span>0</span>
            </div>

            <!-- @点踩 -->
            <div class="cai" data-id="${newID}">
              <svg width="18" height="18" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M20.3793 29.4002V36.6002C20.3793 39.5826 22.7969 42.0002 25.7793 42.0002L32.9793 25.8002V6.00023H12.0633C10.2682 5.97994 8.73244 7.2853 8.46327 9.06023L5.97927 25.2602C5.82077 26.3045 6.12885 27.3657 6.82192 28.1627C7.51499 28.9597 8.52311 29.4122 9.57927 29.4002H20.3793Z" stroke="#666" stroke-width="4" stroke-linejoin="round"></path>
                <path d="M32.9795 6.00017H37.7855C39.8942 5.96288 41.6968 7.51019 41.9795 9.60017V22.2002C41.6968 24.2901 39.8942 26.0375 37.7855 26.0002H32.9795V6.00017Z" fill="none" stroke="#666" stroke-width="4" stroke-linejoin="round"></path>
              </svg>
              <span>0</span>
            </div>
            
            <!-- 只有是自己回复的才能删除 -->
            <div class="delete" data-id="${newID}">
              <img src="https://plan.seohnzz.com/wp-content/plugins/luntan/inc/index/assets/img/del_red.png" alt="">
              <span>删除</span>
            </div>

            <div class="pinglun" data-id="${newID}">
              <img src="https://plan.seohnzz.com/wp-content/plugins/luntan/inc/index/assets/img/remark_blue.png" alt="">
              <span>评论</span>
            </div>
          </div>

          <!-- 点击评论后出现 -->
          <div class="pidi_pinglun" data-id="${newID}" style="display: none;">
            <div class="pinglun_input">
              <!-- @文本域 -->
              <textarea autocomplete="off" rows="4" placeholder="请输入评论内容" class="el-textarea__inner" style="min-height: 43px;border: none;resize: vertical;outline: none;"></textarea>
            </div>
          <div class="pinglun_c_bom">
            <!-- 照片列表 -->
            <div class="imgBox">
            <!-- @上传图片 -->
            <div class="addImg" data-id="${newID}">
              <img src="https://plan.seohnzz.com/wp-content/plugins/luntan/inc/index/assets/img/addImg.png" alt="">
              <input type="file" name="img" multiple="multiple" accept=".jpg, .png, .webp, .gif, .jpeg" class="el-upload__input">
            </div>
          </div>

          <div class="submit" data-id="${newID}">发布</div>
        </div>
      </div>
    </div>
      `
          $this.closest('.pid_list').append(newPid)

        } else if ($this.closest('.pinglunlist').length > 0) {
          // 这是对一级评论的评论
          const oldAvatar = $this.closest('.pinglun_item').find('.pi_avatar img').attr('src');
          const oldNickname = $this.closest('.pinglun_item').find('.pid_top .nick').text();
          const newPid = `
        <div class="pid_item">
          <div class="pidi_top">
            <div class="people">
              <div class="hfr">
                <div class="avatar">
                  <img src="${userDetail.avatar}" alt="">
                </div>

                <!-- @回复的人 -->
                <div class="nick">${userDetail.nickname}</div>
              </div>
              <div class="right_icon">
                <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 12 12" fill="none">
                  <path d="M4.125 2.70711C4.125 2.26165 4.66357 2.03857 4.97855 2.35355L8.27145 5.64645C8.46671 5.84171 8.46671 6.15829 8.27145 6.35355L4.97855 9.64645C4.66357 9.96143 4.125 9.73835 4.125 9.29289L4.125 2.70711Z" fill="#777777"></path>
                </svg>
              </div>

              <div class="bhfr">
                <div class="avatar">
                  <img src="${oldAvatar}" alt="">
                </div>

                <!-- @原评论人 -->
                  <div class="nick">${oldNickname}</div>
                </div>
              </div>

              <!-- 回复时间 -->
              <div class="time">${getFormattedDate()}</div>
            </div>

            <div class="pidi_con">
              <!-- 回复内容 -->
              <div class="text">${$textarea.val().trim()}</div>
              <!-- 回复图片 -->
              <div class="imgs">
                ${newImgs}
              </div>

            </div>
            
            <div class="pidi_bom">
              <div class="mb_time">${getFormattedDate}</div>
                <!-- @点赞 -->
                <div class="zan" data-id="${newID}">
                <svg width="18" height="18" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M27.6002 18.5998V11.3998C27.6002 8.41743 25.1826 5.99977 22.2002 5.99977L15.0002 22.1998V41.9998H35.9162C37.7113 42.0201 39.2471 40.7147 39.5162 38.9398L42.0002 22.7398C42.1587 21.6955 41.8506 20.6343 41.1576 19.8373C40.4645 19.0403 39.4564 18.5878 38.4002 18.5998H27.6002Z" stroke="#666" stroke-width="4" stroke-linejoin="round"></path>
                  <path d="M15 22.0001H10.194C8.08532 21.9628 6.2827 23.7095 6 25.7994V38.3994C6.2827 40.4894 8.08532 42.0367 10.194 41.9994H15V22.0001Z" fill="none" stroke="#666" stroke-width="4" stroke-linejoin="round"></path>
                </svg>
                <span>0</span>
              </div>

              <!-- @点踩 -->
              <div class="cai" data-id="${newID}">
                <svg width="18" height="18" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M20.3793 29.4002V36.6002C20.3793 39.5826 22.7969 42.0002 25.7793 42.0002L32.9793 25.8002V6.00023H12.0633C10.2682 5.97994 8.73244 7.2853 8.46327 9.06023L5.97927 25.2602C5.82077 26.3045 6.12885 27.3657 6.82192 28.1627C7.51499 28.9597 8.52311 29.4122 9.57927 29.4002H20.3793Z" stroke="#666" stroke-width="4" stroke-linejoin="round"></path>
                  <path d="M32.9795 6.00017H37.7855C39.8942 5.96288 41.6968 7.51019 41.9795 9.60017V22.2002C41.6968 24.2901 39.8942 26.0375 37.7855 26.0002H32.9795V6.00017Z" fill="none" stroke="#666" stroke-width="4" stroke-linejoin="round"></path>
                </svg>
                <span>0</span>
              </div>
              
              <!-- 只有是自己回复的才能删除 -->
              <div class="delete" data-id="${newID}">
                <img src="https://plan.seohnzz.com/wp-content/plugins/luntan/inc/index/assets/img/del_red.png" alt="">
                <span>删除</span>
              </div>

              <div class="pinglun" data-id="${newID}">
                <img src="https://plan.seohnzz.com/wp-content/plugins/luntan/inc/index/assets/img/remark_blue.png" alt="">
                <span>评论</span>
              </div>
            </div>

            <!-- 点击评论后出现 -->
            <div class="pidi_pinglun" data-id="${newID}" style="display: none;">
              <div class="pinglun_input">
                <!-- @文本域 -->
                <textarea autocomplete="off" rows="4" placeholder="请输入评论内容" class="el-textarea__inner" style="min-height: 43px;border: none;resize: vertical;outline: none;"></textarea>
              </div>
            <div class="pinglun_c_bom">
              <!-- 照片列表 -->
              <div class="imgBox">
              <!-- @上传图片 -->
              <div class="addImg" data-id="${newID}">
                <img src="https://plan.seohnzz.com/wp-content/plugins/luntan/inc/index/assets/img/addImg.png" alt="">
                <input type="file" name="img" multiple="multiple" accept=".jpg, .png, .webp, .gif, .jpeg" class="el-upload__input">
              </div>
            </div>

            <div class="submit" data-id="${newID}">发布</div>
          </div>
        </div>
      </div>
        `

          $this.closest('.pi_data').find('.pid_list').append(newPid)
        } else {
          // 这是对文章的评论
          const newPl = `
      <div class="pinglun_item">
        <div class="pi_avatar">
        <!-- 头像 -->
          <img src="${userDetail.avatar}" alt="">
        </div>

      <div class="pi_data">
        <div class="pid_top">
          <!-- @用户名 -->
          <div class="nick">${userDetail.nickname}</div>
          <div class="pi_action">
            <!-- @点赞 -->
            <div class="dianzan" data-id="${newID}">
            <svg width="18" height="18" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M27.6002 18.5998V11.3998C27.6002 8.41743 25.1826 5.99977 22.2002 5.99977L15.0002 22.1998V41.9998H35.9162C37.7113 42.0201 39.2471 40.7147 39.5162 38.9398L42.0002 22.7398C42.1587 21.6955 41.8506 20.6343 41.1576 19.8373C40.4645 19.0403 39.4564 18.5878 38.4002 18.5998H27.6002Z" stroke="#666" stroke-width="4" stroke-linejoin="round"></path>
              <path d="M15 22.0001H10.194C8.08532 21.9628 6.2827 23.7095 6 25.7994V38.3994C6.2827 40.4894 8.08532 42.0367 10.194 41.9994H15V22.0001Z" fill="none" stroke="#666" stroke-width="4" stroke-linejoin="round"></path>
            </svg>
              <span>0</span>
            </div>
            <!-- @点踩 -->
            <div class="cai"  data-id="${newID}">
              <svg width="18" height="18" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M20.3793 29.4002V36.6002C20.3793 39.5826 22.7969 42.0002 25.7793 42.0002L32.9793 25.8002V6.00023H12.0633C10.2682 5.97994 8.73244 7.2853 8.46327 9.06023L5.97927 25.2602C5.82077 26.3045 6.12885 27.3657 6.82192 28.1627C7.51499 28.9597 8.52311 29.4122 9.57927 29.4002H20.3793Z" stroke="#666" stroke-width="4" stroke-linejoin="round"></path>
              <path d="M32.9795 6.00017H37.7855C39.8942 5.96288 41.6968 7.51019 41.9795 9.60017V22.2002C41.6968 24.2901 39.8942 26.0375 37.7855 26.0002H32.9795V6.00017Z" fill="none" stroke="#666" stroke-width="4" stroke-linejoin="round"></path>
              </svg>
              <span>0</span>
            </div>

            <!-- @删除 -->
            <div class="delete"  data-id="${newID}">
              <img src="https://plan.seohnzz.com/wp-content/plugins/luntan/inc/index/assets/img/del_red.png" alt="">
              <span>删除</span>
            </div>

            <!-- @评论 -->
            <div class="open"  data-id="${newID}">
              <img src="https://plan.seohnzz.com/wp-content/plugins/luntan/inc/index/assets/img/remark_blue.png" alt="">
                <span>评论</span>
            </div>
          </div>
        </div>

        <div class="pid_con">
          <!-- @评论正文 -->
          <div class="text" data-id="${newID}" >${$textarea.val().trim()}</div>
          <!-- @评论图片 -->
          <div class="imgs" data-id="${newID}" >
            ${newImgs}
          </div>
        </div>

        <!-- @评论时间 -->
        <div class="pid_bom">${getFormattedDate()}</div>
        <!-- 回复编辑 -->
        <div class="pid_edit" data-id="${newID}" >
          <div class="pinglun_input" data-id="${newID}" >
          <!-- @文本域 -->
          <textarea autocomplete="off" rows="4" placeholder="请输入评论内容" class="el-textarea__inner" style="min-height: 43px;border: none;resize: vertical;outline: none;"></textarea>
          </div>

          <div class="pinglun_c_bom">
            <!-- 照片列表 -->
            <div class="imgBox" data-id="${newID}" >
              <!-- @上传图片 -->
              <div class="addImg"  data-id="${newID}">
                <img src="https://plan.seohnzz.com/wp-content/plugins/luntan/inc/index/assets/img/addImg.png" alt="">

                <input type="file" name="img" multiple="multiple" accept=".jpg, .png, .webp, .gif, .jpeg" class="el-upload__input">
              </div>
            </div>

            <div class="submit"  data-id="${newID}">发布</div>
          </div>
        </div>
          
        <!-- 评论的回复 -->
        <div class="pid_list">
          <!-- 评论的盒子 -->
        </div>
      </div>
      </div>`

          $('.pinglunlist').append(newPl)
        }

        //收起评论编辑区
        $('.tz_pl_box .pinglun_box').css('display', 'none');
        $(`.pid_edit`).css('display', 'none');
        $(`.pidi_pinglun`).css('display', 'none');

        //添加帖子评论数量
        let num = Number($('.tz_pl_box .tools .num').text().match(/\d+/g))
        $('.tz_pl_box .tools .num').text(`共${++num}条回复`)

        //清空输入框
        $('.pinglun_box .pinglun_input textarea').val('')
        $('.pinglun_c_bom .imgBox .uploaded-img').remove();


      } else {
        commentSubmitLock = false;
      }
      console.log(formData);
    })


  //------------------------------------------------------图片查看器

  let scale = 1;
  let posX = 0;
  let posY = 0;
  let isDragging = false;
  let startX, startY;

  function initViewer(src) {
    scale = 1;
    posX = 0;
    posY = 0;

    const $viewer = $('<div class="viewer-container"></div>');
    const $img = $('<img>').attr('src', src).css('cursor', 'grab');

    $viewer.append($img).appendTo('body');
    disableScroll();

    // 关闭：点击空白处移除 viewer 元素
    $viewer.on('click', function (e) {
      if ($(e.target).is($viewer)) {
        $viewer.remove();
        enableScroll();
      }
    });

    // 滚轮缩放（以鼠标为中心）
    $img.on('wheel', function (e) {
      e.preventDefault();

      const delta = e.originalEvent.deltaY > 0 ? -0.1 : 0.1;
      const newScale = Math.max(0.5, Math.min(scale + delta, 5));

      if (newScale !== scale) {
        const imgOffset = $img.offset();
        const imgCenterX = imgOffset.left + $img.width() / 2;
        const imgCenterY = imgOffset.top + $img.height() / 2;

        const mouseX = e.pageX;
        const mouseY = e.pageY;

        const dx = mouseX - imgCenterX;
        const dy = mouseY - imgCenterY;
        const ratio = newScale / scale;

        posX -= dx * (ratio - 1);
        posY -= dy * (ratio - 1);

        scale = newScale;

        $img.css('transform', `translate(${posX}px, ${posY}px) scale(${scale})`);
      }
    });

    // 拖动图片
    $img.on('mousedown touchstart', function (e) {
      if (e.type === 'mousedown' && e.button !== 0) return;

      isDragging = true;
      startX = e.pageX || e.touches[0].pageX;
      startY = e.pageY || e.touches[0].pageY;

      $img.css('cursor', 'grabbing');
      e.preventDefault();
    });

    $(document).on('mousemove.viewer touchmove.viewer', function (e) {
      if (!isDragging) return;

      const moveX = e.pageX || e.touches[0].pageX;
      const moveY = e.pageY || e.touches[0].pageY;

      const dx = moveX - startX;
      const dy = moveY - startY;

      posX += dx;
      posY += dy;

      startX = moveX;
      startY = moveY;

      $img.css('transform', `translate(${posX}px, ${posY}px) scale(${scale})`);
    });

    $(document).on('mouseup.viewer touchend.viewer', function () {
      isDragging = false;
      $img.css('cursor', 'grab');
    });

    // 清理全局事件
    $viewer.on('remove', function () {
      $(document).off('.viewer');
    });
  }
  // 绑定点击图片启动查看器
  $(document).on('click', 'img[data-watch="1"]', function () {
    const src = $(this).attr('src');
    initViewer(src);
  })

});

// 其他板块控制
$('.fbr_other a').click(function () {
  // 获取当前点击元素的下标（从0开始）
  const index = $(this).data('id');
  localStorage.setItem('INDEX_LUNTAN', index)
});