<template>
  <div class="env-preview">
    <div
      class="main"
      :style="mainContainerStyle"
      v-show="!loading"
      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"
        @clickSheet="onClickSheet"
        @changeData="changeData"
        keep-alive
      ></component>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
// import $ from "jquery";
import vueLoading from "vue-loading-template";
import "mint-ui/lib/style.css";
import _h5portal from "./assets/js/h5portal/h5portal";
import _apiHelper from "./assets/js/apiHelper.js";
import eventBus from "./assets/js/eventBus.js";

export default {
  name: "PreviewEnv",

  data: function() {
    return {
      cfg: {},
      selectedPage: undefined,
      history: [],
      homePage: {},
      loading: true,
      browserBack: undefined, // 是否正在执行浏览器返回事件
      mainContainerStyle: {} // 主dom容器的样式
    };
  },
  methods: {
    // 订阅事件
    subscribe() {
      var that = this;
      eventBus.$on(eventBus.eventKey.updataMainContainerStyle, function(data) {
        that.mainContainerStyle = _.assign(that.mainContainerStyle, data);
        that.$forceUpdate();
      });
    },

    onClickSheet: function(op) {
      this.selectedPage = op;
    },
    registerComp: function(cb_success) {
      var that = this;

      _apiHelper.getBaseComponentList(
        that.sup8.portalInfo.NavigatingData,
        undefined,
        function(res) {
          if (res.flag && res.data) {
            that.sup8._baseComponentList = res.data;
            that.$parent.registComponent(that.sup8._baseComponentList);
            cb_success && cb_success();
          }
        },
        function(res) {
          console.log("error", res);
        }
      );
    },

    // 获取页面配置并加载
    load: function() {
      var that = this;
      _apiHelper.getConfig(
        that.sup8.portalInfo.NavigatingData,
        that.sup8.codeInfo.EnterpriseNo,
        that.sup8.urlparams.pageid || "",
        function(response) {
          var resData = response.data;
          if (!resData) {
            return;
          }
          that.cfg = resData;
          _.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 (!that.selectedPage) {
              that.selectedPage = that.cfg.pages[0];
            }
          }
          that.loading = false;
        },
        function(response) {
          console.log(response);
          that.loading = false;
        }
      );
    },
    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();
      }
    }
  },
  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.preview;

    /**
     * 进入这个页面有两种方式：
     * 1.扫描二维码、解码、查找模板、加载模板
     * 2.地址中直接指定模板、加载模板
     */
    // tid:模板编号
    var codeInfo = undefined;
    var portalInfo = undefined;
    if (that.sup8.urlparams.tid) {
      portalInfo = {
        NavigatingData: that.sup8.urlparams.tid
      };
      codeInfo = {
        Querycode: that.sup8.urlparams.code
        // EnterpriseNo:that.sup8.urlparams.eno
      };

      that.sup8.codeInfo = codeInfo;
      that.sup8.portalInfo = portalInfo;
    } else {
    }
  },
  created: function() {
    var that = this;
    // this.$emit("changeLoading", false);
    if (that.sup8.gotoError) {
      that.$router.push("/error");
    } else {
      that.registerComp(that.load);
      // that.loading = false;
    }

    // 监控浏览器返回事件
    "pushState" in window.history &&
      setTimeout(function() {
        window.addEventListener("popstate", function(e) {
          debugger;
          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() {
    console.log("mounted");
    var that = this;
    $("#appx").css("display", "none");
    this.subscribe();
    // 接收来自预览页面的预览数据
    window.addEventListener(
      "message",
      function(e) {
        if (e.data.type === "update") {
          console.log("h5plus:postmessage", e.data);

          var CompNavBar = undefined;
          if (that.selectedPage) {
            CompNavBar = _.find(that.selectedPage.components, {
              componentViewName: "CompNavBar"
            });
          }

          // 更新页面的组件，添加或更新一个组件

          if (
            (e.data.target === "page" && that.selectedPage) ||
            (e.data.target === "CompNavBar" && !CompNavBar && that.selectedPage)
          ) {
            that.selectedPage.components = _.reject(
              that.selectedPage.components,
              { tag: "preview" }
            );
            that.selectedPage.components = _.concat(
              that.selectedPage.components,
              e.data.data
            );
          } else {
            eventBus.publish(eventBus.eventKey.previewdataChange, e.data.data);
          }
        }
      },
      false
    );
  }
};
</script>

<style>
@import "./assets/css/index.css";
</style>

<style>
html {
  /* overflow: hidden; */
  /* overflow:-moz-scrollbars-none; */
}
</style>
