<script setup>
import { watch, onBeforeUnmount } from "vue";
import { onLaunch, onShow, onHide } from "@dcloudio/uni-app";
import {
  useSystemStore,
  useShopStore,
  useVideoStore,
  useSocketStore,
  useMessageStore,
  useUserStore,
  useTabbarStore,
} from "@/store";
import { storeToRefs } from "pinia";
import { setLan, findLang } from "@/locale";
import { parseUrl } from "@/utils";
import appUpdate from "./utils/appUpdate";
import { USER_INIT } from "@/api";

const useSystem = useSystemStore();
const useShop = useShopStore();
const useVideo = useVideoStore();
const useScoket = useSocketStore();
const useMessage = useMessageStore();
const useUser = useUserStore();
const useTabbar = useTabbarStore();

const { isFirstConnectNetwork, networkStatus, isHomeFirstConnect } =
  storeToRefs(useSystem);

function initFunc() {
  useSystem.setWinnotice();
  useSystem.setRateList();
  useShop.setCartList();
  useShop.setHotLink();
  useScoket.connect();
  // useVideo.setVideoList();
}

onLaunch(async () => {
  useSystem.checkNetworkStatus();
  // 监听网络状态
  listenerNetworkStatus();
  // initFunc();
  // #ifdef APP-PLUS
  appUpdate();
  initPushService();
  clearBadge();
  // #endif

  // #ifdef H5
  setInit();
  // #endif
});
onShow(() => {
  clearBadge();
  // #ifdef H5
  getLang();
  // #endif
});
onHide(() => {});

onBeforeUnmount(() => {
  uni.$off("$onMessage");
  stopWatch();
});

const stopWatch = watch(
  [isFirstConnectNetwork, networkStatus], // 监听多个响应式变量
  ([newIsFirst, newNetStatus], [oldIsFirst, oldNetStatus]) => {
    // console.log("联动变化：", {
    //   首次连接标记: `${oldIsFirst}→${newIsFirst}`,
    //   网络状态: `${oldNetStatus ? "已连接" : "断开"}→${
    //     newNetStatus ? "已连接" : "断开"
    //   }`,
    // });
    if (newNetStatus) {
      initFunc();
      useSystem.setFirstConnectStatus(false);
    }
  }
);
function listenerNetworkStatus() {
  uni.onNetworkStatusChange((res) => {
    const { isConnected, networkType } = res;
    if (isConnected && networkType != "none") {
      if (isFirstConnectNetwork.value) {
        initFunc();
      }
      useSystem.setNetworkStatus(true);
    } else {
      useSystem.setNetworkStatus(false);
    }
  });
}

const getLang = () => {
  let urlObj = parseUrl(window.location.href);
  let lang = urlObj["lang"];
  let langValue = findLang(lang) && findLang(lang).value;
  if (langValue) {
    useSystem.setLan(langValue);
    setLan(langValue, () => {
      useShop.setHotLink();
    });
  }
};

function initPushService() {
  uni.getPushClientId({
    success: (res) => {
      setInit({ push_cid: res.cid });
    },
    fail: (err) => {
      setInit();
      console.error("获取推送ID失败:", err);
    },
  });
}
const setInit = async (para) => {
  try {
    const res = await USER_INIT(para);
    useUser.setInitId(res.data.auth_id);
    // #ifdef APP-PLUS
    useSystem.setAppinfo(res.data.appinfo);
    // #endif
    if (res.data.token) {
      useUser.setUserInfo(res.data);
    }
  } catch (error) {}
};

// 清除角标的方法
function clearBadge() {
  // #ifdef APP-PLUS
  useMessage.getTotalUnreadCount();
  // #endif
}

uni.$on("$onMessage", ({ event, channel, data }) => {
  // console.log('event, channel, data', event, channel, data)
  useScoket.checkStatus();
  if (
    channel &&
    channel.includes("private-call") &&
    data.extend.message_event == "new_message"
  ) {
    const msgInfo = JSON.parse(data.message);
    if (msgInfo.send == 1) return;
    useMessage.updateMessageList(
      channel,
      {
        ...msgInfo,
        msg: JSON.parse(msgInfo.msg),
      },
      "push"
    );
    useMessage.updateGlobalMapLasttime(
      `${msgInfo.type}Channel`,
      msgInfo.indate
    );
    useMessage.updateUnreadCount(channel);
  } else if (
    channel &&
    channel.includes("private-user") &&
    data.extend.message_event == "new_message"
  ) {
    const msgInfo = JSON.parse(data.message);
    // #ifdef APP-PLUS
    // const cont = JSON.parse(msgInfo.lastmsg || '{}')
    // uni.createPushMessage({
    //   content: cont.text || '测试数据', success: res => {
    //     console.log('通知栏调用成功', res);
    //   }, fail: err => {
    //     console.error('通知栏调用失败', err);
    //   }
    // })
    // #endif
    useMessage.updateGlobalMapUnreadCount(`${msgInfo.type}Channel`);
  }
});

const onPush = () => {
  uni.onPushMessage((res) => {
    const data = res.data;
    console.log(res);
    if (res.type === "receive") {
      // 推送到通知栏
      uni.createPushMessage({
        title: data?.title,
        content: data?.content || "收到新消息",
        payload: data?.payload,
        success: (r) => {
          console.log("推送成功", r);
        },
        fail: (err) => {
          console.error("推送失败", err);
        },
      });
    }
    if (res.type == "click") {
      console.log("通知栏", data);
    }
  });
};

// #ifdef APP-PLUS
onPush();
// #endif
</script>

<style>
@import url("./static/fonts.css");
@import url("static/css/main.css");

/* @font-face {
  font-family: 'MyCustomFont';
  src: url('../static/fonts/SourceHanSansCN-VF.otf') format('opentype');
  font-weight: normal;
  font-style: normal;
} */

@font-face {
  font-family: "HarmonyOS_Sans";
  src: url("../static/fonts/HarmonyOS_Sans_SC.ttf") format("truetype");
  font-weight: normal;
  font-style: normal;
}

body {
  /* font-family: 'MyCustomFont'; */
}
</style>
<style lang="scss">
@import "@/uni_modules/uview-plus/index.scss";

.container {
  padding: 15px;
}

button {
  margin-bottom: 15px;
}
</style>
