<template>
  <div>
    <web-view v-if="withoutScene" :src="pageUrl" @message="getMessage" @error="handleError" @load="handleLoad"></web-view>
  </div>
</template>

<script>
let forUrlAddKey = require("mayi-front-tools/forUrlAddKey").default;
import spokesman from "@/api/spokesman.js";
import shop from "@/api/shop.js";
import indexApi from "@/api/index.js";
import { serialize, getQueryVariable, DFSImg } from "@/utils/index";
import login from "@/api/login";
export default {
  data() {
    return {
      code: '',
      shopId: this.$store.state.mixid,
      options: {},
      session_key: "",
      baseUrl: process.env.BASE_URL,
      link: this.baseUrl,
      page: "/",
      location_obj:encodeURIComponent(wx.getStorageSync("location")),
      params: "?mixid=" + this.shopId+`&native_test=1`,

      userInfo: {
        nickName: "mpvue",
        avatarUrl: "http://mpvue.com/assets/logo.png"
      },
      shareUrl: "",

      //分享
      shopConfig: null,
      spokesmanGroupId: "", // 代言人的集团id
      spokesmanShopId: "", // 代言人的门店id
      spokesmanRelId: "", //代言人的id
      userId : '',
      hasInvitationStatus: 0, // 邀请资格:0-不能够邀请下级,1-能够邀请下级
      newHref: "",
      shareShopName: "",
      shareLogoUrl: "",
      shareOrderSn: "",
      shareTid: "",
      newWindowHref : '',
      withoutScene: false,
      sharePageList: [
        "goods/",
        "receivingGift",
        "article/",
        "/personalCenter/spokesmanCenter"
      ] //分享白名单
    };
  },
  computed: {
    pageUrl() {
      if(this.location_obj){
        this.params += `&location_obj=${this.location_obj}`;
      }
      if(wx.getStorageSync("sessionid")){
        this.params +=`&sessionid=${wx.getStorageSync("sessionid")}`;
      }
      let pageUrl = forUrlAddKey(decodeURIComponent(this.link+this.page+this.params));
      // let pageUrl = this.link+this.page+this.params;
      return pageUrl;
    },
  },
  watch: {
    pageUrl(n,o) {
      //埋点未登录时进入文章
      // this.params+='&articleId=111'
      console.log(wx.getStorageSync("sessionid"),3333333,this.pageUrl)
      if(!wx.getStorageSync("sessionid")&&this.pageUrl.indexOf('articleId')!=-1) {
        // wx.setStorageSync('articleId',true)
        var vars = this.pageUrl.split("&");
        console.log(vars,2222)
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            console.log(pair,1111)
            if (pair[0] == 'articleId') {
              wx.setStorageSync(this.$store.state.mixid+'articleId',pair[1])
            }
        }
      }
      // 小程序登录绑定手机号后回调页面记录客流渠道记录数据。
      if (wx.getStorageSync('sessionid') && wx.getStorageSync('attractingCustomerChannelId') && this.pageUrl.indexOf('open_id') != -1) {
        console.log('绑定手机号后登陆回调页')
        let openId = this.pageUrl.split('open_id=')[1].split('&')[0]
        let unionId = null
        if (this.pageUrl.split('unionId=')[1]) {
          unionId = this.pageUrl.split('unionId=')[1].split('&')[0]
        }
        indexApi.addRecord(
          {
            attractingCustomersChannelId: wx.getStorageSync('attractingCustomerChannelId'),
            miniOpenId: openId,
            unionId: unionId,
            registerFlag: 1,
            newRegisterFlag: 0,
          }
        ).then(ele=>{
          if (ele.data.data) {
            //清空引客渠道id
            wx.setStorageSync('attractingCustomerChannelId','');
          }
        })
      }
    }
  },
  onLoad(options) {

    if(wx.getStorageSync("sessionid")) {
      //清空门店id
      wx.setStorageSync(this.$store.state.mixid+'storeId','')
      wx.setStorageSync(this.$store.state.mixid+'sellerId','')
    }
    this.options = options;
    console.log(this.options,'----------------index-----options')
    Object.assign(this.$data, this.$options.data());

    if(wx.getStorageSync("workBox")){
      this.params += `&workBox=${wx.getStorageSync("workBox")}`
    }
    let op=wx.getStorageSync("openid")
    if (op) {
      this.params += '&open_id='+wx.getStorageSync("openid");
      this.withoutScene = true;
    }else{
      //获取openId
      wx.login({
        success: res => {
          this.code = res.code;
          console.log(this.code,'-----------------------------110---code')
          login.get_open_id_by_code({ code: this.code}).then(res1 => {
              if (res1.data.code == 200) {
                  wx.setStorage({
                      key: "openid",
                      data: res1.data.data
                  });
              }
              this.params += '&open_id='+wx.getStorageSync("openid");
              this.withoutScene = true;
          })
        },
      })
    }
    // 移除重复参数
    if (options.params) {
      let params=decodeURIComponent(options.params)
      let location_obj=getQueryVariable(params, "location_obj")
      location_obj && (options.params=params.split('&location_obj='+location_obj).join(''))
    }
    //检测登录态
    this.checkLogin();
    this.options = options;
    if (options.share) {
      //来自分享
      this.link = decodeURIComponent(options.share);
      this.spokesmanGroupId =
        getQueryVariable(this.link, "spokesmanGroupId") || "";
      this.spokesmanShopId =
        getQueryVariable(this.link, "spokesmanShopId") || "";
      this.spokesmanRelId = getQueryVariable(this.link, "spokesmanRelId") || "";
      this.userId = getQueryVariable(this.link, "userId") || "";
      if (this.spokesmanGroupId != "") {
        //上级分销员信息
        this.$store.commit("setSpokesman", {
          spokesmanGroupId: this.spokesmanGroupId,
          spokesmanShopId: this.spokesmanShopId,
          spokesmanRelId: this.spokesmanRelId
        });
      }
      this.page = "";
      this.params = "";
    } else if (options.from && options.from == "h5login") {
      let params = JSON.parse(options.params);
      console.log(params.sessionid,'--------------h5login--params')
      //来自h5登录
      wx.setStorage({
        key: "sessionid",
        data: params.sessionid
      });
      this.page = decodeURIComponent(options.backpath);
      console.log(this.page,'----------------------h5login--page')
      options.params && (this.params += "&" + serialize(params));
    } else if (options.from && (options.from == "home" || options.from == "livedToIndex")) {
      //来自直播详情
      this.page = decodeURIComponent(options.backpath);
      if(this.page.includes("?")){
        this.params="&mixid=" + this.shopId+`&native_test=1&location_obj=${this.location_obj}`;
      }
      options.params && (this.params += "&" + serialize(decodeURIComponent(options.params)));
    } else if (options.from && options.from == "themeLink") {
      // 多主题link
      this.page = decodeURIComponent(options.backpath);
      this.params += "&" + decodeURIComponent(options.params);
    } else if(options.from && (options.from == "liveList" || options.from == "livedBackShop" || options.from == "livedToGoodsInfo" || options.from == "livedToOrderConfirm")){
      //从主播端跳到商品   //直播页back到商城   //从直播详情商品列表到商城商品详情 //从直播详情商品列表到商城确认订单
      this.page = decodeURIComponent(options.backpath);
      this.params += "&" + serialize(options.params);
    } else if (options.from && options.from == "login") {
      //来自小程序登录页面
      this.page = decodeURIComponent(options.backpath);
      this.params += "&" + decodeURIComponent(options.params);
    } else if (options.from && options.from == "logout") {
      //来自用户登出
      wx.removeStorage({
        key: "sessionid"
      });
      wx.removeStorage({
        key: "openid"
      });
    } else if (options.from && options.from == "address") {
      // 来自小程序地址页面
      this.link = decodeURIComponent(options.backpath);
      console.log("adress", options.backpath, this.link);
      this.page = "";
      this.params = "";
    } else if (options.from == "wxPay") {
      //来自支付页面
      this.page = options.backpath;
      this.params += "&" + serialize(options.params);
    } else if (options.scene) {
      console.log(options)
      console.log(222222)
      if(options.scene.indexOf('_') == -1){
        this.withoutScene = false;
        //新二维码扫码进入
        wx.nextTick(() => {
          indexApi.getShareSceneRecord(options.scene).then(res=>{
            this.withoutScene = true;
            if(res.data.code == '200'){
              this.page = res.data.data.pageUri;
              let paramsObj = JSON.parse(res.data.data.scene);
              wx.setStorageSync('attractingCustomerChannelId',paramsObj.attractingCustomerChannelId);
              wx.setStorageSync(this.$store.state.mixid+'storeId',paramsObj.storeId);
              wx.setStorageSync(this.$store.state.mixid+'sellerId',paramsObj.sellerId);
              console.log(res.data.data)
              wx.login({
                success: res => {
                  login.get_open_id_by_code({ code: res.code}).then(res1 => {
                    if (res1.data.code == 200) {
                      wx.setStorageSync({
                          key: "openid",
                          data: res1.data.data
                      });
                      console.log('判断是否登录过=登陆过直接调用..未登录过需要授权头像昵称信息。')
                      if (wx.getStorageSync('sessionid')) {
                        console.log('已登陆了')
                        indexApi.addRecord(
                          {
                            attractingCustomersChannelId: paramsObj.attractingCustomerChannelId,
                            miniOpenId: res1.data.data,
                            registerFlag: 1,
                            newRegisterFlag: 0,
                          }
                        ).then(ele=>{
                          if (ele.data.data) {
                            //清空引客渠道id
                            wx.setStorageSync('attractingCustomerChannelId','');
                          }
                        })
                      } else {
                        console.log('未登录过需要授权头像昵称信息。')

                        const url = `/pages/login/main?back=${encodeURIComponent(this.page)}&param=${
                          encodeURIComponent(JSON.stringify(paramsObj))
                        }`;

                        console.log(url)
                        wx.navigateTo({url});
                      }
                    }
                  })
                },
              })
              let params = '';
              for(let i in paramsObj){
                params += "&"+i+'='+paramsObj[i]
              }
              this.params += params
            }
          }).catch((err)=>{
            this.withoutScene = true;
          })
        });

      }else {
        //来自扫码
        // options 中的scene需要使用decodeURIComponent才能获取到生成二维码时传入的scene
        var scene = decodeURIComponent(options.scene); //参数二维码传递过来的参数
        let querys = scene.split("_");
        if (querys) {
          if (querys[0] == "pid") {
            //商品详情 pid_123
            this.page = `/goods/${querys[1]}`;
            this.params += this.paramsHander(querys,3)+`&discountMargin=${querys[querys.length-1]}`
            // if(querys.length > 3){
            //   if(querys[5]){
            //     this.params += `&spokesmanGroupId=${querys[2]}&spokesmanShopId=${querys[3]}&spokesmanRelId=${querys[4]}&userId=${querys[5]}`
            //   }else{
            //     this.params += `&spokesmanGroupId=${querys[2]}&spokesmanShopId=${querys[3]}&spokesmanRelId=${querys[4]}`
            //   }

            // }else if(querys.length == 3){
            //   this.params += `&userId=${querys[2]}`
            // }


          } else if (querys[0] == "activty") {
            //活动页面activty_turntable_123
            this.params += `&pageInfo=${scene}`;
          } else if (querys[0] == "spokesman") {
            //分销员 小程序码
            this.page = `/personalCenter/spokesmanCenter`;
            this.params += this.paramsHander(querys,2)
            // if(querys.length > 2){
            //   if(querys[4]){
            //     this.params += `&spokesmanGroupId=${querys[1]}&spokesmanShopId=${querys[2]}&spokesmanRelId=${querys[3]}&userId=${querys[4]}`
            //   }else{
            //     this.params += `&spokesmanGroupId=${querys[1]}&spokesmanShopId=${querys[2]}&spokesmanRelId=${querys[3]}`
            //   }

            // }else if(querys.length == 2){
            //   this.params += `&userId=${querys[1]}`
            // }

          }else if(querys[0] == "home"){
            this.page = `/`;
            this.params += this.paramsHander(querys,2)
            // if(querys.length > 2){
            //   if(querys[4]){
            //     this.params += `&spokesmanGroupId=${querys[1]}&spokesmanShopId=${querys[2]}&spokesmanRelId=${querys[3]}&userId=${querys[4]}`
            //   }else{
            //     this.params += `&spokesmanGroupId=${querys[1]}&spokesmanShopId=${querys[2]}&spokesmanRelId=${querys[3]}`
            //   }

            // }else if(querys.length == 2){
            //   this.params += `&userId=${querys[1]}`
            // }
          }else if(querys[0] == "coupon"){
            this.page = `/personalCenter/coupon/getCoupon`;
            this.params+=`&couponId=${querys[1]}`
          }else if(querys[0] == "a"){
            this.page = "/activty/receivingGift"
            this.params += `&orderId=${querys[1]}`
            this.params += this.paramsHander(querys,3)
            // if(querys.length > 3){
            //   if(querys[5]){
            //     this.params += `&orderSn=${querys[1]}&spokesmanGroupId=${querys[2]}&spokesmanShopId=${querys[3]}&spokesmanRelId=${querys[4]}&userId=${querys[5]}`
            //   }else{
            //     this.params += `&orderSn=${querys[1]}&spokesmanGroupId=${querys[2]}&spokesmanShopId=${querys[3]}&spokesmanRelId=${querys[4]}`
            //   }

            // }else if(querys.length == 3){
            //   this.params += `&orderSn=${querys[1]}&userId=${querys[2]}`
            // }
          }else if (querys[0] == 'redeemCode') {//兑换码
            this.page = `/personalCenter/CDkey/exchange`;
          }else if(querys[0] == 'card'){
            this.page = `/giftCards/linkReceive`;
            this.params+=`&id=${querys[1]}`
            this.params += this.paramsHander(querys,3)
          }else if(querys[0] == 'giftView'){
            this.page = `/giftCoupon/preview`;
            this.params+=`&id=${querys[1]}`
          }else if(querys[0] == 'form'){//问卷调查
            this.page = `/smartForm`;
            this.params+=`&formId=${querys[1]}`;
            this.params += this.paramsHander(querys,3)
          }
        }
        console.log(querys, "scene");
        console.log(this.page)
        console.log(this.params)
      }


      // var query = options.query.dentistId; // 参数二维码传递过来的场景参数
    }
    this.init();
  },
  onShow(){
  },
  methods: {
    init() {
      // 获取小程序开启的订阅消息配置
      shop.getWxMiniSubscribeMessageConfig().then(res => {
        if (res.data.code == 200) {
          const data = res.data.data;
          console.log("wx mini subscribe message data: ", data);
          if (data != null) {
            const subscribeMessageObj = {};
            for (var key in data) {
              if(data[key] && data[key].template_id) {
                subscribeMessageObj[key] = data[key].template_id;
              }
            }

            this.$store.commit("setSubscribeMessageObj", subscribeMessageObj);
          }
        }
      });
    },
    checkLogin() {
      let getOpenid = wx.getStorageSync("openid");
      let getSessionid = wx.getStorageSync("sessionid");

      console.log('244',getOpenid,getSessionid);
      if (getOpenid == "" || getSessionid == "") {
        // this.params += "&logOut=true";
      }
    },
    getLocationHandle() {
      wx.getLocation({
        type: "wgs84",
        success: res => {
          var latitude = res.latitude;
          var longitude = res.longitude;
          var speed = res.speed;
          var accuracy = res.accuracy;
          console.log("~~~~~~~~~1~~~~~~~", res);
        },
        fail: res => {
          console.log("++++++++++2++++++", res);
        }
      });
    },
    async getSpokesman() {
      await spokesman.getSpokesmanidByShare().then(res => {
        if (res.data.code == 200) {
          if (res.data.data.hasInvitationStatus == 1) {
            this.hasInvitationStatus = 1;
            this.spokesmanGroupId = res.data.data.groupId;
            this.spokesmanShopId = res.data.data.shopId;
            this.spokesmanRelId = res.data.data.spokesmanId;

            this.newHref = `&spokesmanGroupId=${
              this.spokesmanGroupId
            }&spokesmanShopId=${this.spokesmanShopId}&spokesmanRelId=${
              this.spokesmanRelId
            }`;
          }else{
            this.newHref="";
          }
          console.log(this.newHref, "this.newHrefthis.newHrefthis.newHref");
        }
      });
    },
    bindViewTap() {
      const url = "../logs/main";
      if (mpvuePlatform === "wx") {
        mpvue.switchTab({ url });
      } else {
        mpvue.navigateTo({ url });
      }
    },
    //右上角分享时触发
    getMessage(res) {
      let len = res.target.data.length - 1;
      console.log(res, "h5消息", res.target.data[len]);
      this.shareShopName = res.target.data[len].shareShopName || "";
      this.shareLogoUrl = DFSImg(res.target.data[len].shareLogoUrl, 500, 400);

      //分享内容中有订单信息为送礼活动
      this.shareOrderSn = res.target.data[len].orderSn;
      this.shareTid = res.target.data[len].shareTid;
      this.newWindowHref = res.target.data[len].shareImgUrl + '&verifyShare=1';// + '&fromVisitorOpenId=' + wx.getStorageSync("openid")
      console.log("分享信息:", this.shareLogoUrl, this.shareShopName,1111111,this.newWindowHref);
      //文章详情分享埋点
      if(this.newWindowHref.indexOf('articleId')!=-1) {
        var articleId = ''
        var vars = this.newWindowHref.split("&");
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            console.log(pair,2222)
            if (pair[0] == 'articleId') {
              articleId = pair[1];
            }
        }
        indexApi.forward({articleId: articleId,}).then(res=>{

        })
      }
    },
    //加载成功
    handleLoad(){
      console.log('网页加载成功');
    },
    handleError(data){
      wx.showLoading({
        title: "网页加载失败 请右上角刷新"
      });
      this.$mpAnalytics.recordError({
      data,
      extendsInfo: {
        mixid: this.$store.state.mixid || null
      }
    });
    },
    checkPageUrl(val) {
      for (let i = 0; i < this.sharePageList.length; i++) {
        if (val.indexOf(this.sharePageList[i]) != -1) {
          return true;
        }
      }
      return false;
    },
    //增加params参数
    paramsHander(querys,midNum){

      let params = ''
      if(querys.length > midNum){
        if(querys[midNum + 2]){
          params += `&spokesmanGroupId=${querys[midNum - 1]}&spokesmanShopId=${querys[midNum]}&spokesmanRelId=${querys[midNum+1]}&userId=${querys[midNum+2]}`
        }else{
          params += `&spokesmanGroupId=${querys[midNum - 1]}&spokesmanShopId=${querys[midNum]}&spokesmanRelId=${querys[midNum+1]}`
        }

      }else if(querys.length == midNum){
        params += `&userId=${querys[midNum - 1]}`
      }

      return params;
    },
    delParam(oldUrl,paramKey) {
      var url = oldUrl;    //页面url
      var urlParam = oldUrl.split("?")[1];   //页面参数
      var beforeUrl = url.substr(0, url.indexOf("?"));   //页面主地址(参数之前地址)
      var nextUrl = "";

      var arr = new Array();
      if (urlParam != "") {
        var urlParamArr = urlParam.split("&"); //将参数按照&符分成数组
        for (var i = 0; i < urlParamArr.length; i++) {
          var paramArr = urlParamArr[i].split("="); //将参数键,值拆开
          //如果键雨要删除的不一致,则加入到参数中
          if (paramArr[0] != paramKey) {
            arr.push(urlParamArr[i]);
          }
        }
      }
      if (arr.length > 0) {
        nextUrl = "?" + arr.join("&");
      }
      url = beforeUrl + nextUrl;
      return url;
    },
  },
  onUnload() {
    console.log("卸载----------------", this.options);
  },
  async onShareAppMessage(res) {
    await this.getSpokesman();
    let url = ''
    console.log(this.newWindowHref + 'this.newWindowHref')
    //分享路径
    if(this.newWindowHref){
      url = this.newWindowHref;
    }else{
      url = res.webViewUrl;
    }
    //分享页面去掉登录态
    if (url.indexOf("sessionid") > -1) {
      // url = url.split("?")[0] + "?mixid=" + this.shopId;
      url = this.delParam(this.newWindowHref,'sessionid')
      url = this.delParam(url,'open_id')
    }
    //分销员推广页面 默认分享分销员中心页面
    if (url.indexOf("/personalCenter/spokesmanCenter/mine/popularize") > -1) {
      url = `${this.baseUrl}/personalCenter/spokesmanCenter?mixid=${
        this.shopId
      }`;
    }

    console.log('shareUrl---------------' + url)
    //增加分销员信息
    if(this.hasInvitationStatus == 1 && url.indexOf('spokesmanGroupId')==-1){
      this.shareUrl = url+ this.newHref
    }else{
      this.shareUrl = url ;
    }


    console.log(this.shareUrl, "index12");
    console.log(`/pages/index/main?share=${encodeURIComponent(this.shareUrl)}`, '测试直播分享相关')
    return {
      title: this.shareShopName, // 默认是小程序的名称
      path: `/pages/index/main?share=${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() {
        // 转发结束之后的回调(转发成不成功都会执行)
      }
    };
  }
};
</script>

<style scoped>
.userinfo {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.userinfo-avatar {
  width: 128rpx;
  height: 128rpx;
  margin: 20rpx;
  border-radius: 50%;
}

.userinfo-nickname {
  color: #aaa;
}

.form-control {
  display: block;
  padding: 0 12px;
  margin-bottom: 5px;
  border: 1px solid #ccc;
}
.all {
  width: 7.5rem;
  height: 1rem;
  background-color: blue;
}
.all:after {
  display: block;
  content: "";
  clear: both;
}
.left {
  float: left;
  width: 3rem;
  height: 1rem;
  background-color: red;
}

.right {
  float: left;
  width: 4.5rem;
  height: 1rem;
  background-color: green;
}
</style>