<template>
  <div class="env-run">
    <loading v-if="loading"></loading>
    <div class="main" id="mainx" v-if="selectedPage && selectedPage.components">
      <component
        v-for="comp in selectedPage.components"
        :key="comp.id"
        :is="comp.componentViewName + comp.baseCompId"
        :comp="comp"
        :cfg="cfg"
        :selectedPage="selectedPage"
        @changeData="changeData"
        keep-alive
      ></component>
    </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 { sign } from "./assets/js/cryptoHelper.js";
import _gis from "./assets/js/location-common.js";
import eventBus from "./assets/js/eventBus.js";
// import { Toast } from 'mint-ui';
import wx from "weixin-js-sdk";
import loading from "./loading";
import apiHelper from "./assets/js/apiHelper.js";

export default {
  name: "KeyEnv",
  data: function() {
    return {
      cfg: {},
      selectedPage: undefined,
      homePage: {},
      loading: false,
      TargetType: "",
      history: [], // 页面浏览历史
      // 以下的错误码跳转错误页
      errCode: [
        "200101",
        "200102",
        "200201",
        "200202",
        "200203",
        "200204",
        "200205",
        "200206",
        "300101",
        "300102"
      ],

      browserBack: undefined // 是否正在执行浏览器返回事件
    };
  },
  components: { loading },
  methods: {
    changeData: function(opt) {
      this._data = _.assign(this._data, opt);
      this.$forceUpdate();
    },

    changeSelectedPage(pageType) {
      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() {
      this.$router.push("/wxsubscribe");
    },
    // 页面跳转
    goPage() {
      let that = this;
      _.forEach(that.cfg.pages, function(page, i) {
        _.forEach(page.components, function(com, k) {
          com.props = that.convertCompProps(com.props);
        });
      });
      // 地址中是不是指定打开哪个页面
      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 (this.sup8.urlparams.targetreg) {
          if (this.sup8.urlparams.entranceid == "0") {
            that.TargetType = "C_Reg";
          } else {
            that.TargetType = "K_Reg";
          }
          that.selectedPage = that.cfg.pages.find(that.CheckParamKey);
        } else if (this.sup8.urlparams.targetlogin) {
          that.TargetType = "Key_Login";
          that.selectedPage = that.cfg.pages.find(that.CheckParamKey);
        }else if (this.sup8.urlparams.targethome) {
          that.TargetType = "Key_HPage";
          that.selectedPage = that.cfg.pages.find(that.CheckParamKey);
        } else if (this.sup8.urlparams.targetstore) {
          that.TargetType = "Key_AStore";
          that.selectedPage = that.cfg.pages.find(that.CheckParamKey);
        } else if (this.sup8.urlparams.targetselect) {
          that.TargetType = "K_Select";
          that.selectedPage = that.cfg.pages.find(that.CheckParamKey);
        } else {
          if (!that.selectedPage) {
            that.selectedPage = that.cfg.pages[0];
          }
        }
      }
    },
    CheckParamKey(arry) {
      var that = this;
      if (arry.type == that.TargetType) {
        return true;
      }
    },
    // 校验入口参数
    checkUrlParams() {
      if (!this.sup8.urlparams && !this.sup8.context) {
        this.gotoErrorPage(ErrorCode.shop_missParam);
        return;
      }

      if (!this.sup8.urlparams.eno && !this.sup8.context.eno) {
        this.gotoErrorPage(ErrorCode.shop_missParam_eno);
      }
    },

    loadConfig() {
      let that = this;
      // 获取企业的商城模板编号

      let eno = this.sup8.urlparams.eno || this.sup8.context.eno;
      let portalInfo = _h5portal.getPortal({
        EnterpriseNo: eno,
        businessType: "9",
        TargetPeople: that.sup8.context.entranceid
      });

      if (!portalInfo || !portalInfo.data || !portalInfo.data.NavigatingData) {
        this.gotoErrorPage(ErrorCode.shop_notFoundTemplate);
        return;
      }

      let tid = portalInfo.data.NavigatingData;

      apiHelper.getUrlCodeInfo(
        "",
        eno,
        tid,
        "9",
        function(res) {
          if (!res.flag || !res.data) {
            that.gotoErrorPage(ErrorCode.fail, res.msg);
            return;
          }

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

          that.sup8._baseComponentList = res.data.baseComponent;
          that.$parent.registComponent(componentList);

          that.cfg = res.data.config;
          that.goPage();
          that.loading = false;
        },
        function() {
          that.loading = false;
        }
      );
    },
    // 判断使用哪个公众号
    getWeChatEnterpriseParam() {
      return new Promise((resolve, reject) => {
        apiHelper.getWeChatEnterpriseParam(
          this.sup8.context.eno,
          res => {
            // 1:企业公众号，2:中商公众号
            resolve(res);
          },
          e => {
            reject(e);
          }
        );
      });
    },
    // 调用微信授权
    async weixinAuthorization(res, cache) {
      // 1:企业公众号，2:中商公众号
      let wc = await this.getWeChatEnterpriseParam();
      let fun = wc.data == 1 ? "getWxUserInfo" : "getWxUserInfoByCCN";
      this.$parent.getGeo(
        () => {
          if (this.sup8.$utils.isWechat()) {
            this.sup8.h5Template = { WeChatAuthorized: 1 };
            this.$parent[fun](() => {
              this.$parent.initWxJsSdk(this.sup8.context.eno);
              this.loadConfig();
            }, this.$parent.gotoErrorPage);
          } else {
            this.loadConfig();
          }
        },
        () => {
          this.$parent.gotoErrorPage();
        }
      );
    }
  },
  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;

      let step = {
        title: document.title + n.id,
        url: url
      };
      window.history.pushState(step, document.title + n.id, url);
      console.log("pushState", document.title);
    }
  },
  beforeCreate: function() {
    let that = this; // 初始化、整理各种参数
    that.sup8.env = that.sup8._def.env.run;
  },
  created: function() {
    var that = this;
    that.loading = true;
    // 校验参数
    this.checkUrlParams();
    this.weixinAuthorization();

    // 获取用户位置
    // this.$parent.getGeo(
    //   function() {
    //     if (that.sup8.$utils.isWechat()) {
    //       that.sup8.h5Template = { WeChatAuthorized: 1 };
    //       that.$parent.getWxUserInfoByCCN(
    //         function() {
    //           that.$parent.initWxJsSdk(that.sup8.context.eno);
    //           that.loadConfig();
    //         },

    //         that.$parent.gotoErrorPage
    //       );
    //     } else {
    //       that.loadConfig();
    //     }
    //   },
    //   function() {
    //     that.$parent.gotoErrorPage();
    //   }
    // );

    // 监控浏览器返回事件
    "pushState" in window.history &&
      setTimeout(function() {
        console.log(
          '"pushState" in window.history',
          "pushState" in window.history
        );
        //   window.history.pushState("forward", null, "#");
        // window.history.forward(1);
        // window.history.pushState(null, null, window.location.search);

        // window.onpopstate = function() {
        //   alert("onpopstate");
        // };

        window.addEventListener("popstate", function(e) {
          // alert("onpopstate");
          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() {
    var that = this;
  }
};
</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>
