<template>
  <div class="env-run">
    <loading v-if="loading"></loading>
    <div
      class="main"
      id="mainx"
      :style="mainContainerStyle"
      v-if="selectedPage && selectedPage.components"
    >
      <component
        v-for="comp in selectedPage.components"
        :id="comp.id"
        :key="comp.id"
        :is="comp.componentViewName + comp.baseCompId"
        :comp="comp"
        :cfg="cfg"
        :selectedPage="selectedPage"
        @clickSheet="onClickSheet"
        @changeData="changeData"
      ></component>
    </div>

    <!-- <button @click="scanQR()">点击扫码</button> -->
    <!-- <div class='copy-right'>
          <img src="http://image.supercarrier8.com/logo/super8/logo_v3.png" alt="">
          <span>由超级8提供技术支持</span>
    </div>-->
  </div>
</template>
<script>
import ErrorCode from "./assets/js/errorCode.js";
import Vue from "vue";
// import $ from "jquery";
import "mint-ui/lib/style.css";
import _stringResource from "./assets/js/stringResource.js";
import _h5portal from "./assets/js/h5portal/h5portal";
import _apiHelper from "./assets/js/apiHelper.js";
import { sign } from "./assets/js/cryptoHelper.js";
import _gis from "./assets/js/location-common.js";
import eventBus from "./assets/js/eventBus.js";
import ut from "./assets/js/utils.js";
import { Toast } from "mint-ui";
import wx from "weixin-js-sdk";
import loading from "./loading";
// import errorCode from "./assets/js/errorCode.js";
import { Indicator } from "mint-ui";

export default {
  name: "RunEnv",
  data: function() {
    return {
      cfg: {},
      selectedPage: undefined,
      homePage: {},
      loading: false,
      history: [], // 页面浏览历史
      // 以下的错误码跳转错误页
      errCode: [
        "200101",
        "200102",
        "200201",
        "200202",
        "200203",
        "200204",
        "200205",
        "200206",
        "300101"
        // "300102"
      ],
      browserBack: undefined, // 是否正在执行浏览器返回事件
      jsSDKReady: false, // 微信sdk是否授权成功
      intercept: true, // url是否需要截取
      mainContainerStyle: {}, // 主dom容器的样式
      mainContainerStyle_paddingBottom: 0
    };
  },
  components: { loading },
  methods: {
    // 检查当前设备是否合法
    // checkEntryType(cb) {
    //   let that = this;
    //   // this.cfg.entryType=0;

    //   if (this.cfg.entryType === this.sup8._def.entryType.wechat.code) {
    //     that.entryType = this.sup8._def.entryType.wechat.code; // 需要微信打开
    //     if (this.sup8.$utils.isWechat()) {
    //       this.sup8.context.needScan = true; //

    //       this.initWxSDK(function() {
    //         // 判断是不是从公众号菜单进入系统
    //         if (that.sup8.urlparams.channel == "2") {
    //           cb();
    //         } else {
    //           // needSubscibe==1,如果没有关注公众号，直接跳转公众号关注页面
    //           if (that.cfg.needSubscibe == 1) {
    //             that.gotoWxSubscribePage();
    //           } else {
    //             cb();
    //           }
    //         }
    //         // cb();
    //       });
    //     } else {
    //       this.gotoErrorPage(ErrorCode.entryTypeErro1);
    //     }
    //   } else {
    //     cb();
    //   }
    // },

    // initWxSDK(cb) {
    //   let that = this;
    //   const eNo = that.sup8.context.eno;
    //   _apiHelper.getWxJsSdkConfig(
    //     eNo,
    //     location.href.split("#")[0],
    //     function(res) {
    //       if (!res || !res.flag || !res.data) {
    //         console.log(
    //           "ErrorCode.jsSdkConfigError",
    //           ErrorCode.jsSdkConfigError
    //         );
    //         that.gotoErrorPage(ErrorCode.jsSdkConfigError);
    //         return false;
    //       }
    //       res = res.data;
    //       that.sup8.context.wx_user = res;

    //       // wx.config({
    //       // 	debug: false, // 开启调试模式,
    //       // 	appId: res.appId, // 必填，企业号的唯一标识，此处填写企业号corpid
    //       // 	timestamp: res.timestamp, // 必填，生成签名的时间戳
    //       // 	nonceStr: res.nonceStr, // 必填，生成签名的随机串
    //       // 	signature: res.signature, // 必填，签名，见附录1
    //       // 	jsApiList: ["scanQRCode"] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
    //       // });
    //       cb();
    //       return true;
    //     },
    //     function() {
    //       that.gotoErrorPage(ErrorCode.jsSdkConfigError);
    //       return false;
    //     }
    //   );
    // },
    // 订阅事件
    subscribe() {
      var that = this;
      eventBus.$on(eventBus.eventKey.updataMainContainerStyle, function(data) {
        if (data.paddingBottom) {
          that.mainContainerStyle_paddingBottom += data.paddingBottom;
          that.mainContainerStyle.paddingBottom =
            that.mainContainerStyle_paddingBottom + "px";
        }

        that.$forceUpdate();
      });

      eventBus.$on(eventBus.eventKey.hasNavList, function(data) {
        if (data.paddingBottom) {
          that.mainContainerStyle_paddingBottom += data.paddingBottom;
          that.mainContainerStyle.paddingBottom =
            that.mainContainerStyle_paddingBottom + "px";
        }

        that.$forceUpdate();
      });
    },
    initWxJsSdk() {
      let that = this;
      Indicator.open();
      if (!that.sup8.$utils.isWechat()) {
        that.jsSDKReady = false;
        that.getGPS();
        return;
      }
      _apiHelper.getWxJsSdkConfig(
        that.sup8.context.eno,
        location.href.split("#")[0],
        1,
        function(res) {
          console.log(112);
          if (res.flag) {
            res = res.data;
            that.sup8.context.wx_user = res;
            wx.config({
              debug: false, // 开启调试模式,
              appId: res.appId, // 必填，企业号的唯一标识，此处填写企业号corpid
              timestamp: res.timestamp, // 必填，生成签名的时间戳
              nonceStr: res.nonceStr, // 必填，生成签名的随机串
              signature: res.signature, // 必填，签名，见附录1
              jsApiList: [
                "scanQRCode",
                "getLocation",
                "chooseImage",
                "previewImage",
                "uploadImage",
                "downloadImage",
                "getLocalImgData"
              ] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
            });
            wx.ready(function() {
              console.log(113);
              that.jsSDKReady = true;
              that.getGPS();
            });
            wx.error(function(e) {
              console.log(114);
              //   that.jsSDKReady = false;
              //   that.getGPS();
            });
            // that.getGPS();
          } else {
            that.jsSDKReady = false;
            that.getGPS();
          }
        },
        function(e) {
          that.jsSDKReady = false;
          that.getGPS();
        }
      );
    },

    onClickSheet: function(op) {
      this.selectedPage = op;
    },

    changeData: function(opt) {
      this._data = _.assign(this._data, opt);
      this.$forceUpdate();
    },

    changeSelectedPage(pageType) {
      debugger;
      let that = this;
      let newPage = _.find(that.cfg.pages, {
        type: pageType
      });

      if (newPage) {
        that.selectedPage = newPage;
        that.$forceUpdate();
      }
    },

    // 跳转到错误页
    gotoErrorPage(error, errorMsg) {
      this.sup8.gotoError = true;
      this.sup8.msg = errorMsg;
      this.sup8.error = error;
      this.$router.push("/error");
    },

    // 跳转到微信关注页面
    gotoWxSubscribePage() {
      let that = this;
      if (this.sup8.context.follow) {
        _.forEach(that.cfg.pages, function(page, i) {
          _.forEach(page.components, function(com, k) {
            com.props = that.convertCompProps(com.props);
          });
        });
        this.changeSelectedPage(this.sup8.context.follow);
      } else {
        //this.$router.push("/wxsubscribe");
        window.location.href = "/wxsubscribe";
      }
    },
    // // 缓存数据
    // cachingData(res) {
    //   let that = this;
    //   sessionStorage.setItem("codeInfo", JSON.stringify(res));
    //   var url = location.href.split("?")[0];

    //   that.sup8.context.eno = "100344004624";
    //   location.href =
    //     that.sup8._appConf.apiUrl.getWxUserInfo +
    //     `?enterpriseNo=${that.sup8.context.eno}&redirectUrl=${url}`;
    // },
    // // 缓存读取微信用户信息后数据返回
    // dataReturn() {
    //   let that = this;
    //   let res = JSON.parse(sessionStorage.getItem("codeInfo"));
    //   that.sup8.codeInfo = res.data.codeBase || {};
    //   that.sup8.$utils.updateContext(that.sup8.context, that.sup8.codeInfo);
    //   //记录解码时的错误码，查防伪的时候会用到
    //   that.sup8.context.decodestatus = res.errorCode || "";
    //   // 判断错误码，是否需要跳转错误页
    //   if (that.errCode.includes(that.sup8.context.decodestatus)) {
    //     that.getReply();
    //     return;
    //   }
    //   var resData = res.data.config;
    //   if (!resData || !res.flag) {
    //     that.gotoErrorPage(ErrorCode.fail, res.msg);
    //     return;
    //   }
    //   that.cfg = resData;
    //   that.loading = false;
    //   let NavigatingData = {
    //     NavigatingData: resData.id,
    //     PortalType: 0
    //   };
    //   that.sup8.portalInfo = NavigatingData;
    //   that.sup8.$utils.updateContext(that.sup8.context, {
    //     tid: NavigatingData.NavigatingData
    //   });

    //   that.sup8._baseComponentList = res.data.baseComponent;
    //   that.$parent.registComponent(that.sup8._baseComponentList);
    //   that.goPage();
    // },

    // 获取数码信息
    async getCodeInfo() {
      let that = this;
      // 1:服务号；2：订阅号,0：未知
      let WxType = "0";
      let WechatConfig = await this.getWechatConfigInfoByEnterpriseNo();
      if (WechatConfig.flag && !!WechatConfig.data) {
        that.sup8.WechatConfig = WechatConfig.data;
        WxType = WechatConfig.data.WxType;

        sessionStorage.WechatConfig = JSON.stringify(WechatConfig.data);
      } else {
        WxType = "0";
      }

      console.log(WxType);
      let qr_code = location.href;
      if (["3", "4"].includes(this.sup8.$utils.ssg("channel"))) {
        qr_code = "";
      } else {
        if (this.intercept && qr_code.includes("&")) {
          qr_code = qr_code.split("&")[0];
        }
      }
      if (this.sup8.$utils.ssg("from_businesstype")) {
        this.sup8.context.businesstype = this.sup8.$utils.ssg(
          "from_businesstype"
        );
      }
      let businesstype = this.sup8.context.businesstype
        ? this.sup8.context.businesstype
        : "";
      // 测试临时修改
      //   if(!!this.sup8.context.wxUser && this.sup8.context.eno=="100800022421"){
      // 	  this.sup8.context.wxUser.openid = "oR-mp07Ee_FLJoARQfKlNBXxGpfg";
      //   }
      _apiHelper.getUrlCodeInfo(
        qr_code,
        that.sup8.context.eno,
        that.sup8.context.externalurl,
        businesstype,
        function(res) {
          // 记录解码时的错误码，查防伪的时候会用到
          that.sup8.context.decodestatus = res.errorCode || "";
          if (!res.data.config.id) {
            that.loading = false;
            that.gotoErrorPage("", "当前没有可参与活动");
            return;
          }
          // 判断错误码，是否需要跳转错误页
          if (that.errCode.includes(that.sup8.context.decodestatus)) {
            that.getReply();
            return;
          }
          let resData = res.data.config;
          let compList = [];
          if (!resData || !res.flag) {
            that.gotoErrorPage(ErrorCode.fail, res.msg);
            return;
          }
          resData.pages.forEach(v => {
            if (v.type == "3-2") {
              // 活动注册页
              that.sup8.context.activityRegister = v.type;
            }
            if (v.type == "10-2") {
              // 微信关注页
              that.sup8.context.follow = v.type;
            }
            compList = [...compList, ...v.components];
          });

          that.sup8._baseComponentList = res.data.baseComponent;
          // 获取组件列表，注册组件
          let componentList = that.$parent.filterComponentList(
            resData.pages,
            // res.data.baseComponent
            compList
          );
          //   res.data.baseComponent = that.sup8._baseComponentList = componentList;

          that.cfg = resData;
          if (that.sup8.$utils.ssg("from_subscibe")) {
            that.cfg.needSubscibe = that.sup8.$utils.ssg("from_subscibe");
          }
          // that.cachingData(res);

          // return;
          // that.sup8.codeInfo = res.data.codeBase || {};
          // that.sup8.$utils.updateContext(that.sup8.context, that.sup8.codeInfo);
          // 隐藏loading
          // that.$emit("changeLoading", false);

          let NavigatingData = {
            NavigatingData: resData.id,
            PortalType: 0
          };
          that.sup8.portalInfo = NavigatingData;
          that.sup8.$utils.updateContext(that.sup8.context, {
            tid: NavigatingData.NavigatingData
          });
          // that.afterGetPortal(NavigatingData);
          // if (resData.portType == that.sup8._def.portalType.third.code) {
          //     setTimeout(() => {
          //         that.thirdLink(resData.url);
          //     }, 200);
          //     return false;
          // }

          that.$parent.registComponent(componentList);

          if (that.cfg.entryType === that.sup8._def.entryType.wechat.code) {
            if (that.sup8.$utils.isWechat()) {
              if (WxType == "1") {
                // if (that.sup8.urlparams.channel != "2" && that.cfg.needSubscibe == 1) {
                let wxUserInfo = that.sup8.$utils.ssg("wxUser")
                  ? that.sup8.$utils.ssg("wxUser")
                  : { subscribe: "" };
                if (
                  that.sup8.urlparams.channel != "2" &&
                  wxUserInfo.subscribe != 1
                ) {
                  that.loading = false;
                  that.gotoWxSubscribePage();
                  return;
                }
              } else {
                if (
                  that.sup8.urlparams.channel != "2" &&
                  that.cfg.needSubscibe == 1
                ) {
                  that.loading = false;
                  that.gotoWxSubscribePage();
                  return;
                }
              }
            } else {
              that.loading = false;
              that.gotoErrorPage(ErrorCode.entryTypeErro1);
              return;
            }
          }

          // that.checkEntryType(that.goPage);
          that.goPage();
          that.loading = false;
        },
        function(e) {
          //   console.log(e);
        }
      );
    },
    // 第三方跳转
    thirdLink(url) {
      let that = this;
      let code = that.sup8.context.code;
      let timestamp = new Date().getTime();
      let _sign = sign("super8", {
        code,
        timestamp
      });
      url = url + "&timestamp=" + timestamp + "&sign=" + _sign;
      // console.log(url);
      location.href = url;
      // if (that.sup8.context.channel) {
      //     let frominfo = that.sup8.context.channel;
      //     url = url + "&frominfo=" + frominfo;
      //     location.href = url;
      // } else {
      //     that.getIP(url);
      // }
    },
    // 利用搜狐获取ip
    getIP(url) {
      $.ajax({
        url: "http://pv.sohu.com/cityjson?ie=utf-8",
        dataType: "script",
        success: function(res) {
          location.href = url + "&frominfo=" + window.returnCitySN.cip;
        },
        error: function() {
          location.href = url + "&frominfo=";
        }
      });
    },
    // 页面跳转
    goPage() {
      let that = this;
      _.forEach(that.cfg.pages, function(page, i) {
        _.forEach(page.components, function(com, k) {
          com.props = that.convertCompProps(com.props);
          that.mergeCompProps(com);
        });
      });
      // 地址中是不是指定打开哪个页面
      if (that.sup8.urlparams.pageid && that.sup8.urlparams.pageid.length > 0) {
        that.selectedPage = _.find(that.cfg.pages, {
          id: that.sup8.urlparams.pageid
        });
      } else if (
        that.sup8.urlparams.ptype &&
        that.sup8.urlparams.ptype.length > 0
      ) {
        that.selectedPage = _.find(that.cfg.pages, {
          type: that.sup8.urlparams.ptype
        });
      } else {
        that.selectedPage = _.find(that.cfg.pages, {
          isHome: true
        });
        if (!that.selectedPage) {
          that.selectedPage = that.cfg.pages[0];
        }
      }
    },

    // 模板处理
    afterGetPortal(portalInfo) {
      let that = this;
      if (!portalInfo.NavigatingData) {
        that.sup8.gotoError = true;
        that.sup8.msg = res.msg;
      }

      that.sup8.portalInfo = portalInfo;
      if (portalInfo) {
        switch (portalInfo.PortalType) {
          // 第三方的要跳出去
          case that.sup8._def.portalType.third.code:
            window.open(portalInfo.NavigatingData, "_parent");
            break;
          default:
            that.sup8.$utils.updateContext(that.sup8.context, {
              tid: portalInfo.NavigatingData
            });
            break;
        }
      } else {
        that.sup8.gotoError = true;
        that.sup8.msg = _stringResource.notFountTemplate;
        that.$router.push("/error");
        return;
      }
      // $("#appx").css("display", "none");
      if (that.sup8.gotoError) {
        that.$router.push("/error");
      }
    },
    /**
     * 获取防伪答复
     * @param {String} eNo 企业编号
     * @param {String} rType 答复类型
     * @param {String} cType 通道类型
     * @param {String} SkuLogisticCode 物流码
     * @param {Function} cbSuccess 成功回调
     * @param {Function} cbError 错误回调
     */
    getReply() {
      let that = this;
      _apiHelper.getReply(
        that.sup8.context.eno,
        that.sup8.context.decodestatus,
        "X",
        that.sup8.context.code,
        function(res) {
          if (res.flag && res.data !== undefined) {
            that.sup8.msg = res.data;
            that.$router.push("/error");
          } else {
            that.sup8.msg = "查询出现错误";
            that.$router.push("/error");
          }
        },
        function(res) {
          that.sup8.msg = "查询出现错误";
          that.$router.push("/error");
        }
      );
    },
    getGeo(map) {
      let that = this;
      // 如果已经有定位信息，不再次定位
      let gis = new _gis();
      //   if (!sessionStorage.getItem("gps")) {
      if (map == "bmap") {
        //   this.baiduGPS();
        gis.getGeo(function(res) {
          that.sup8.UA.geo = res;
          let channel = res.latitude + "," + res.longitude;
          sessionStorage.setItem("gps", channel);
          that.sup8.context.channel = channel;
          that.sup8.context.geo = res;
          eventBus.publish("gpsDone", true);
        });
      } else if (
        that.sup8.$utils.isWechat() &&
        !that.sup8.$utils.isWechatdevtools()
      ) {
        console.log("微信定位..");
        console.time("tengxunmappp");
        wx.getLocation({
          type: "wgs84", // 默认为wgs84的gps坐标
          success: function(res) {
            console.log("微信定位：成功:", res);
            sessionStorage.wxLocation = JSON.stringify(res);
            var latitude = res.latitude; // 纬度
            var longitude = res.longitude; // 经度
            that.wgs84TransformBM(longitude, latitude);
          },
          cancel: function(e) {
            console.log("拒绝:" + JSON.stringify(e));
            gis.getGeo(function(res) {
              that.sup8.UA.geo = res;
              let channel = res.latitude + "," + res.longitude;
              sessionStorage.setItem("gps", channel);
              that.sup8.context.channel = channel;
              that.sup8.context.geo = res;
              eventBus.publish("gpsDone", true);
            });
          },
          fail: function(e) {
            console.log("失败:" + JSON.stringify(e));
            gis.getGeo(function(res) {
              that.sup8.UA.geo = res;
              let channel = res.latitude + "," + res.longitude;
              sessionStorage.setItem("gps", channel);
              that.sup8.context.channel = channel;
              that.sup8.context.geo = res;
              eventBus.publish("gpsDone", true);
            });
          }
        });
      } else {
        if (that.sup8._appConf.debug) {
          that.sup8.UA = {};
          var res = { latitude: "31.86694226", longitude: "117.28269909" };
          that.sup8.UA.geo = res;
          sessionStorage.gps = res.latitude + "," + res.longitude;
        } else {
          gis.getGeo(function(res) {
            that.sup8.UA.geo = res;
            let channel = res.latitude + "," + res.longitude;
            sessionStorage.setItem("gps", channel);
            that.sup8.context.channel = channel;
            that.sup8.context.geo = res;
            eventBus.publish("gpsDone", true);
          });
        }
      }
      //   }
    },
    // wgs84转百度地图坐标
    wgs84TransformBM(lng, lat) {
      var that = this;
      var ggPoint = new BMap.Point(lng, lat);
      var convertor = new BMap.Convertor();
      var pointArr = [];
      pointArr.push(ggPoint);
      convertor.translate(pointArr, 1, 5, data => {
        console.log(data, 597);
        if (data.status === 0) {
          $.ajax({
            url: `https://api.map.baidu.com/geocoder/v2/?ak=DAkHeza7GMvAuA5FL2p8GAZxC84WoMLh&location=${data.points[0].lat},${data.points[0].lng}&output=json&pois=1`,
            dataType: "jsonp",
            callback: "BMap._rd._cbk43398",
            success: function(res) {
              console.log(603);
              console.log(JSON.stringify(res));
              Indicator.close();
              let mapInfo = {
                latitude: data.points[0].lat,
                longitude: data.points[0].lng,
                map: "baidu",
                addressComponent: res.result.addressComponent
              };
              let channel = data.points[0].lat + "," + data.points[0].lng;
              sessionStorage.setItem("gps", channel);
              that.sup8.context.channel = channel;
              that.sup8.context.geo = mapInfo;
              that.sup8.UA.geo = mapInfo;
              eventBus.publish("gpsDone");
            },
            error: function(e) {
              Indicator.close();
              console.log("百度经坐标转地址:error", e);
              eventBus.publish("gpsDone");
            }
          });
        } else {
          console.log("百度经坐标转地址:error", e);
          Indicator.close();
          eventBus.publish("gpsDone");
        }
      });
    },
    // 获取入口信息
    getImportConfigByUrl(
      url,
      enterpriseno,
      code,
      productid,
      labelno,
      productionbatchid,
      productioncodebatchid,
      codesegmentbatchid
    ) {
      console.log(url);
      let that = this;
      if (url == undefined) {
        let qr_code = location.href;
        if (this.intercept && qr_code.includes("&")) {
          qr_code = qr_code.split("&")[0];
        }
        url = qr_code;
      }

      _apiHelper.getImportConfigByUrl(
        url,
        enterpriseno,
        code,
        productid,
        labelno,
        productionbatchid,
        productioncodebatchid,
        codesegmentbatchid,
        function(res) {
          if (res.flag && res.data.h5Template) {
            if (
              that.sup8.$utils.ssg("from_scan") == 1 &&
              res.data.codeBase.EnterpriseNo !=
                that.sup8.$utils.ssg("from_scanEno")
            ) {
              that.loading = false;
              that.gotoErrorPage(ErrorCode.codeENoNotMatch);
              return;
            }
            if (!res.data.h5Template.ExternalUrl) {
              that.sup8.msg = ErrorCode.notFoundTemplate.msg;
              that.$router.push("/error");
              return;
            }

            that.sup8.h5Template = res.data.h5Template;
            that.sup8.codeInfo = res.data.codeBase || {};
            that.sup8.$utils.updateContext(
              that.sup8.context,
              that.sup8.codeInfo
            );

            that.sup8.$utils.updateContext(
              that.sup8.context,
              res.data.h5Template
            );
            // 第三方跳转
            if (
              res.data.h5Template.PortalType ==
              that.sup8._def.portalType.third.code
            ) {
              that.thirdLink(res.data.h5Template.ExternalUrl);
              return;
            }
            if (that.sup8.$utils.ssg("loadingFirst") != 1) {
              that.loading = true;
              that.sup8.$utils.sss("loadingFirst", 1);
            }
            if (
              res.data.h5Template.MultiTargetPeople != null &&
              res.data.h5Template.MultiTargetPeople.length > 0
            ) {
              if (!that.sup8.context.wxUser) {
                that.sup8.$utils.sss("configByUrl", res);
                that.weixinAuthorization(res);
              } else {
                that.getUserMemberType();
              }
            } else if (
              ["1", "0"].includes(res.data.h5Template.WeChatAuthorized)
            ) {
              if (!that.sup8.context.wxUser) {
                that.sup8.$utils.sss("configByUrl", res);
                that.weixinAuthorization(res);
              } else {
                that.getUserMemberType();
              }
            } else {
              if (res.data.h5Template.IsGPS == 0) {
                that.sup8.context.channel = returnCitySN.cip;
                that.getCodeInfo();
              } else {
                that.decode();
              }
            }
          } else {
            if (that.errCode.includes(res.errorCode)) {
              that.sup8.context.decodestatus = res.errorCode;
              that.getReply();
            } else {
              that.sup8.msg = res.msg || "网络异常";
              that.$router.push("/error");
            }
          }
        },
        function(e) {
          that.sup8.msg = "网络异常";
          that.$router.push("/error");
        }
      );
    },
    // 调用微信授权
    async weixinAuthorization(res, cache) {
      console.log("1:企业公众号，2:中商公众号");
      // 1:企业公众号，2:中商公众号
      if (!this.sup8.$utils.isWechat()) {
        this.sup8.msg = "请使用微信扫码访问";
        this.$router.push("/error");
      }
      let wc = await this.getWeChatEnterpriseParam();
      let fun = wc.data == 1 ? "getWxUserInfo" : "getWxUserInfoByCCN";
      if (this.sup8.h5Template.WeChatAuthorized != 2) {
        // this.sup8.$utils.sss("configByUrl", res);
        if (!this.sup8.context.wxUser || !this.sup8.$utils.ssg("wxUser")) {
          if (res.data.h5Template.IsGPS === 0) {
            this.sup8.context.channel = returnCitySN.cip;
            this.$parent[fun](this.getCodeInfo);
          } else {
            if (cache) {
              this.$parent[fun](this.getUserMemberType);
            } else {
              this.$parent[fun](this.decode);
            }
          }
        }
      }
    },
    // 获取入口缓存信息
    getCaching() {
      let that = this;
      let res = this.sup8.$utils.ssg("configByUrl");
      sessionStorage.removeItem("configByUrl");
      console.log("今天星期三");
      if (res.flag && res.data.h5Template) {
        if (
          that.sup8.$utils.ssg("from_scan") == 1 &&
          res.data.codeBase.EnterpriseNo != that.sup8.$utils.ssg("from_scanEno")
        ) {
          that.gotoErrorPage(ErrorCode.codeENoNotMatch);
          return;
        }
        if (!res.data.h5Template.ExternalUrl) {
          that.sup8.msg = ErrorCode.notFoundTemplate.msg;
          that.$router.push("/error");
          return;
        }
        that.sup8.h5Template = res.data.h5Template;

        that.sup8.codeInfo = res.data.codeBase || {};
        that.sup8.$utils.updateContext(that.sup8.context, that.sup8.codeInfo);

        that.sup8.$utils.updateContext(that.sup8.context, res.data.h5Template);
        // 第三方跳转
        if (
          res.data.h5Template.PortalType == that.sup8._def.portalType.third.code
        ) {
          that.thirdLink(res.data.h5Template.ExternalUrl);
          return;
        }

        if (that.sup8.$utils.ssg("loadingFirst") != 1) {
          that.loading = true;
          that.sup8.$utils.sss("loadingFirst", 1);
        }
        if (
          res.data.h5Template.MultiTargetPeople != null &&
          res.data.h5Template.MultiTargetPeople.length > 0
        ) {
          that.weixinAuthorization(res, true);
        } else if (["1", "0"].includes(res.data.h5Template.WeChatAuthorized)) {
          that.weixinAuthorization(res, true);
        } else {
          if (res.data.h5Template.IsGPS == 0) {
            that.sup8.context.channel = returnCitySN.cip;
            that.getCodeInfo();
          } else {
            that.decode();
          }
        }
      } else {
        if (that.errCode.includes(res.errorCode)) {
          that.sup8.context.decodestatus = res.errorCode;
          that.getReply();
        } else {
          that.sup8.msg = res.msg || "网络异常";
          that.$router.push("/error");
        }
      }
    },
    getUserMemberType() {
      // console.log(this.sup8.context.wxUser.openid,814);
      _apiHelper.getUserMemberType(
        this.sup8.context.wxUser.openid,
        this.sup8.context.eno,
        res => {
          if (res.flag) {
            this.sup8.memberType = res.data;
            const mt = this.sup8.h5Template.MultiTargetPeople;
            const memberType = res.data.MemberType;
            let flag = true;
            let mtInfo = [];
            if (mt.length > 0) {
              for (let i = 0; i < mt.length; i++) {
                if (mt[i].TargetPeople == memberType) {
                  mtInfo.push(mt[i]);
                }
              }
              if (mtInfo.length >= 1) {
                mtInfo = _.sortBy(mtInfo, "BusinessType");
                this.sup8.$utils.updateContext(this.sup8.context, mtInfo[0]); // 筛选出来的
                this.sup8.h5Template = mtInfo[0];
                flag = false;
              }
            } else {
              if (this.sup8.h5Template.TargetPeople == memberType) {
                flag = false;
              }
            }
            if (flag) {
              this.loading = false;
              this.gotoErrorPage("", "当前没有可参与活动");
              return;
            }
            this.decode();
          } else {
            this.decode();
          }
        },
        e => {
          this.loading = false;
          this.gotoErrorPage("", "当前没有可参与活动");
        }
      );
    },
    // 判断使用哪个公众号
    getWeChatEnterpriseParam() {
      return new Promise((resolve, reject) => {
        _apiHelper.getWeChatEnterpriseParam(
          this.sup8.context.eno,
          res => {
            // 1:企业公众号，2:中商公众号
            resolve(res);
          },
          e => {
            reject(e);
          }
        );
      });
    },
    decode() {
      this.getCodeInfo();
      this.initWxJsSdk();
    },
    // 获取定位
    getGPS() {
      let that = this;
      // 如果是微信进入，获取定位权限，不限企业
      if (that.sup8.$utils.isWechat()) {
        if (that.jsSDKReady) {
          that.getGeo();
        } else {
          that.getGeo("bmap");
        }
        // let that = this;
        // const eNo = that.sup8.context.eno;

        // _apiHelper.getWxJsSdkConfig(
        //   eNo,
        //   location.href.split("#")[0],
        //   function(res) {
        //     if (!res || !res.flag || !res.data) {
        //       that.getGeo("bmap");
        //     } else {
        //       res = res.data;
        //       that.sup8.context.wx_user = res;

        //       wx.config({
        //         debug: false, // 开启调试模式,
        //         appId: res.appId, // 必填，企业号的唯一标识，此处填写企业号corpid
        //         timestamp: res.timestamp, // 必填，生成签名的时间戳
        //         nonceStr: res.nonceStr, // 必填，生成签名的随机串
        //         signature: res.signature, // 必填，签名，见附录1
        //         jsApiList: ["scanQRCode", "getLocation"] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        //       });
        //     }
        //   },
        //   function(e) {
        //     console.log(e);
        //     that.getGeo("bmap");
        //   }
        // );
        // wx.ready(function() {
        //   that.getGeo();
        // });
        // wx.error(function(e) {
        //   console.log("==:" + e);
        //   // that.getGeo();
        // });
      } else {
        // 获取定位信息,不是微信使用百度定位
        that.getGeo("bmap");
      }
    },
    geoFormWeixin() {
      this.getGeo();
    },
    geoFormBaidu() {
      this.getGeo("bmap");
    },
    // 获取公众号信息
    getWechatConfigInfoByEnterpriseNo() {
      return new Promise((resolve, reject) => {
        _apiHelper.getWechatConfigInfoByEnterpriseNo(
          this.sup8.context.eno,
          res => {
            resolve(res);
          },
          e => {
            reject(e);
          }
        );
      });
    }
  },
  watch: {
    selectedPage: function(n, o) {
      document.title = n.name; // this

      if (this.browserBack) {
        this.browserBack = undefined;
        this.history = _.dropRight(this.history);
        return;
      }

      n.historyIndex = this.history.length;

      this.history.push(n);
      var url = location.href;
      window.history.pushState(
        {
          title: document.title + n.id,
          url: url
        },
        document.title + n.id,
        url
      );
    }
  },
  beforeCreate: function() {
    let that = this; // 初始化、整理各种参数
    that.sup8.env = that.sup8._def.env.run;
  },
  created: function() {
    var that = this;
    console.log(this.sup8.urlparams);
    if (that.sup8.$utils.ssg("wxUser")) {
      that.sup8.context.wxUser = that.sup8.$utils.ssg("wxUser");
    }
    // if (this.sup8.urlparams.userInfo) {
    //   let data = JSON.parse(this.sup8.urlparams.userInfo);

    //   //测试代码///////////////////
    //   //data.ResponseData.subscribe = 0;
    //   ////////////////////

    //   if (data.ResponseData.subscribe != 1) {
    //     that.gotoWxSubscribePage();
    //   } else {
    //     this.dataReturn();
    //   }
    // } else
    // if(this.sup8.$utils.ssg("urlCode")){
    //     this.sup8.context.businesstype =this.sup8.$utils.ssg("from_businesstype");
    //     this.cfg.needSubscibe = this.sup8.$utils.ssg("from_subscibe");
    // }
    // enterpriseno,digit,productid,labelno,productionbatchid,productioncodebatchid,codesegmentbatchid,
    // http://testh5.sup8.yesno.com.cn:82/?channel=4&digit=12311241&eno=100695019827&timestamp=1574837883381&sign=af9ad1965b460841820bc68ed3a7818a
    if (["3", "4"].includes(this.sup8.urlparams.channel)) {
      // 劲头足模式：3
      // 黑荞模式：4
      // debugger
      let signData = this.sup8.urlparams;

      let appConfig = ut.ssg("appConfig");
      let _sign = signData.sign;
      let token =
        signData.channel == 3
          ? appConfig.jintouzu_token
          : appConfig.heiqiao_token;
      let digit = signData.digit; // 数码，原code
      let timestamp = signData.timestamp;
      // 判断签名是否有效
      if (this.sup8.urlparams.channel == 3) {
        if (!ut.checkCcnSign(_sign, token, digit, timestamp)) {
          this.gotoErrorPage("", "URL无效");
          return;
        }
      } else {
        delete signData.sign;
        if (!ut.checkSup8Sign(_sign, token, signData)) {
          this.gotoErrorPage("", "URL无效");
          return;
        }
      }
      ut.sss("channel", this.sup8.urlparams.channel);
      this.getImportConfigByUrl(
        "",
        this.sup8.urlparams.eno,
        this.sup8.urlparams.digit,
        this.sup8.urlparams.pid,
        this.sup8.urlparams.labelno,
        this.sup8.urlparams.batchId,
        this.sup8.urlparams.productioncodebatchid,
        this.sup8.urlparams.codesegmentbatchid
      );
    } else if (this.sup8.urlparams.scan) {
      // let url = location.href.split("&")[0];
      // this.sup8.$utils.sss("urlCode",url);
      this.sup8.$utils.sss("from_scanEno", this.sup8.urlparams.eno);
      this.sup8.$utils.sss("from_scan", this.sup8.urlparams.scan);
      this.sup8.$utils.sss("from_subscibe", this.sup8.urlparams.subscibe);
      this.sup8.$utils.sss(
        "from_businesstype",
        this.sup8.urlparams.businesstype
      );
      // this.sup8.context.businesstype = this.sup8.urlparams.businesstype;
      // this.cfg.needSubscibe = this.sup8.urlparams.subscibe;
      this.getImportConfigByUrl();
    } else if (
      this.sup8.urlparams.channel == "2" &&
      !!this.sup8.urlparams.eno
    ) {
      this.intercept = false;
      this.sup8.context.eno = this.sup8.urlparams.eno;
      this.loading = true;
      this.decode();
      //   this.getGPS();
    } else {
      if (this.sup8.$utils.ssg("configByUrl")) {
        this.getCaching();
      } else {
        this.getImportConfigByUrl();
      }
    }
    // 获取用户设备、地理信息
    that.sup8.UA = {
      ua: navigator.userAgent,
      geo: {}
    };

    // 监控浏览器返回事件
    "pushState" in window.history &&
      setTimeout(function() {
        window.addEventListener("popstate", function(e) {
          if (that.history.length > 1 && that.selectedPage.historyIndex > 0) {
            var tempPage = undefined;
            try {
              if (that.selectedPage.historyIndex) {
                tempPage = _.cloneDeep(
                  that.history[that.selectedPage.historyIndex - 1]
                );
              } else {
                tempPage = _.cloneDeep(
                  that.history[that.selectedPage.length - 2]
                );
              }

              tempPage.back = true; // 表示是按返回键返回的页面
              that.browserBack = true;
              that.selectedPage = tempPage;
            } catch (error) {
              //  alert("popstate error");
            }

            return false;
          } else {
            return true;
          }
        });
      }, 1000);
  },
  mounted() {
    this.subscribe();
  }
};
</script>
<style>
@import "./assets/css/index.css";
</style>
<style scoped>
body {
  margin: 0;
  background: #f8f8f8;
  font-family: "方正圆体" !important;
  font-weight: 100 !important;
}

#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  /* margin-top: 60px; */
}

.comp {
  position: relative;
  width: 100%;
}
</style>
