import { defineStore } from "pinia";
import { ref } from "vue";
import dayjs from "dayjs";
import { getPoints } from "@/service/modular/hospital";

// sessionStorage key：当天是否已经处理过（弹过 / 已签到不再弹）
const POPUP_FLAG_KEY = "csm_signin_popup_date";

/**
 * 全局签到弹窗状态（AdminLayout 承载组件，登录后由 layout 触发）
 * - open()                 打开
 * - close()                关闭 + 标记今日已处理
 * - checkAndShow()         登录后调用：取 summary 判断是否需要弹
 * - refreshSummary()       签到成功后刷新 summary 数据
 * - fireSigned()           签到成功后由 SignInDialog 调用,触发 onSigned 回调
 */
export const useSignInDialogStore = defineStore("signInDialog", () => {
  const visible = ref(false);
  const loading = ref(false);

  // 透传给 SignInDialog 的字段（来自 /hospital/points 接口 summary）
  const summary = ref({
    isSignIn: false,
    isDraw: false,
    totalPoints: 0,
    consecutiveSignInDays: 0,
    signInRank: 0,
    beatPercent: 0,
  });

  // 签到成功回调（AdminLayout 注册,用于打开 RewardResultDialog）
  const onSigned = ref(null);

  const todayKey = () => dayjs().format("YYYY-MM-DD");

  // 当天是否已经处理过（弹过 / 已签到跳过）
  const hasHandledToday = () => {
    try {
      return sessionStorage.getItem(POPUP_FLAG_KEY) === todayKey();
    } catch {
      return false;
    }
  };

  const markHandledToday = () => {
    try {
      sessionStorage.setItem(POPUP_FLAG_KEY, todayKey());
    } catch {
      /* sessionStorage 不可用时静默忽略 */
    }
  };

  const unwrap = (res) => res?.data ?? res ?? {};

  const setSummary = (data) => {
    summary.value = {
      isSignIn: !!data?.isSignIn,
      isDraw: !!data?.isDraw,
      totalPoints: Number(data?.totalPoints) || 0,
      consecutiveSignInDays: Number(data?.consecutiveSignInDays) || 0,
      signInRank: Number(data?.signInRank) || 0,
      beatPercent: Number(data?.beatPercent) || 0,
    };
  };

  const open = () => {
    visible.value = true;
  };

  const close = () => {
    visible.value = false;
    // 用户主动关闭：标记今天不再弹（避免反复打扰）
    markHandledToday();
  };

  /**
   * 登录后 / 路由进入 layout 时调用：
   * 1) sessionStorage 已标记今天处理过 → 不再请求接口、不弹
   * 2) 调 getPoints 取 summary，更新 store
   * 3) 今日未签到才弹（已签到不弹，但仍标记今天已处理）
   */
  const checkAndShow = async () => {
    if (hasHandledToday()) return;
    if (loading.value) return;
    loading.value = true;
    try {
      const res = unwrap(await getPoints());
      setSummary(res);
      if (!summary.value.isSignIn) {
        open();
      }
      // 不论是否弹，都标记今天已处理
      markHandledToday();
    } catch (_) {
      // 接口失败时不弹也不标记，下次重试
    } finally {
      loading.value = false;
    }
  };

  // 签到成功后刷新 summary（不弹窗，仅更新数据）
  const refreshSummary = async () => {
    try {
      const res = unwrap(await getPoints());
      setSummary(res);
      return res;
    } catch (_) {
      /* 静默失败,不影响签到成功提示 */
      return null;
    }
  };

  // 触发签到成功回调
  const fireSigned = () => {
    if (typeof onSigned.value === "function") {
      onSigned.value();
    }
  };

  return {
    visible,
    loading,
    summary,
    onSigned,
    open,
    close,
    checkAndShow,
    refreshSummary,
    fireSigned,
  };
});
