<!-- /pages/webview/webview.vue -->
<template>
  <view>
    <web-view
      style="height: calc(100% - 30px); margin-top: 30px"
      :src="src"
      ref="webview"
    ></web-view>
    <view
      class="zai-title text-shadow"
      style="position: fixed; top: 5px; z-index: 3"
      >返回</view
    >
  </view>
</template>

<script>
import configService from "@/common/service/config.service.js";
import { ACCESS_TOKEN, USER_NAME, USER_INFO } from "@/common/util/constants";
import api from "@/api/api";
export default {
  data() {
    return {
      timer: "",
      src: "",
    };
  },
  methods: {
    onLoaded() {
      this.$tip.toast("onLoaded");
      // 在webview加载完成后,注入JavaScript代码
      this.$refs.webview.evalJs(`
	        (function() {
	          // 监听URL变化事件
	          window.addEventListener('hashchange', function() {
	            // 将URL变化通过postMessage传递给uniapp
	            window.postMessage(JSON.stringify({
	              type: 'urlChange',
	              url: window.location.href
	            }));
	          });
	
	          // 监听popstate事件(用于处理浏览器历史记录的变化)
	          window.addEventListener('popstate', function() {
	            window.postMessage(JSON.stringify({
	              type: 'urlChange',
	              url: window.location.href
	            }));
	          });
	
	          // 初始化时发送一次当前URL
	          window.postMessage(JSON.stringify({
	            type: 'initUrl',
	            url: window.location.href
	          }));
	        })();
	      `);

      // 监听来自webview的消息
      window.addEventListener("message", (event) => {
        const data = JSON.parse(event.data);
        if (data.type === "urlChange") {
          console.log("Webview URL changed:", data.url);
          // 在这里处理URL变化逻辑
        } else if (data.type === "initUrl") {
          console.log("Initial Webview URL:", data.url);
          // 处理初始化时的URL
        }
      });
    },
    startListening() {
		var than = this
      this.timer = setInterval(() => {
        var pages = getCurrentPages();
        var page = pages[pages.length - 1];
        var currentWebview = page.$getAppWebview();
        var urls = currentWebview.children()[0].getURL();
        console.log("=======当前地址======", urls);

        console.log(
          "WebView加载新页面------------------------------------------------------------------------" +
            this.src
        );
        if (urls.indexOf("ticket") != -1) {
          this.stopListening();
          var tourl = urls;
          tourl = tourl.substring(tourl.indexOf("ticket") + 7, tourl.length);
          var pos = tourl.indexOf("&");
          if (pos != -1) tourl = tourl.substring(0, pos);
        console.log("=======ticket======", tourl);
		
		uni.navigateTo({
		  url: "/pages/login/login?ticket="+tourl,
		});
		  // setTimeout(()=>{
    //       uni.navigateTo({
    //         url: "/pages/index/index",
    //       });
		  // },10000)
          // than.loginCas(tourl);
        }
      }, 200); // 间隔3秒检查一次
    },
    stopListening() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },

    loginCas(value) {
      var than = this;
	  
	  this.$tip.success(configService.apiUrl);
	  var ser = configService.apiUrl;
	  ser = tourl.replace(9999, 8092);
              this.$tip.success(ser);
      new Promise((resolve, reject) => {
        api
          .validateCasLogin("", "?ticket=" + value + "&service=" + ser)
          .then((response) => {
              than.$tip.success(response.message);
			  
            // console.log("response===>response", JSON.stringify(response));
            // if (response.data.code == 200) {
            // 	uni.setStorageSync(ACCESS_TOKEN, response.data.result.token);
            // } else {
            // }
            const result = response.data.result;
            const userInfo = result.userInfo;
            uni.setStorageSync(ACCESS_TOKEN, result.token);
            uni.setStorageSync(USER_INFO, userInfo);
            console.log("userInfo=" + userInfo);
            than.$store.commit("SET_TOKEN", result.token);
            console.log("result.token=" + result.token);
            than.$store.commit("SET_DICT", result.sysAllDictItems);
            than.$store.commit("SET_AVATAR", userInfo.avatar);
            than.$store.commit("SET_NAME", {
              username: userInfo.username,
              realname: userInfo.realname,
            });

              than.$tip.success("loginCas=");
            than.getPermissionList();
          })
          .catch((error) => {
            debugger;
            // console.log("catch===>response", error);
            // uni.navigateTo({
            //   url: "/pages/home/home",
            // });
          });
      });
    },

    //获取权限菜单
    getPermissionList() {
      var than = this;
              this.$tip.success("getPermissionList");
      console.log("getPermissionList=========================");
      new Promise((resolve, reject) => {
        api
          .getPermission({})
          .then((response) => {
            console.log(response, "权限菜单----------------");
            if (response.statusCode == 200) {
              let data = response.data.result.menuApp;
              let dataBtn = response.data.result.appauth;
              uni.setStorageSync("menuPermission", data);
              uni.setStorageSync("btnPermission", dataBtn);
              than.$tip.success("登录成功!");
              than.$tip.success("navigateTo="+pages/index/index);
              uni.navigateTo({
                url: "/pages/index/index",
              });
            } else {
              reject(response);
            }
          })
          .catch((error) => {
            console.log("catch===>response", response);
            reject(error);
          });
      });
    },
    saveClientId() {
      console.log("saveClientId=========================");
      var info = plus.push.getClientInfo();
      var cid = info.clientid;
      this.$http
        .get("/sys/user/saveClientId", {
          params: {
            clientId: cid,
          },
        })
        .then((res) => {
          console.log("res::saveClientId>", res);
          //获取权限菜单
          this.getPermissionList();
        });
    },
  },
  onShow() {
    this.startListening();
  },
  onHide() {
    this.stopListening();
  },
  watch: {},
  onUnload() {
    plus.runtime.quit();
  },
  onLoad(option) {
    // 获取传递过来的url参数
    let optionurl = option.url;
    console.log("onLoad  当前URL:", option.url);
    // setTimeout(()=>{

    // 	console.log('onLoad  setNavigationBarTitle', option.url);
    // uni.setNavigationBarTitle({
    //         title: '单点登录'
    //       });
    // },2000)
    console.log("option.url======" + option.url);
    this.src = decodeURIComponent(optionurl);
  },
};
</script>
<style scoped>
.zai-title {
  margin-top: 20upx;
  font-size: 58upx;
  color: #000000;
  text-align: center;
}
</style>