<template>
  <view class="login">
    <div class="title">
      <img :src="globalConfig" alt="" class="logo" style="width: 250rpx" />
      <span class="text">微信登录认证中...</span>
    </div>
    <u-toast ref="uToast"></u-toast>
  </view>
</template>

<script>
import { WeChatSSO } from "@/api/login.js";
import logo from "@/static/logo.png";
import localStorage from "@/utils/localStorage";
export default {
  data() {
    return {
      globalConfig: logo,
    };
  },
  onShow() {
    //页面通过微信服务器回调回来时会带上code,页面获取code后再去进行身份认证
    const currentUrl = document.location.toString();
    const obj = this.parseURLParams(currentUrl);
    //解析url中包含的code
    const code = obj.code;
    if (code == "" || code == null || code == undefined) {
      //重定向回当前页面
      var redirect = encodeURIComponent(
        "http://ufidahz.com.cn:9085/app/index.html#/pages/loginAuthen/authenWeChat"
      );
      var url =
        "https://open.weixin.qq.com/connect/oauth2/authorize" +
        "?appid=wwb46c3f5e6ffe3e2b" +
        "&redirect_uri=" +
        redirect +
        "&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
      window.location.href = url;
    } else {
      this.WXLogin(code);
    }
  },
  methods: {
    // 解析URL字符串
    parseURLParams(url) {
      const params = {};
      const paramStr = url.split("?")[1];
      if (paramStr) {
        const paramPairs = paramStr.split("&");
        paramPairs.forEach((pair) => {
          const [key, value] = pair.split("=");
          params[key] = decodeURIComponent(value);
        });
      }
      return params;
    },
    async WXLogin(code) {
      let params = {
        code: code,
      };
      let res = await WeChatSSO(params);
      if (res.code == 1) {
        localStorage.set("MIDDLEGROUND-TOKEN", res.data[0]);
        localStorage.set("MIDDLEGROUND-USERINFO", res.data[1]);
		this.$nextTick(()=>{
			uni.reLaunch({
			  url: "/pages/loginAuthen/selectCompany",
			});
		})
      } else if (res.code == "1005") {
        this.$refs.uToast.show({
          type: "warning",
          message: "您尚未进行登录认证，请先认证！",
        });
        setTimeout(() => {
          localStorage.set("MIDDLEGROUND-USERID", res.data[0]);
          uni.reLaunch({
            url: "/pages/loginAuthen/loginWeChat",
          });
        }, 1000);
      } else {
        localStorage.remove("MIDDLEGROUND-TOKEN");
        localStorage.remove("MIDDLEGROUND-USERINFO");
        localStorage.remove("MIDDLEGROUND-USERID");
      }
    },
  },
};
</script>

<style scoped>
.title {
  padding-top: 80rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.title .logo {
  vertical-align: middle;
}
.title .text {
  font-size: 17px;
  font-weight: 700;
  vertical-align: middle;
  padding: 24px;
  color: var(--text-color-light);
}
</style>
<style scoped>
page {
  background: #fff;
}
</style>