<style lang="scss">
/* 注意要写在第一行，同时给style标签加入lang="scss"属性 */
@import "uview-plus/index.scss";
</style>
<script setup>
import { onLaunch, onShow, onHide } from "@dcloudio/uni-app";
import { userInfoModules } from "@/store/modules/userInfo";
import { loginApi } from "./api/login";
const userInfoModulesPinia = userInfoModules();
onLaunch(() => {
  console.log("App Launch!");
  // 获取平台及系统信息
  uni.getSystemInfo({
    success: function (res) {
      let uniPlatform = "";
      let osName = "";
      if (res.uniPlatform == "web") {
        uniPlatform = 1;
      } else if (res.uniPlatform == "mp-weixin") {
        uniPlatform = 2;
      } else if (res.uniPlatform == "mp-toutiao") {
        uniPlatform = 3;
      }
      if (res.osName == "windows") {
        osName = 1;
      } else if (res.osName == "ios") {
        osName = 2;
      } else if (res.osName == "android") {
        osName = 3;
      } else if (res.osName == "mac") {
        osName = 4;
      } else if (res.osName == "linux") {
        osName = 5;
      }

      userInfoModulesPinia.platForm = uniPlatform; // 平台
      userInfoModulesPinia.hostSystem = osName; // 系统
      console.log(res.uniPlatform, uniPlatform, "PlatForm");
      console.log(res.osName, osName, "System");
    },
  });
  // 微信登录授权
  uni.login({
    provider: "weixin", // 使用微信登录授权
    success: async (res) => {
      console.log(res);
      if (res.code) {
        console.log(res.code);
        try {
          uni.showLoading({
            title: "加载中...",
            mask: true,
          });
          const data = {
            appId: "wx75cf14e3a0d45821",
            code: res.code,
          };
          const res2 = await loginApi(data);
          userInfoModulesPinia.openId = res2.data.openId;
          userInfoModulesPinia.token = res2.token;
          console.log(userInfoModulesPinia.openId, "获取openid");
          uni.hideLoading();
          if (res2.token) {
            uni.redirectTo({
              url: "/pages/home/index",
            });
          } else {
            uni.redirectTo({
              url: "/pages/index/index",
            });
            uni.showToast({
              title: "登录失败，请重试",
              icon: "none",
            });
          }
        } catch (error) {
          // uni.redirectTo({
          //   url: "pages/index/index",
          // });
          uni.showToast({
            title: "登录失败，请重试",
            icon: "none",
          });
        }
      } else {
        // uni.redirectTo({
        //   url: "pages/index/index",
        // });
        uni.showToast({
          title: "登录失败，请重试",
          icon: "none",
        });
      }
    },
    fail: (err) => {
      // uni.redirectTo({
      //   url: "pages/index/index",
      // });
      uni.showToast({
        title: "登录失败，请重试",
        icon: "none",
      });
    },
  });
});
onShow(() => {
  console.log("App Show!");
});
onHide(() => {
  console.log("App Hide!");
});
</script>

<style>
/*每个页面公共css */
</style>
