<template>
  <view class="page-container tn-gradient-bg__cool-5" @click="hideUserMenu">
    <cheader></cheader>
    <div class="index-body">
      <div class="body-title">
        <span class="title-mian"></span>
        <!-- 右上角用户信息缩略展示 -->
        <view class="user-mini" @click.stop="toggleUserMenu">
          <image :src="userInfo.image" class="user-mini-avatar"></image>
          <text class="user-mini-name">{{ userInfo.realName || "" }}</text>
          <view v-if="showUserMenu" class="user-menu" @click.stop>
            <view class="user-menu-item" @click.stop="loginOutAction"
              >退出登录</view
            >
          </view>
        </view>
      </div>
      <div class="body-content">
        <!-- 左侧数据展示纵向排列 -->
        <div class="stats-column">
          <h2>大厅概况</h2>
          <div class="stat-card" @click="goToHallInfo()">
            <p class="stat-title">当前等候人数</p>
            <p class="stat-value">{{ waitingCount }}</p>
          </div>
          <div class="stat-card" @click="goToHallInfo()">
            <p class="stat-title">今日预约人数</p>
            <p class="stat-value">{{ todayAppointmentCount }}</p>
          </div>
          <div class="stat-card" @click="goToHallInfo()">
            <p class="stat-title">空闲窗口</p>
            <p class="stat-value">{{ idleWindowCount }}</p>
          </div>
          <div class="stat-card" @click="goToHallInfo()">
            <p class="stat-title">空闲自助机</p>
            <p class="stat-value">{{ idleKioskCount }}</p>
          </div>
        </div>
        <!-- 右侧功能按钮区 -->
        <div class="btn-content">
          <div class="btn-row1">
            <div class="row1-item1 col-center" @click="goToQueue()">
              <uni-icons type="compose" size="60" color="#fff"></uni-icons>
              <p class="btn-p">预检取号</p>
            </div>
            <div class="row1-item2 col-center" @click="goToTicket()">
              <uni-icons type="list" size="60" color="#fff"></uni-icons>
              <p class="btn-p">票号管理</p>
            </div>
            <div class="row1-item3 col-center" @click="goToManager()">
              <uni-icons type="staff-filled" size="60" color="#fff"></uni-icons>
              <p class="btn-p">网格员</p>
            </div>
          </div>
          <!-- <div style="height: 2vh"></div> -->
          <div class="btn-row2">
            <div class="row2-item1">
              <div class="row2-item1-top row-center" @click="goToPushMessage()">
                <uni-icons type="info" size="60" color="#fff"></uni-icons>
                <p class="btn-p">信息推送</p>
              </div>
              <!-- <div style="height: 2vh"></div> -->
              <div
                class="row2-item1-bottom row-center"
                @click="openNormalTakeTicket"
              >
                <uni-icons type="compose" size="60" color="#fff"></uni-icons>
                <p class="btn-p">普通取号</p>
              </div>
            </div>
            <div class="row2-item2">
              <div
                class="row2-item2-left col-center"
                @click="goToSignPriority()"
              >
                <uni-icons
                  type="home-filled"
                  size="60"
                  color="#fff"
                ></uni-icons>
                <p class="btn-p">回签优先</p>
              </div>
              <!-- <div style="width: 2vh"></div> -->
              <div class="row2-item2-center col-center">
                <uni-icons
                  type="auth-filled"
                  size="60"
                  color="#fff"
                ></uni-icons>
                <p class="btn-p">预留功能</p>
              </div>
              <!-- <div style="width: 2vh"></div> -->
              <div class="row2-item2-right col-center">
                <uni-icons
                  type="settings-filled"
                  size="60"
                  color="#fff"
                ></uni-icons>
                <p class="btn-p">预留功能</p>
              </div>
              <!-- <div v-for="item in 3" style="flex: 1;"></div> -->
            </div>
          </div>
        </div>
      </div>
    </div>
    <TakeTicketPopup ref="takeTicketPopupRef" />
  </view>
</template>

<script setup>
import { getAuthProfile } from "@/api/index.js";
import { getOverview } from "@/api/system.js";
import cheader from "@/components/header.vue";
import TakeTicketPopup from "@/components/TakeTicketPopup/TakeTicketPopup.vue";
import {
  onBackPress,
  onHide,
  onLoad,
  onShow,
  onUnload,
} from "@dcloudio/uni-app";
import { ref } from "vue";

const userInfo = ref({
  realName: "",
  id: "",
  image: "",
});

// 用户菜单
const showUserMenu = ref(false);
const toggleUserMenu = () => {
  showUserMenu.value = !showUserMenu.value;
};
const hideUserMenu = () => {
  showUserMenu.value = false;
};

// 数据展示模块
const waitingCount = ref(0);
const todayAppointmentCount = ref(0);
const idleWindowCount = ref(0);
const idleKioskCount = ref(0);
const takeTicketPopupRef = ref(null);
let overviewTimer = null;

onBackPress(() => {
  return true;
});

onLoad(() => {
  try {
    const storageData = uni.getStorageSync("userInfo");
    if (storageData) {
      const parsedData = JSON.parse(storageData);
      userInfo.value = {
        realName: parsedData.realName || "",
        id: parsedData.id || "",
        image: parsedData.image || "/static/header_no.png",
      };
      console.log("用户信息:", userInfo.value);
    }
    initData();
  } catch (error) {
    console.error("获取用户信息失败:", error);
  }
});

const initData = async () => {
  try {
    const res = await getOverview();
    console.log("大厅概况", res);
    waitingCount.value = Number(res?.waitingCount ?? 0);
    todayAppointmentCount.value = Number(res?.todayAppointmentCount ?? 0);
    idleWindowCount.value = Number(res?.idleWindowCount ?? 0);
    idleKioskCount.value = Number(res?.idleKioskCount ?? 0);
  } catch (error) {
    console.log("获取大厅概况失败", error);
  }
};

const loadHallNameFromProfile = async () => {
  try {
    const profile = await getAuthProfile();
    const swjgMC = profile?.swjgMC || profile?.swjgMc || "";
    console.log("[auth/profile@index] response:", profile);
    console.log("[auth/profile@index] parsed swjgMC:", swjgMC);
    if (swjgMC) {
      uni.setStorageSync("swjgMC", swjgMC);
      uni.$emit("hall-name-updated");
      console.log("[auth/profile@index] swjgMC saved");
    } else {
      console.log("[auth/profile@index] swjgMC is empty, skip save");
    }
  } catch (error) {
    console.log("获取机构名称失败", error);
  }
};

const startOverviewTimer = () => {
  if (overviewTimer) {
    clearInterval(overviewTimer);
  }
  overviewTimer = setInterval(() => {
    initData();
  }, 300000);
};

const stopOverviewTimer = () => {
  if (overviewTimer) {
    clearInterval(overviewTimer);
    overviewTimer = null;
  }
};

onShow(() => {
  loadHallNameFromProfile();
  initData();
  startOverviewTimer();
});

onHide(() => {
  stopOverviewTimer();
});

onUnload(() => {
  stopOverviewTimer();
});

const goToGuidance = () => {
  uni.navigateTo({
    url: "/pages/mod/guidance?isFromTicket=false",
  });
};

const goToDailyEntry = () => {
  uni.navigateTo({
    url: "/pages/table/dailyEntry",
  });
};

const goToAppointment = () => {
  uni.navigateTo({
    url: "/pages/table/appointment",
  });
};

const goToTicket = () => {
  uni.navigateTo({
    url: "/pages/table/ticket",
  });
};

const goToMultiInOne = () => {
  uni.navigateTo({
    url: "/pages/mod/multiInOne",
  });
};

const goToPushMessage = () => {
  uni.navigateTo({
    url: "/pages/mod/pushMessage",
  });
};

const goToQueue = () => {
  uni.navigateTo({
    url: "/pages/queue/index",
  });
};

const goToManager = () => {
  uni.navigateTo({
    url: "/pages/mod/manager",
  });
};

const goToHallManagment = () => {
  uni.navigateTo({
    url: "/pages/mod/hallManagment",
  });
};

const goToHallInfo = () => {
  uni.navigateTo({
    url: "/pages/mod/hallInfo",
  });
};

const goToSignPriority = () => {
  uni.navigateTo({
    url: "/pages/mod/sign-priority",
  });
};

const openNormalTakeTicket = () => {
  takeTicketPopupRef.value?.open();
};

const loginOutAction = () => {
  uni.showModal({
    title: "登出",
    content: "是否退出登录，并返回到登录界面？",
    success: (res) => {
      if (res.confirm) {
        // 先停止轮询，避免退出后仍持续请求
        stopOverviewTimer();
        // 清除登录态缓存，但保留 swjgMC 以便下次启动直接显示大厅名称
        uni.removeStorageSync("token");
        uni.removeStorageSync("refresh_token");
        uni.removeStorageSync("userInfo");
        // 重启路由栈，彻底离开当前页，避免后台页面继续触发请求
        uni.reLaunch({
          url: "/pages/login/login",
        });
      }
      // 如果用户点击取消，则什么都不做，停留在当前页面
    },
  });
};
</script>

<style lang="scss">
.index-body {
  height: 90vh;
  width: 100vw;
  margin-top: 2vh;
  display: flex;
  flex-direction: column;
  // justify-content: center;
  align-items: center;

  .body-title {
    height: 10vh;
    margin-bottom: 2vh;
    display: flex;
    align-items: center;
    justify-content: space-between;
    /* 关键：让标题区域占满可用宽度，space-between 才能拉开两端 */
    width: 80vw;
    max-width: 100vw;

    .title-mian {
      background: linear-gradient(to bottom, #adadad 10%, #fff 90%);
      /* 2. 将背景裁剪成文字形状 (需要-webkit-前缀) */
      -webkit-background-clip: text;
      background-clip: text;
      /* 3. 将文字颜色设为透明，显示出渐变背景 */
      color: transparent;
      /* 为了效果明显，可以设置一些字体样式 */
      font-size: 36px;
      font-weight: 600;
    }

    /* 顶部用户缩略信息 */
    .user-mini {
      position: relative;
      display: flex;
      align-items: center;
      background-color: rgba(0, 0, 0, 0.3);
      border-radius: 25px;
      padding: 6px 10px 6px 6px;

      .user-mini-avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        border: 1px solid #fff;
        margin-right: 10px;
        object-fit: cover;
      }

      .user-mini-name {
        font-size: 18px;
        color: #fff;
      }

      .user-menu {
        position: absolute;
        top: 100%;
        right: 0;
        margin-top: 6px;
        background-color: rgba(0, 0, 0, 0.3);
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        overflow: hidden;
        min-width: 120px;
        z-index: 10;

        .user-menu-item {
          padding: 10px 16px;
          font-size: 14px;
          color: #fff;
          text-align: center;
        }

        .user-menu-item:active {
          background-color: #f5f5f5;
        }
      }
    }
  }

  .body-content {
    display: flex;
    flex-direction: row;
    align-items: stretch;
    width: 82vw;
    max-width: 82vw;
    --module-gap: 10px;

    /* 左侧数据展示列 */
    .stats-column {
      width: 18vw;
      margin-right: 4vw;
      display: flex;
      flex-direction: column;
      flex: 0 0 18vw;
      gap: var(--module-gap);

      h2 {
        color: #fff;
        margin-bottom: 0;
      }

      .stat-card {
        background: #ffffffe0;
        border-radius: $card-border-radius;
        padding: 16px 20px;
        flex: 1;
        min-height: 0;
        display: flex;
        flex-direction: column;
        justify-content: center;
        box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
      }

      .stat-title {
        font-size: 16px;
        color: #555;
        margin-bottom: 8px;
      }

      .stat-value {
        font-size: 28px;
        font-weight: bold;
        color: #007aff;
      }
    }

    .btn-content {
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: var(--module-gap);

      .btn-row1 {
        flex: 1;
        min-height: 0;
        width: 100%;
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: var(--module-gap);

        .row1-item1 {
          background: #cc3333;
          border-radius: $card-border-radius;
        }

        .row1-item2 {
          background-color: #cc3366;
          border-radius: $card-border-radius;
        }

        .row1-item3 {
          background-color: #cc3399;
          border-radius: $card-border-radius;
        }
      }

      .btn-row2 {
        flex: 1.6;
        min-height: 0;
        width: 100%;
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: var(--module-gap);

        .row2-item1 {
          display: flex;
          flex-direction: column;
          gap: var(--module-gap);

          .row2-item1-top {
            flex: 1;
            background-color: #99ccff;
            border-radius: $card-border-radius;
          }

          .row2-item1-bottom {
            flex: 1;
            background-color: #9999ff;
            border-radius: $card-border-radius;
          }
        }

        .row2-item2 {
          grid-column: span 2;
          display: flex;
          flex-direction: row;
          gap: var(--module-gap);

          .row2-item2-left {
            flex: 1;
            background-color: #ffcc99;
            border-radius: $card-border-radius;
          }

          .row2-item2-center {
            flex: 1;
            background-color: #ffcccc;
            border-radius: $card-border-radius;
          }

          .row2-item2-right {
            flex: 1;
            background-color: #ffccff;
            border-radius: $card-border-radius;
          }
        }
      }
    }
  }
}

.col-center {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.row-center {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}

.btn-p {
  font-size: 22px;
  font-weight: 800;
  color: #fff;
  margin: 8px;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}
</style>
