<!--
 第三方url
-->
<template>
  <div>
    <web-view
      :src="useLink"
      @message="getMessage"
      @error="handleError"
      @load="handleLoad"
    ></web-view>
  </div>
</template>

<script>
let forUrlAddKey = require("mayi-front-tools/forUrlAddKey").default;
let getUrlKey = require("mayi-front-tools/getUrlKey").default;
let getUrlAllKey = require("mayi-front-tools/getUrlAllKey").default;
let removeUrlKey = require("mayi-front-tools/removeUrlKey").default;
import { serialize, getQueryVariable, DFSImg } from "@/utils/index";
import login from "@/api/login";
import indexApi from "@/api/index";
function forUrlAddKey2(url, params) {
  let urlHost = url.slice(0, url.indexOf('?'));
  let urlParams = null;
  let url2 = url;
  let url3 = '';
  if(url2.includes('#/')){
      url2 = url.split('#/')[0];
      url3 = url.split('#/')[1];
  }
  urlParams = getUrlAllKey(url2)
  if (params && params.length) {
      params.forEach(res => {
          delete urlParams[res]
      })
  }
  let datas = [];
  for (let key in urlParams) {
      datas.push(key + '=' + urlParams[key])
  }
  if (datas.length) {
      return urlHost + '?' + datas.join('&') + (url3?`#/${url3}`:'')
  } else {
      return urlHost 
  }
}
const app = getApp();
const { log } = app;
export default {
  data() {
    return {
      link: "",
      useLink: "",
      shareShopName: "", //分享名称
      shareLogoUrl: "", //分享图片url
      newWindowHref: "", //分享页面url
      shopId: this.$store.state.mixid,
    };
  },
  async onLoad(options) {
    console.log(options,'--------------------options')
    log.info("--------------------options",options)
    this.link='';
    /**
     * scene=sso 第三方需要登录的页面
     * login=1   jwt需要登录(临时方案)
     */
    if (options.scene) {
      //扫码
      let data = await this.getParams(options.scene);
      if (data.sso) {
        let link = data.link;
        if(getUrlKey(decodeURIComponent(link), "getMixId") == '1') {//第三方跳转加mixid
          link = forUrlAddKey(decodeURIComponent(link),{mixid: this.$store.state.mixid})
        }
        if (!wx.getStorageSync("sessionid")) {
          wx.redirectTo({
            url: `../login/main?scene=sso&isEncode=1&back=${link}`,
          });
        } else {
          this.getSsoBcakUrl(decodeURIComponent(link).replace(/\/\?(.+?)#\//, '/?token=${token}&scene=sso&toAppid=qOAhsauSaagQlxYdGbJL#/'));
        }
      }
    } else if (options.link) {
      let link = options.link;
      if(getUrlKey(decodeURIComponent(link), "getMixId") == '1') {//第三方跳转加mixid
        link = forUrlAddKey(decodeURIComponent(link),{mixid: this.$store.state.mixid})
      }
      if(getUrlKey(decodeURIComponent(link), "scene") == 'dynamicForm') {
        link = decodeURIComponent(link)
      }
      console.log(link,'--------------------------57')
      if (getUrlKey(decodeURIComponent(link), "scene") == "sso") {
        if (!wx.getStorageSync("sessionid")) {
          // appraisalTwo:道可二级详情页面,之前进入道可项目所有页面都需登录,现在进入二级可不登录
          if (!link.includes("appraisalTwo")) {
            wx.redirectTo({
              url: `../login/main?scene=sso&isEncode=1&back=${link}`,
            });
          } else {
            this.setLink(decodeURIComponent(link));
          }
        } else {
          this.getSsoBcakUrl(decodeURIComponent(link).replace(/\/\?(.+?)#\//, '/?token=${token}&scene=sso&toAppid=qOAhsauSaagQlxYdGbJL#/'));
        }
      } else if (getUrlKey(decodeURIComponent(link), "login") != "1") {
        //判断是否需要带token
        if(decodeURIComponent(link).indexOf('setToken={token}') > -1) {
          if (wx.getStorageSync("sessionid")) {
            this.getSsoBcakUrl(decodeURIComponent(link).replace(/\/\?(.+?)#\//, '/?token=${token}&scene=sso&toAppid=qOAhsauSaagQlxYdGbJL#/'))
          } else {
            let url = `/pages/login/main?scene=sso&isEncode=1&back=${link}`;
            wx.navigateTo({
              url
            });
          }
        }else {
          this.setLink(decodeURIComponent(link));
        }
      } else {
        if (wx.getStorageSync("sessionid")) {
          this.setLink(
            forUrlAddKey(decodeURIComponent(link), {
              token: wx.getStorageSync("sessionid"),
              jwt: 1,
            })
          );
        } else {
          let url = "";
          if(link.includes('formDesignDetail')){
            url = `/pages/login/main?scene=sso&back=${encodeURIComponent(link)}`
          } else {
            url = `/pages/login/main?scene=sso&back=${link}`
          }
          wx.navigateTo({
            url,
          });
        }
      }
    }
  },
  onShow() {
    console.log(this.link,'------------154')
    setTimeout(() => {
      console.log(this.link,'------------154---2')
    }, 1000);
  },
  async onShareAppMessage(res) {
    console.log(res,'----------------------onShareAppMessage---------res')
    let url = "";
    console.log(this.newWindowHref + "this.newWindowHref");
    //分享路径
    if (this.newWindowHref) {
      url = this.newWindowHref;
    } else {
      url = res.webViewUrl;
    }
    // forUrlAddKey2(url, ["token"])
    console.log(url,'++++++++++++++++++',decodeURIComponent(url).replace(/\/\?(.+?)#\//, '/?token=${token}&scene=sso&toAppid=qOAhsauSaagQlxYdGbJL#/'),777777777)
    if(url.indexOf('setToken={token}') == -1) {
      url = decodeURIComponent(url).replace(/\/\?(.+?)#\//, '/?token=${token}&scene=sso&toAppid=qOAhsauSaagQlxYdGbJL#/');
    }
    console.log(url,'-------------164')
    //分享页面去掉登录态
    if (url.indexOf("sessionid") > -1) {
      if (url.includes('taokor')) {
        if (url.includes('&sessionid')) {
          url = url.split('&sessionid')[0];
        }
      } else {
        url = url.split("?")[0] + "?mixid=" + this.shopId;
      }
    }else if(url.indexOf('getMixId') > -1) {//分享链接需要带mixid
      url  = forUrlAddKey(url,{mixid: this.shopId})
    }
    this.shareUrl = url;
    console.log(this.shareUrl, "index12");
    console.log(
      `/pages/index/main?link=${encodeURIComponent(this.shareUrl)}`,
      "测试直播分享相关"
    );
    return {
      title: this.shareShopName, // 默认是小程序的名称
      path: `/pages/wxArticle/main?link=${encodeURIComponent(this.shareUrl)}`, // 默认是当前页面
      imageUrl: this.shareLogoUrl,
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == "shareAppMessage:ok") {
          console.log(res, "分享成功");
        }
      },
      fail: function () {
        // 转发失败之后的回调
        if (res.errMsg == "shareAppMessage:fail cancel") {
          // 用户取消转发
          console.log(res, "分享失败");
        } else if (res.errMsg == "shareAppMessage:fail") {
          // 转发失败,其中 detail message 为详细失败信息
        }
      },
      complete: function () {
        // 转发结束之后的回调(转发成不成功都会执行)
      },
    };
  },
  watch:{
    link() {
      console.log(this.link,this.link.includes('$%7Btoken%7D'),wx.getStorageSync("sessionid"),'-------watch----link')
      if (this.link.includes('$%7Btoken%7D') && wx.getStorageSync("sessionid")) {
        this.getSsoBcakUrl(decodeURIComponent(this.link));
      }
      if ((!this.link.includes('sessionid')) && wx.getStorageSync("sessionid")) {
        this.link +=`${this.link.includes('?') && !this.link.includes('#/') || (this.link.split('?').length - 1 > 1) ?'&':'?'}sessionid=${wx.getStorageSync("sessionid")}`
      }
      this.useLink = this.link;
      console.log(this.useLink,'--this.useLink')
    },
  },
  methods: {
    setLink(data) {
      this.link = data;
      console.log(this.useLink,89999999)
    },
    getSsoBcakUrl(link) {
      console.log(link,'--------------------------------------------163-----link')
      let op = {
        callbackUrl: link,
        email: "",
        fromAppid: "VsEOuDJqBnGNyXZJWCQS",
        // mobilephone: '15821335747',hgFTLLhgnBmeOyCkcbyv
        // toAppid: 'hgFTLLhgnBmeOyCkcbyv',
        toAppid: getUrlKey(link, "toAppid"), //道可
        wxAvatarUrl: this.$store.state.userInfo?this.$store.state.userInfo.avatarUrl:'',
      };
      login.getSsoBcakUrl(op).then((res) => {
        if (res.data.code == "200") {
          console.log('14888888',res)
          this.setLink(res.data.data);
          
        } else {
          wx.showToast({ title: res.data.msg, icon: "none" });
          if(res.data.msg == "登录人信息错误") {
            // 跳转登录页
            let backUrl = link.split("?")[0];
            let ossLink = link.split("?")[1] +'?'+ link.split("?")[2];
            let url = `/pages/login/main?scene=sso&isEncode=1&back=${backUrl}&ossLink=${encodeURIComponent(ossLink)}`;
            wx.navigateTo({
              url
            });
          }
        }
      });
    },
    getParams(options) {
      return new Promise((resolve, reject) => {
        indexApi
          .getShareSceneRecord(options)
          .then((res) => {
            if (res.data.code == "200") {
              let scene = JSON.parse(res.data.data.scene);
              resolve(scene);
            }
          })
          .catch((err) => {});
      });
    },
    //加载成功
    handleLoad() {
      console.log("网页加载成功");
    },
    //右上角分享时触发
    getMessage(res) {
      let len = res.target.data.length - 1;
      console.log(res, "h5消息", res.target.data[len]);
      this.shareShopName = res.target.data[len].shareShopName || "";
      if (res.target.data[len].shareLogoUrl) {
        this.shareLogoUrl = DFSImg(res.target.data[len].shareLogoUrl, 500, 400);
      }
      this.newWindowHref = res.target.data[len].shareImgUrl; // + '&fromVisitorOpenId=' + wx.getStorageSync("openid")
      console.log(
        "分享信息:",
        this.shareLogoUrl,
        this.shareShopName,
        1111111,
        res
      );
    },
    handleError(data) {
      wx.showLoading({
        title: "网页加载失败 请右上角刷新",
      });
    },
  },
};
</script>