layui.use(["element", "layer"], function () {
  var element = layui.element;

  var layer = layui.layer;

  var $ = layui.$;

  // 检查认证状态

  function checkAuth() {
    try {
      // 从 cookie 中获取 token
      const token = localStorage.getItem('token');
      // console.log(token); 
      if (!token) {
        window.location.href = "/login";
        return false;
      }
      return true;
    } catch (error) {
      console.error("认证检查失败：", error);
      window.location.href = "/login";
      return false;
    }
  }

  // 添加请求拦截器
  function addAuthHeader(url) {
    const token = localStorage.getItem('token');
    if (!token) {
      window.location.href = '/login';
      return false;
    }

    return {
      'Authorization': 'Bearer ' + token,
      'Content-Type': 'application/json'
    };
  }

  // 封装fetch请求
  async function request(url, options = {}) {
    const headers = addAuthHeader(url);
    if (!headers) return;

    const response = await fetch(url, {
      ...options,
      headers: {
        ...headers,
        ...options.headers
      }
    });

    if (response.status === 401) {
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      window.location.href = '/login';
      return;
    }

    return response.json();
  }

  // 在页面加载时检查认证

  $(document).ready(function () {
    if (!checkAuth()) return;

    // 加载用户信息

    authFetch("/api/users/profile")
      .then((user) => {
        $("#current-user").text(user.username);

        // 根据用户角色显示/隐藏菜单

        if (user.role !== "admin") {
          $(".admin-only").hide();
        }
      })

      .catch((error) => {
        layer.msg("加载用户信息失败：" + error.message);
      });

    // 加载站点配置

    loadSiteConfig();

    // 默认加载 dashboard

    loadPage("/admin/dashboard", "控制台");
  });

  // 左侧菜单点击事件

  $(".layui-nav-item a").on("click", function () {
    var url = $(this).data("url");

    if (url) {
      var title = $(this).text().trim();

      loadPage(url, title);
    }
  });

  // 加载页面内容

  function loadPage(url, title) {
    // 更新面包屑

    updateBreadcrumb(title);

    // 加载页面内容

    $("#content-frame").attr("src", url+"?token="+localStorage.getItem('token'));

    // 更新选中状态

    $(".layui-nav-item").removeClass("layui-this");

    $(`a[data-url="${url}"]`).parent().addClass("layui-this");
  }

  // 更新面包屑导航

  function updateBreadcrumb(title) {
    var html =
      '<a href="javascript:;">首页</a> <span lay-separator="">/</span> ' +
      title;

    $(".layui-breadcrumb").html(html);

    element.render("breadcrumb");
  }

  // 修改密码

  $(".change-password").on("click", function () {
    layer.open({
      type: 2,

      title: "修改密码",

      area: ["500px", "300px"],

      content: "/admin/change-password",
    });
  });

  // 退出登录

  $(".logout").on("click", function () {
    layer.confirm("确定要退出登录吗？", function (index) {
      // 清除 cookie
      document.cookie = "token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";
      window.location.href = '/login';
      layer.close(index);
    });
  });

  // 加载站点配置

  function loadSiteConfig() {
    authFetch("/api/site/settings")
      .then((data) => {
        if (data.error) {
          layer.msg(data.error);

          return;
        }

        // 更新页面元素

        document.title = data.title;

        $("#site-title").text(data.title);

        $("#site-description").attr("content", data.description);

        $("#site-favicon").attr("href", data.favicon);

        $("#site-logo").attr("src", data.logo);

        $("#site-name").text(data.title);

        $("#site-copyright").text(data.copyright);

        $("#site-icp").text(data.icp);
      })

      .catch((error) => {
        layer.msg("加载配置失败：" + error.message);
      });
  }

  // 监听子页面消息

  window.addEventListener('message', function(event) {
    if (event.data.type === 'updateBreadcrumb') {
      updateBreadcrumb(event.data.title);
    }
  });
});
