<template>
  <div class="treatyNew" id="temp">
    <div class="bannerBox" :style="{backgroundImage: `url(${imgUrl}${pageData.mainProduct.bannerPics[0]})`,
      }" @click="bannerClick">
      <img @click.stop class="activity" v-if="
          pageData.strategyInfo.activityType !== 0 &&
          pageData.strategyInfo.activityLogo
        " :src="`${pageData.strategyInfo.activityLogo}`" @click="onGoLink()" />
      <!-- 轮播条 -->
      <van-notice-bar v-show="showScroll" scrollable :text="pageData.remarks.zoetropeText" />
    </div>
    <!-- 订购按钮 -->
    <div class="buyBox" v-if="
        pageData.remarks.isBuy === '1' && isBuy !== '已订购' && sp !== 'text'
      ">
      <div class="btn" @click="btnClick" :style="{
          'background-color': pageData.mainProduct.themeColor[0],
          'border-color': pageData.mainProduct.themeColor[1],
        }">
        {{ pageData.remarks.btnText ? pageData.remarks.btnText : "点我领取" }}
      </div>
      <!-- 隐私声明 -->
      <div class="privacyBox">
        <van-checkbox v-model="checked" checked-color="#fc8940">
          <p style="margin: 0; padding: 0">
            我已阅读并同意
          </p>
        </van-checkbox>
        <span class="span" v-if="temp === 'ksInfo'" style="color: #fc8940" @click="showAgreeMent = true">《隐私声明》</span>
        <span class="span" v-else style="color: #fc8940" @click="showConceal = true">《隐私声明》</span>
        <span class="span" style="color: #fc8940" @click="ruleClick">《产品说明》</span>
      </div>
      <div class="text"
        :style="productJson.length>0 && productJson[0].rushC.e!==''?{'color':`${productJson[0].rushC.e}`}:{'color':'#000'}">
        <span
          :style="productJson.length>0 && productJson[0].rushC.e!==''?{'color':`${productJson[0].rushC.s}`}:{'color':'#ea1313'}">{{ times }}</span>{{pageData.remarks.orderText!=='' && pageData.remarks.orderText?pageData.remarks.orderText:'用户已抢购成功'}}
      </div>
      <div v-if="temp === 'tencent'" class="tips">
        注：1.手机号仅用于开通服务；2.本服务为中国联通提供，相关服务和责任由中国联通承担，如有问题请咨询中国联通10010。
      </div>
    </div>
    <!-- 短认 -->
    <div v-if="isBuy !== '已订购' && pageData.remarks.isBuy !== 1 && sp === 'text'" class="buyBoxText">
      <div class="textBox">
        <div class="input">
          <input type="text" v-model="loginForm.phone" placeholder="请输入联通手机号" />
        </div>
        <div class="input">
          <input type="text" v-model="loginForm.vcode" v-on:input="checkVcode" placeholder="验证码" maxlength="6" />
          <span class="getcode" :class="{ code: 1, number: codeState.state }"
            @click="getCode('btn')">{{ codeState.state ? codeState.time + "s" : "获取验证码" }}</span>
        </div>
      </div>
      <div class="btn" :style="{
          'background-color': pageData.mainProduct.themeColor[0],
          'border-color':pageData.mainProduct.themeColor[1],
        }" @click="btnTextClick">
        {{ pageData.remarks.btnText ? pageData.remarks.btnText : "点我领取" }}
      </div>
      <!-- 隐私声明 -->
      <div class="privacyBox">
        <van-checkbox v-model="checked" checked-color="#fc8940">
          <p style="margin: 0; padding: 0">
            我已阅读并同意
          </p>
        </van-checkbox>
        <span class="span" v-if="temp === 'ksInfo'" style="color: #fc8940" @click="showAgreeMent = true">《隐私声明》</span>
        <span class="span" v-else style="color: #fc8940" @click="showConceal = true">《隐私声明》</span>
        <span class="span" style="color: #fc8940" @click="ruleClick">《产品说明》</span>
      </div>
      <div class="text"
        :style="productJson.length>0 && productJson[0].rushC.e!==''?{'color':`${productJson[0].rushC.e}`}:{'color':'#000'}">
        <span
          :style="productJson.length>0 && productJson[0].rushC.e!==''?{'color':`${productJson[0].rushC.s}`}:{'color':'#ea1313'}">{{ times }}</span>{{pageData.remarks.orderText!=='' && pageData.remarks.orderText?pageData.remarks.orderText:'用户已抢购成功'}}
      </div>
      <div v-if="temp === 'tencent'" class="tips">
        注：1.手机号仅用于开通服务；2.本服务为中国联通提供，相关服务和责任由中国联通承担，如有问题请咨询中国联通10010。
      </div>
    </div>
    <!-- 用户状态 -->
    <div v-if="user.userid" class="memBox">
      {{ String(user.phone) | formatPhone }}（{{ isBuy }}）
    </div>
    <!-- 说明 -->
    <div class="descbox">
      <div class="main" v-html="pageData.mainProduct.givePhoneInfo"></div>
    </div>
    <!-- 推荐产品 -->
    <div v-if="pageData.recommend.length > 0">
      <div v-for="(item, index) in pageData.recommend" :key="index" class="probox" @click="recommend(item.id)" :style="{
          backgroundImage: `url(${item.promotePhoto})`,
        }"></div>
    </div>

    <!-- 活动图 -->
    <div v-if="pageData.strategyInfo.posterPhoto" class="probox" @click="onGoLink()" :style="{
        backgroundImage: `url(${pageData.strategyInfo.posterPhoto})`,
      }"></div>
    <!-- tab导航 -->
    <div class="tabBox">
      <div class="tab" v-if="pageData.remarks.jiluBtn === '1'" @click="beforeLogin('manual')">
        <img src="../assets/record.png" alt="" />
        <div>订购记录</div>
      </div>
      <div class="tab" v-if="pageData.remarks.jihuoBtn === '1'"
        @click="$emit('jihuo', { product: pageData.mainProduct })">
        <img src="../assets/liuliang.png" alt="" />
        <div>流量激活</div>
      </div>
      <div class="tab" v-if="pageData.remarks.memberBtn === '1'" @click="beforeLogin('member')">
        <img src="../assets/huiyuan.png" alt="" />
        <div>领取会员</div>
      </div>
      <div class="tab" v-if="pageData.remarks.chaxunBtn === '1'" @click="chaxun">
        <img src="../assets/guanzhu.png" alt="" />
        <div>剩余流量查询</div>
      </div>
      <div class="tab" v-if="pageData.remarks.tuidingBtn === '1'" @click="beforeLogin('unBUy')">
        <img src="../assets/tuiding.png" alt="" />
        <div>退订产品</div>
      </div>
    </div>
    <!-- 使用说明 -->
    <div class="rule" @click="ruleClick">
      <div class="icon"></div>
      <div class="text">产品说明</div>
    </div>
    <rule-modal v-if="showRule" @ruleShow="ruleShow" :pageData="pageData"></rule-modal>
    <!-- 反馈 -->
    <div class="tucaoModal" @click="showTucao = true">
      <div class="icon"></div>
      <div class="text">反馈</div>
    </div>
    <vent-modal v-model="showTucao"></vent-modal>
    <!-- 登录弹框组件 -->
    <login-modal v-model="showLogin" :type="type" :text="text" @getIsBuy="getIsBuy"></login-modal>
    <!-- 退订弹框组件 -->
    <unbuy-modal v-model="showUnbuy" :pageData="pageData" @childData="getChildData"></unbuy-modal>
    <!-- 剩余流量查询 -->
    <account-modal v-model="showQr"></account-modal>
    <!-- 订购超时 -->
    <timeout-modal v-model="showTimeout"></timeout-modal>
    <!-- 遮罩 -->
    <newZheZhao v-if="showZhezhao" isZheZhao="1"></newZheZhao>
    <!-- 退订挽留 -->
    <van-overlay :show="unBuyDrainage" :duration="0.1" @click="unBuyDrainage = false"
      pageData.strategyInfo.unsubscribeStrategyList.length>0 > 0 >
      <div class="other-modal modal" @click.stop>
        <img src="../../assets/img/close.png" class="close" @click="unBuyDrainage = false" />
        <div class="text-box">确定要放弃本服务吗?</div>
        <div class="text-box">
          {{ unBuyDrainageText }}
        </div>
        <div class="text-box">不要错过！</div>
        <div class="btn-box">
          <div class="btn left" @click="unBuySure">确定</div>
          <div class="btn right" @click="recommend(pageData.strategyInfo.unsubscribeStrategyList[0])">
            去看看
          </div>
        </div>
      </div>
    </van-overlay>
    <!-- 快手隐私声明 -->
    <agreeMent v-if="temp === 'ksInfo'" v-model="showAgreeMent"></agreeMent>
    <!-- 隐私条款 -->
    <conceal v-model="showConceal"></conceal>
    <!-- 重复订购引流 -->
    <repeat-modal @repeat="recommend" v-model="repeatShow"></repeat-modal>
  </div>
</template>

<script>
  import {
    orderList,
    changeUserid,
    strategyGetID,
    detMainProduct,
    seniorStrategy,
  } from "../../api";
  import mixinTreatyNew from "../../common/mixinTreatyNew";
  import loginModal from "../../components/login.vue";
  import addR from "../../common/addRecord";
  import ruleModal from "../../components/ruleModal002.vue";
  import ventModal from "../../components/helpModal.vue";
  import accountModal from "../../components/gongZongHao.vue";
  import timeoutModal from "../../components/timeoutModal.vue";
  import newZheZhao from "../../components/newZheZhao.vue";
  import unbuyModal from "../../components/unbuyModal.vue";
  import agreeMent from "../../components/agreeMent.vue";
  import MgtvApi from "@/util/mgTvJssdk.js";
  import conceal from "../../components/conceal.vue";
  import repeatModal from "../../components/repeatModal.vue";
  export default {
    mixins: [mixinTreatyNew],
    data() {
      return {
        imgUrl: process.env.VUE_APP_IMGS_URL,
        times: 0,
        showLogin: false,
        showRule: false,
        showTucao: false,
        showQr: false,
        type: "",
        showTimeout: false,
        showUnbuy: false,
        unBuyDrainage: false,
        showAgreeMent: false,
        showScroll: false,
        checked: false,
        unBuyDrainageText: "",
        isBuy: "已订购",
        showConceal: false,
        text: "",
        repeatShow: false,
        productJson: [],
      };
    },
    components: {
      loginModal,
      ruleModal,
      ventModal,
      accountModal,
      timeoutModal,
      newZheZhao,
      unbuyModal,
      agreeMent,
      conceal,
      repeatModal
    },

    props: {
      sp: String,
      temp: String,
      getUid: Function,
      postUid: Function,
    },
    filters: {
      formatPhone: (phone) => {
        phone = phone.toString();
        return phone.substr(0, 3) + "****" + phone.substr(7, 11);
      },
    },
    activated() {
      window.document.title = this.pageData.mainProduct.productName;
      if (/ip(hone|od|ad)/i.test(navigator.userAgent)) {
        const hackIframe = document.createElement("iframe");
        hackIframe.style.display = "none";
        hackIframe.src = "/";
        document.body.appendChild(hackIframe);
        setTimeout((_) => {
          document.body.removeChild(hackIframe);
        }, 300);
      }
    },
    created() {
      document.title = this.pageData.mainProduct.productName;
      if (this.pageData.mainProduct.cacheSeatOne) {
        this.productJson = this.pageData.mainProduct.cacheSeatOne
      }
      if (this.temp === "bili") {
        this.getUid();
      }
      if (this.temp === "ksInfo") {
        let head = document.getElementsByTagName("head")[0];
        let script = document.createElement("script");
        script.innerHTML = `
    (function (root) {
      var ksscript = document.createElement('script');
      ksscript.setAttribute('charset', 'utf-8');
      ksscript.src = 'https://tx2.a.kwimgs.com/udata/pkg/ks-ad-trace-sdk/ks-trace.3.2.0.min.js';
      var s = document.getElementsByTagName('script')[0];
      s.parentNode.insertBefore(ksscript, s);
    })(window);`;
        head.appendChild(script);
      }
      if (this.pageData.remarks.privacy && this.pageData.remarks.privacy !== '' && this.pageData.remarks.privacy !==
        null) {
        if (this.pageData.remarks.privacy === '1') {
          this.checked = true
        }
      }
    },
    mounted() {
      addR.showSP();
      let now = new Date().getTime();
      let times = (now - 1622476800000) / 180000;
      this.times = String(Math.ceil(times * 2));
      if (this.user.userid) {
        this.getIsBuy();
      } else {
        this.isBuy = "未订购";
      }
      let newTime = new Date();
      let d = newTime.getDate();
      if (31 >= d && d >= 25 && this.pageData.remarks.isZoetrope === "1") {
        this.showScroll = true;
      }
    },
    methods: {
      ruleShow() {
        this.showRule = false;
      },
      ruleClick() {
        this.showRule = true;
        localStorage.setItem("startTime", new Date().getTime());
      },
      btnClick() {
        if (this.checked === false) {
          this.$toast.fail("请先勾选隐私声明");
        } else {
          this.openIframe();
        }
      },
      btnTextClick() {
        if (this.checked === false) {
          this.$toast.fail("请先勾选隐私声明");
        } else {
          this.toBuy();
        }
      },

      bannerClick() {
        if (
          this.pageData.remarks.isBuy === "1" &&
          this.sp !== "text" &&
          this.isBuy !== "已订购"
        ) {
          if (this.checked === false) {
            this.$toast.fail("请先勾选隐私声明");
          } else {
            addR.clickBanner();
            this.openIframe();
          }
        }
      },
      chaxun() {
        addR.clickFollow();
        this.showQr = true;
      },
      async beforeLogin(type) {
        this.type = type;
        if (this.user.userid) {
          if (type === "manual" || type === "member") {
            this.toLink(type);
          } else if (type === "unBUy") {
            addR.unBuyClick();
            if (
              this.pageData.strategyInfo.unsubscribeStrategyList !== null &&
              this.pageData.strategyInfo.unsubscribeStrategyList.length > 0
            ) {
              let productId = await strategyGetID({
                id: this.pageData.strategyInfo.unsubscribeStrategyList[0],
              });
              let drainageRes = await detMainProduct({
                productId: productId.data.primaryProductId,
              });
              this.unBuyDrainageText = drainageRes.data.productName;
              this.unBuyDrainage = true;
            } else {
              this.showUnbuy = true;
            }
          }
        } else if (type === "unBUy") {
          addR.unBuyClick();
          if (
            this.pageData.strategyInfo.unsubscribeStrategyList !== null &&
            this.pageData.strategyInfo.unsubscribeStrategyList.length > 0
          ) {
            let productId = await strategyGetID({
              id: this.pageData.strategyInfo.unsubscribeStrategyList[0],
            });
            let drainageRes = await detMainProduct({
              productId: productId.data.primaryProductId,
            });
            this.unBuyDrainageText = drainageRes.data.productName;
            this.unBuyDrainage = true;
          } else {
            this.showUnbuy = true;
          }
        } else {
          addR.loginClick();
          this.showLogin = true;
        }
      },
      toLink(type) {
        let cpid = this.$store.state.pageData.mainProduct.cpid;
        let spid = this.$store.state.pageData.mainProduct.spid;
        let isCompositeProduct =
          this.$store.state.pageData.mainProduct.isCompositeProduct;
        let activeType = this.$store.state.pageData.mainProduct.activeType;
        let productName = this.$store.state.pageData.mainProduct.productName;
        let url;
        if (type === "manual") {
          addR.clickOrderRecord();
          url = "/order001";
        } else if (type === "member") {
          addR.memberClick();
          if (this.pageData.mainProduct.isCompositeProduct === 2) {
            url = "/member002";
          } else {
            url = "/member001";
          }
        }
        this.$router.push({
          path: url,
          query: {
            cpid: cpid,
            spid: spid,
            isCompositeProduct: isCompositeProduct,
            activeType: activeType,
            productName: productName,
          },
        });
      },
      // 获取产品订购状态
      getIsBuy(e) {
        if (this.temp === "ksZC") {
          window.ksBridge.register(
            "emitFreeTrafficUpdate",
            "emitFreeTrafficUpdate"
          );
          window.ksBridge.emitFreeTrafficUpdate({
            complete: (res) => {
              console.log(res);
            },
          });
        }
        if (this.temp === "ksInfo") {
          window.ksBridge.register(
            "emitFreeTrafficUpdate",
            "emitFreeTrafficUpdate"
          );
          window.ksBridge.emitFreeTrafficUpdate({
            complete: (res) => {
              console.log(res);
            },
          });
        }
        orderList({
          userid: this.user.userid,
          cpid: this.param.cpid,
          spid: this.param.spid,
        }).then((res) => {
          let data = res.data;
          if (data.length === 0) {
            this.isBuy = "未订购";
          } else {
            for (let i = 0; i < data.length; i++) {
              if (data[i].STATUS === "0") {
                this.isBuy = "已订购";
              } else {
                this.isBuy = "已退订";
              }
            }
          }
        });
      },
      // 推荐产品跳转
      recommend(val) {
        // this.$store.commit("setTempName", "loading");
        strategyGetID({
          id: val
        }).then(async (res) => {
          if (res.data.strategyStatus === 1) {
            let data = res.data;
            let info = await detMainProduct({
              productId: data.primaryProductId
            });
            if (this.user.userid) {
              this.getIsBuy();
            }
            let recommend = [];
            if (
              data.recommendStrategyList !== null &&
              data.recommendStrategyList.length > 0
            ) {
              for (let i = 0; i < data.recommendStrategyList.length; i++) {
                let list = await strategyGetID({
                  id: data.recommendStrategyList[i],
                });
                recommend.push(list.data);
              }
            }
            let pageData = {
              mainProduct: info.data,
              strategyInfo: data,
              remarks: data.extJson,
              channl: {
                channelKey: localStorage.getItem("key"),
              },
              recommend: recommend,
            };
            MgtvApi.setWebviewTitle({
              title: pageData.mainProduct.productName,
            });
            let params = {
              anonymousId: this.$sensors.store._state.$device_id,
              channleKey: localStorage.getItem("key"),
              spId: info.data.spid,
              userId: this.user.userid,
            };
            let item = await seniorStrategy(params);
            if (item.data !== null) {
              // 判断高级策略是否开启遮罩;
              if (item.data.enableMask !== null) {
                pageData.remarks.isMask = String(item.data.enableMask);
                // 判断高级策略是否有遮罩文案 并替换
                if (item.data.maskText !== null && item.data.maskText !== "") {
                  pageData.remarks.maskText = item.data.maskText;
                }
              }
              // 判断高级策略是否开启有推荐
              if (
                item.data.recommendStrategy !== "" &&
                item.data.recommendStrategy !== null
              ) {
                let itemList = item.data.recommendStrategy.split(",");
                pageData.recommend = [];
                itemList.forEach((v) => {
                  strategyGetID({
                    id: v,
                  }).then((resp) => {
                    pageData.recommend.push(resp.data);
                  });
                });
              }
              if (item.data.cancelRule !== "" && item.data.cancelRule !== null) {
                pageData.strategyInfo.unsubscribeStrategyList =
                  item.data.cancelRule.split(",");
              }
              if (item.data.interceptRule === "1") {
                pageData.interceptRule = item.data.interceptRule;
              }
              if (item.data.location !== "" && item.data.location !== null) {
                pageData.location = item.data.location.split(",");
              }
            }
            document.title = pageData.mainProduct.productName;
            this.$store.commit("setPageData", pageData);
            this.$store.commit("setTempName", data.templateCode);
            if (item.data !== null) {
              if (
                item.data.templateName !== "" &&
                item.data.templateName !== null
              ) {
                this.$store.commit("setTempName", item.data.templateName);
              }
            }
          } else {
            this.$toast.fail("当前策略未生效");
          }
        });
        this.unBuyDrainage = false;
      },
      // 活动链接跳转
      onGoLink() {
        if (this.user.userid) {
          if (this.pageData.strategyInfo.activityType === 2) {
            let url = `${
            this.pageData.strategyInfo.linkUrl
          }&userid=${encodeURIComponent(this.user.userid)}`;
            window.location.href = url;
          } else if (this.pageData.strategyInfo.activityType === 1) {
            changeUserid({
              userid: this.user.userid,
              cpid: this.param.cpid,
            }).then((res) => {
              let url = `${this.pageData.strategyInfo.linkUrl}?userid=${res.data}`;
              window.location.href = url;
            });
          }
        } else {
          this.loginType = " 登录 ";
          this.showLogin = true;
          addR.loginClick();
        }
      },
      // 点击确定
      unBuySure() {
        addR.clickUnsubscribe();
        this.unBuyDrainage = false;
        this.showUnbuy = true;
      },
      getChildData(data) {
        this.isBuy = data;
      },
    },
  };
</script>

<style lang="scss">
  @import "./index.scss";
</style>