<template>
  <div id="box" class="home">
    <div :is="this.$store.state.tempName"></div>
  </div>
</template>
<script>
import {
  detMainProduct,
  channelGet,
  strategyGetNew,
  strategyGetID,
  newStrategy,
  strategytemplate
} from "../api";
import MgtvApi from "@/util/mgTvJssdk.js";
import { getWxCode } from "../api/wx";
import util from "../util";
export default {
  name: "home",
  data () {
    return {
      imgUrl: process.env.VUE_APP_IMGS_URL,
    };
  },
  computed: {
    user () {
      return this.$store.state.user;
    },
  },
  created () {
    let channelKey = this.$route.params.key;
    channelGet({
      channelKey: channelKey,
    }).then((res) => {
      let url = location.href;
      if (res.data.wotv !== "1" && url.indexOf("wo186.tv") != -1) {
        return false;
      }

      if (res.data != null) {
        if (res.data.globa.length > 0 && res.data.globa !== null) {
          let list = {};
          res.data.globa.forEach((val) => {
            list[val.tag] = val.status;
          });
          this.$store.commit("setGlobal", list);
          if (list.servicing === 1) {
            this.$router.push("servicing");
          }
          if (list.js === 0) {
            this.createJs(list.point);
          }
        }
        if (res.data.fictitious.length > 0 && res.data.fictitious !== null) {
          let obj = [];
          res.data.fictitious.forEach((item) => {
            if (item.type === 1) {
              obj.push(item.number);
            }
          });
          this.$store.commit("setFictitious", obj.join(','));
        }
        if (res.data.onOffStatus !== 1) {
          if (res.data.channelStatus === 0) {
            this.$router.push("servicing");
            return false;
          } else {
            if (this.$store.state.global.sensors === 0) {
              this.$sensors.registerPage({
                attr1: res.data.fullCode,
              });
            }
            this.onloadNew(
              channelKey,
              res.data.strategyId,
              res.data.channelName,
              res.data.fullCode
            );
          }
        } else {
          this.onload(channelKey, res.data.fullCode, res.data.onOffStatus);
        }
      } else {
        this.$router.push("servicing");
      }
    });
  },
  beforeRouteUpdate (to, from, next) {
    next();
    let channelKey = this.$route.params.key;
    channelGet({
      channelKey: channelKey,
    }).then((res) => {
      let url = location.href;
      if (res.data.wotv !== "1" && url.indexOf("wo186.tv") != -1) {
        return false;
      }
      if (res.data.globa.length > 0 && res.data.globa !== null) {
        let list = {};
        res.data.globa.forEach((val) => {
          list[val.tag] = val.status;
        });

        this.$store.commit("setGlobal", list);
        if (list.servicing === 1) {
          this.$router.push("servicing");
        }
        if (list.js === 0) {
          this.createJs(list.point);
        }
      }
      if (res.data.onOffStatus !== 1) {
        if (res.data.channelStatus === 0) {
          this.$router.push("servicing");
          return false;
        } else {
          this.onloadNew(
            channelKey,
            res.data.strategyId,
            res.data.channelName,
            res.data.fullCode
          );
        }
      } else {
        this.onload(channelKey, res.data.fullCode, res.data.onOffStatus);
      }
    });
  },
  methods: {
    onload (channelKey, fullCode, edition) {
      if (channelKey) {
        localStorage.setItem("key", channelKey);
      } else {
        this.$toast.fail("渠道报错，请刷新页面");
        return false;
      }
      let userid = this.user.userid;
      let anonymousId = this.$sensors.store._state.$device_id;
      let params = {
        anonymousId: anonymousId,
        channelKey: channelKey,
        location: "",
      }
      newStrategy(params).then(async (res) => {
        let data = res.data;

        if (userid) {
          this.$sensors.login(userid);
        }
        this.$sensors.registerPage({
          attr2: data.templateCode,
          attr3: "订购页",
        });
        let info = await detMainProduct({ productId: data.primaryProductId })
        console.log(info)
        let productJson = JSON.parse(data.productJson)
        let mainJson = productJson.product;
        let viceJson = productJson.viceProduct ? productJson.viceProduct : ''
        let mainProduct = {
          activeType: info.data.activeType,
          bannerPics: [mainJson.bannerImg, mainJson.jsonImg, mainJson.upImg, mainJson.topImg,],
          bgColor: [mainJson.pageBgcol, '', mainJson.orderBgcol, mainJson.orderBdcol],
          cacheSeatOne: [{
            dongHua: mainJson.drawVal,
            memberUrl: info.data.cacheSeatOne[0].memberUrl,
            proC: {
              e: mainJson.hideCol,
              s: mainJson.pageTextcol
            },
            productV: mainJson.productV,
            rushC: {
              e: mainJson.orderTextcol,
              s: mainJson.orderNumcol,
            },
            tabC: {
              e: mainJson.tabVicecol,
              s: mainJson.tabMaincol,
            },
            btnUrl: "",
          }],
          cpid: info.data.cpid,
          discountInfo: null,
          flowJumpUrl: info.data.flowJumpUrl,
          givePhoneInfo: info.data.givePhoneInfo,
          guidancePic: {
            c: mainJson.orderImg,
            p: mainJson.explainImg
          },
          id: data.primaryProductId,
          isCompositeProduct: info.data.isCompositeProduct,   //是否复合产品
          logoPic: mainJson.logoPic,
          manualInfo: info.data.manualInfo,
          memberName: info.data.memberName,
          orderingInfo: info.data.orderingInfo,
          originalPrice: info.data.originalPrice,
          pageTitle: mainJson.pageTitle,
          productName: info.data.productName,
          productType: info.data.productType,
          promotionPic: info.data.promotionPic,
          pushJumpUrl: info.data.pushJumpUrl,
          remark: info.data.producremarktName,
          remark1: info.data.remark1,
          remark2: info.data.remark2,
          remark3: mainJson.remark3,
          spid: info.data.spid,
          themeColor: [mainJson.btnTopcol, mainJson.btnBotcol],
        }
        mainProduct.primaryProductInfo = info.data;
        let recommend = [];
        if (data.recommendStrategyIds.length > 0 && data.recommendStrategyIds) {
          data.recommendStrategyIds.forEach(async val => {
            let list = await strategytemplate(val)
            recommend.push(list.data);
          });
        }
        let pageData = {
          mainProduct: mainProduct,
          channl: {
            fullCode: fullCode,
            channelKey: channelKey,
            edition: edition
          },
          recommend: recommend,
          remarks: JSON.parse(data.extJson),
          viceJson: viceJson, //副产品json
          mainJson: mainJson,
          otherJson: data.otherJson, //备用json
          strategyInfo: {
            activityLogo: data.activityLogo,
            activityType: data.activityType,
            directCharge: null,
            extJson: data.extJson,
            id: data.id,
            linkUrl: data.linkUrl,
            maskText: data.maskText,
            posterPhoto: data.posterPhoto,
            primaryProductId: data.primaryProductId,
            primarySpid: null,
            productInfo: [],
            promotePhoto: data.promotePhoto,
            strategyName: data.strategyName,
            strategyStatus: data.strategyStatus,
            strategyType: data.strategyType,
            templateCode: data.templateCode,
            templateId: data.templateId,
            templateName: "",
            recommendStrategyList: data.recommendStrategyIds,
            unsubscribeStrategyList: data.unsubscribeStrategyIds,
            viceProductStrategyList: data.viceProductIds,
          }
        };
        this.$store.commit("setPageData", pageData);
        if (window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == "micromessenger") {
          let banners = pageData.mainProduct.bannerPics[0];
          let img = pageData.mainProduct.logoPic
            ? this.imgUrl + pageData.mainProduct.logoPic
            : this.imgUrl + banners[0];
          let url = location.href;
          let desc = pageData.mainProduct.remark3
            ? pageData.mainProduct.remark3
            : "联通畅视流量包";
          getWxCode(pageData.mainProduct.productName, img, url, desc);
        }
        document.title = mainProduct.pageTitle;
        if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
          MgtvApi.setWebviewTitle({
            title: mainProduct.pageTitle,
          });
        }
        this.$store.commit("setTempName", data.templateCode);
      });
    },
    onloadNew (channelKey, id, channelName, fullCode) {
      document.body.style.height = document.documentElement.clientHeight + "px";
      // this.$store.commit("setTempName", "loading");
      if (channelKey) {
        localStorage.setItem("key", channelKey);
      } else {
        this.$toast.fail("渠道报错，请刷新页面");
        return false;
      }
      let userid = this.user.userid;
      let anonymousId = this.$sensors.store._state.$device_id;
      strategyGetNew(
        {
          channelKey,
          userid,
          anonymousId,
          id,
        },
        true
      )
        .then(async (res) => {
          if (res.data[0].strategyStatus === 1) {
            let data = res.data;
            if (data.id === null) {
              this.$toast.fail("当前页面无效");
              return false;
            }
            if (this.user.phone) {
              if (this.$store.state.global.sensors === 0) {
                this.$sensors.login(this.user.phone);
              }
            }
            if (data[0].testId) {
              this.$store.commit("setTestId", data[0].testId);
            }
            if (data[0].testGroupId) {
              this.$store.commit("setTestGroupId", data[0].testGroupId);
            }
            if (this.$store.state.global.sensors === 0) {
              let beCome = this.buriedPoint();
              localStorage.setItem("beCome", beCome);
              this.$sensors.registerPage({
                attr2: data[0].templateCode,
                attr3: beCome,
                attr19: this.$store.state.testId,
                attr20: this.$store.state.testGroupId,
              });
            }
            let recommend = [];
            if (data[0].recommendStrategyList !== null && data[0].recommendStrategyList.length > 0) {
              for (let i = 0; i < data[0].recommendStrategyList.length; i++) {
                let list = await strategyGetID({ id: data[0].recommendStrategyList[i] }, true);
                recommend.push(list.data);
              }
            }
            let pageData = {
              mainProduct: data[0].productInfo,
              strategyInfo: data[0],
              remarks: data[0].extJson,
              channl: {
                channelKey: channelKey,
                channelName: channelName,
                fullCode: fullCode,
              },
              recommend: recommend,
            };
            document.title = pageData.mainProduct.productName;
            if (
              window.navigator.userAgent
                .toLowerCase()
                .match(/MicroMessenger/i) == "micromessenger"
            ) {
              let banners = pageData.mainProduct.bannerPics[0];
              let img = pageData.mainProduct.logoPic
                ? this.imgUrl + pageData.mainProduct.logoPic
                : this.imgUrl + banners[0];
              let url = location.href;
              let desc = pageData.mainProduct.remark3
                ? pageData.mainProduct.remark3
                : "联通畅视流量包";
              getWxCode(pageData.mainProduct.productName, img, url, desc);
            }
            if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
              // const hackIframe = document.createElement("iframe");
              // hackIframe.style.display = "none";
              // hackIframe.src = "https://operation.mige.tv/a/mgTitle.html";
              // document.body.appendChild(hackIframe);
              // setTimeout((_) => {
              //   document.body.removeChild(hackIframe);
              // }, 300);
              MgtvApi.setWebviewTitle({
                title: pageData.mainProduct.productName,
              });
            }
            this.$store.commit("setPageData", pageData);
            this.$store.commit("setTempName", data[0].templateCode);
          } else {
            this.$toast.fail("当前策略未生效");
          }
        })
        .catch((error) => {
          this.$toast.fail("免登录格式错误");
          localStorage.removeItem("userid");
          // setTimeout(() => {s
          //   location.reload();
          // }, 1500);
        });
    },
    getPorduct (productId) {
      return detMainProduct({
        productId: productId,
      });
    },
    // 外部js
    createJs (num) {
      if (num === 0) {
        //判定是否开启拦截用户中心埋点js创建
        let script = document.createElement("script");
        let script2 = document.createElement("script");
        script.type = "text/javascript";
        script2.type = "text/javascript";
        script.src =
          "//account.bol.wo.cn/static/js-sdk/wolog/VuePageVisitor.js";
        script2.src = "//account.bol.wo.cn/static/js-sdk/wolog/WoAnalytics.js";
        document.body.appendChild(script);
        document.body.appendChild(script2);
      }
      // 其余外部js引入
      let script4 = document.createElement("script");
      let script5 = document.createElement("script");
      script4.type = "text/javascript";
      script5.type = "text/javascript";
      script4.src =
        "https://s1.hdslb.com/bfs/cm/cm-sdk/static/js/track-collect.js";
      script5.src =
        "https://static.yximgs.com/udata/pkg/fe/ks-bridge.1.0.17.min.58d27a53.js";
      document.body.appendChild(script4);
      document.body.appendChild(script5);
    },
    // 埋点
    buriedPoint () {
      let { mappid } = util.query2obj(location.search);
      let beCome = this.$route.query.become;
      if (mappid) {
        return "外链活动";
      }
      if (beCome) {
        return beCome;
      }
      if (!beCome && !mappid) {
        return "订购页";
      }
    },
  },
};
</script>
<style lang="scss">
</style>