<template>
  <div class="templateThree" id="temp" :style="{ 'backgroundColor': pageData.mainJson.pageBgcol }">
    <div class="bannerBox">
      <!-- 底层banner -->
      <img class="banner" v-if="pageData.mainJson.bannerImg" :class="pageData.mainJson.dongHua == '1' ? 'cartoon1' : ''
        " :src="imgUrl + pageData.mainJson.bannerImg" alt="" />
      <!-- json动图 -->
      <div class="svgBanner">
        <div id="lottie_box"></div>
      </div>
      <!-- 上层png -->
      <div class="banner2" :class="pageData.mainJson.dongHua == '1' ? 'cartoon2' : ''"
        v-if="pageData.mainJson.upImg !== ''">
        <img :src="imgUrl + pageData.mainJson.upImg" alt="" />
      </div>
      <!-- 顶层png/gif -->
      <div class="banner2" v-if="pageData.mainJson.topImg !== ''">
        <img :src="imgUrl + pageData.mainJson.topImg" alt="" />
      </div>
      <img @click.stop class="activity"
        v-if="pageData.strategyInfo.activityType !== 0 && pageData.strategyInfo.activityLogo"
        :src="`${pageData.strategyInfo.activityLogo}`" @click="onGoLink()" />
      <div class="extend" v-if="pageData.remarks.extendImg">
        <img :src="pageData.remarks.extendImg" alt="" />
      </div>
      <div class="rule" @click="ruleClick">
        产品说明
      </div>
    </div>
    <div class="orderBox"
      :style="{ 'background': pageData.mainJson.orderBgcol, 'borderColor': pageData.mainProduct.bgColor[3] }">
      <div class="orderTitle" v-if="pageData.mainJson.explainTitle !== ''">
        <img :src="imgUrl + pageData.mainJson.explainTitle" alt="">
      </div>
      <div class="orderRow" v-if="pageData.remarks.img1 != ''">
        <div class="orderContent" v-for="(item, index) in productDatas" :key="index">
          <img :src="imgUrl + item.img" alt="">
          <div class="buyBtn" @click="buyBtn(item)"
            :style="{ 'background-image': `linear-gradient(90deg,${pageData.mainJson.btnTopcol},${pageData.mainJson.btnBotcol})`, 'color': pageData.mainJson.btnTextCol }">
            ￥{{ item.originalPrice }}/月
          </div>
        </div>
      </div>
      <div class="orderRow" v-else>
        <div class="orderContent2" v-for="(item, index) in productDatas" :key="index"
          :style="{ 'background-image': `linear-gradient(313deg,${pageData.remarks.threeBgCol1},${pageData.remarks.threeBgCol2})` }">
          <div class="content_box" v-if="productNum > -1" @click="tabProduct(item, index)"
            :style="productNum === index ?
              { 'background-image': `linear-gradient(313deg,${pageData.remarks.threeBgCol1},${pageData.remarks.threeBgCol2})`, 'color': '#fff' }
              : { 'background-image': `linear-gradient(313deg,${pageData.remarks.threeBgCol3},${pageData.remarks.threeBgCol4})`, 'color': `${pageData.remarks.threeTxtCol2}` }">
            <div v-if="index == 0">
              <div class="div1">5G速率</div>
              <div class="div2">5GB</div>
            </div>
            <div v-if="index == 1">
              <div class="div1">5G速率</div>
              <div class="div2">10GB</div>
            </div>
            <div v-if="index == 2">
              <div class="div1">5G速率</div>
              <div class="div2">20GB</div>
            </div>
            <div class="buyBtn"
              :style="productNum == index ? { 'color': `${pageData.remarks.threeTxtCol2}`, 'opacity': '0.6' } : { 'border': `1px solid ${pageData.remarks.threeTxtCol2}`, 'color': `${pageData.remarks.threeTxtCol2}` }">
              ￥{{ item.originalPrice }}/月
            </div>
          </div>

        </div>
      </div>
      <div class="textBox">
        <div class="input">
          <input type="text" @blur="inputBlur" @focus="inputFocus($event)" maxlength="11" placeholder="请输入联通号码"
            v-model="phone" />
        </div>
      </div>
      <div class="buyBox" v-if="pageData.remarks.isBuy === '1' && pageData.remarks.img1 == ''">
        <div class="btn" @click="orderBtn" :class="!pageData.mainJson.btnBorderCol ? '' : 'borderColor'"
          :style="{ 'background-image': `linear-gradient(to right,${pageData.mainJson.btnTopcol},${pageData.mainJson.btnBotcol})`, 'border-color': pageData.mainJson.btnBorderCol }">
          {{ pageData.remarks.btnText ? pageData.remarks.btnText : "立即订购" }}
        </div>
      </div>
      <div class="privacyBox" v-if="pageData.remarks.isBuy === '1'">
        <van-checkbox v-model="checked" checked-color="#6696FF">
          <div>
            <p style="margin: 0; padding: 0">手机号仅用于开通服务,我已阅读并同意
            </p>
          </div>
        </van-checkbox>
      </div>
      <div class="priacyText" :style="pageData.mainJson.hideCol !== '' ? { 'color': pageData.mainJson.hideCol } : {}">
        <span class="span" @click="showConceal = true">《隐私声明》</span>、
        <span class="span" @click="showRule = true">《产品说明》</span>
      </div>
      <div class="tips" v-if="pageData.remarks.privacyText !== ''"
        :style="pageData.mainJson.pageTextcol !== '' ? { 'color': pageData.mainJson.pageTextcol } : { 'color': '#000' }">
        {{ pageData.remarks.privacyText }}
      </div>
    </div>

    <!-- 说明 -->
    <div class="descbox"
      :style="{ 'background': pageData.mainJson.orderBgcol, 'borderColor': pageData.mainProduct.bgColor[3] }">
      <div class="explainTitle">
        <img :src="imgUrl + pageData.mainJson.orderImg" alt="">
      </div>
      <div class="main"
        :style="pageData.mainJson.pageTextcol !== '' ? { 'color': pageData.mainJson.pageTextcol } : { 'color': '#000' }"
        v-html="pageData.mainProduct.givePhoneInfo"></div>
    </div>
    <!-- tab导航 -->
    <tab-Modal @tabClick="tabClickThree" :isApplet="isApplet"></tab-Modal>
    <!-- 隐私条款 -->
    <conceal v-model="showConceal" :pageData="pageData"></conceal>
    <!-- 产品说明 -->
    <rule-modal v-model="showRule" @ruleShow="showRule = false" :pageData="pageData"></rule-modal>
    <!-- <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" @jihuo="jihuo"
      @memberClick="beforeLogin"></unbuy-modal>
    <!-- 剩余流量查询 -->
    <account-modal v-model="showQr"></account-modal>
    <!-- 订购超时 -->
    <timeout-modal v-model="showTimeout"></timeout-modal>
    <!-- 遮罩 -->
    <newZheZhao v-if="showZhezhao" isZheZhao="1" :indexNum="indexNum"></newZheZhao>
    <!-- 退订挽留 -->
    <van-overlay :show="unBuyDrainage" :duration="0.1" @click="unBuyDrainage = false">
      <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>
    <!-- 重复订购引流 -->
    <repeat-modal @repeat="recommend" v-model="repeatShow"></repeat-modal>
    <!-- 选择退订产品 -->
    <tab-unbuy @itemClick="itemClick" :datas="productDatas" v-model="unbuyShow" />
    <!-- 订购成功提示  -->
    <handel-modal v-model="handelShow" @jihuo="jihuoChange"></handel-modal>
    <!-- 退出挽留 -->
    <exit-modal v-model="exitShow" />
    <!-- 会员弹框 -->
    <member-modal v-model="memberShow" />
    <!-- 会员二维码弹框 -->
    <member-code v-model="memberCode" />
  </div>
</template>

<script>
import { detMainProduct, strategytemplate } from "../../api";
import common from '@/common/common'
import ruleModal from "../../componentsNew/ruleModal002.vue";
import conceal from "../../componentsNew/hideModal.vue";
import tabModal from "./components/tabModal.vue";
import tabUnbuy from "./components/tabUnbuy.vue";
import loginModal from "../../componentsNew/login.vue";
import accountModal from "../../componentsNew/gongZongHao.vue";
import timeoutModal from "../../componentsNew/timeoutModal.vue";
import newZheZhao from "../../componentsNew/newZheZhao.vue";
import unbuyModal from "../../componentsNew/unbuyModal.vue";
import repeatModal from "../../componentsNew/repeatModal.vue";
import handelModal from "../../componentsNew/handelModal.vue";
import MgtvApi from "@/util/mgTvJssdk.js";
import lottie from "lottie-web";
import addR from "../../common/addRecord";
import { Dialog } from "vant";

export default {
  mixins: [common],
  components: {
    ruleModal,
    conceal,
    tabModal,
    loginModal,
    accountModal,
    timeoutModal,
    newZheZhao,
    unbuyModal,
    repeatModal,
    tabUnbuy,
    handelModal
  },
  data () {
    return {
      lottie: {},
      imgUrl: process.env.VUE_APP_IMGS_URL,
      dataIds: [],
      productDatas: [],
      imgDatas: [],
      key: 0,
      type: "",
      checked: false,
      showConceal: false,
      showRule: false,
      showUnbuy: false,
      showLogin: false,
      showTimeout: false,
      unBuyDrainage: false,
      showQr: false,
      repeatShow: false,
      unbuyShow: false,
      unBuyDrainageText: "",
      phone: "",
      isBuy: "未订购",
      text: "",
      productNum: 0,
      handelShow: false
    }
  },
  async created () {
    this.dataIds.push(this.pageData.mainProduct.id)
    if (this.pageData.remarks.img1 !== '') {
      this.imgDatas.push(this.pageData.remarks.img1)
    }
    if (this.pageData.strategyInfo.viceProductStrategyList.length > 0) {
      this.dataIds.push(this.pageData.strategyInfo.viceProductStrategyList[0])
      if (this.pageData.remarks.img2 !== '') {
        this.imgDatas.push(this.pageData.remarks.img2)
      }
    }
    if (this.pageData.remarks.viceProductId2 !== '') {
      this.dataIds.push(this.pageData.remarks.viceProductId2)
      if (this.pageData.remarks.img3 !== '') {
        this.imgDatas.push(this.pageData.remarks.img3)
      }
    }
    for (let i = 0; i < this.dataIds.length; i++) {
      await detMainProduct({ productId: this.dataIds[i] }).then(res => {
        this.key = this.key + 1
        let obj = res.data
        obj.img = this.imgDatas[i]
        this.productDatas.push(obj)
      })
    }
  },
  mounted () {
    addR.showSP();
    this.callSvg();
    if (this.pageData.remarks.privacy === '1') {
      this.checked = true
    }
  },
  watch: {
    phone (val) {
      if (val != '') {
        addR.phoneEvent()
      }
    }
  },
  methods: {
    inputBlur () {
      if (this.phone != '') {
        addR.phoneEvent()
      }
    },
    inputFocus (e) {

      if (this.isNet2) {
        if (this.pageData.remarks.dispose && this.pageData.remarks.dispose !== '') {
          if (this.pageData.remarks.dispose == 'net5G') {
            if (!this.checked) {
              return this.$toast('请勾选隐私声明!')
            }

            if (!localStorage.getItem('net5g')) {
              this.$nextTick(() => {
                e.srcElement.blur()
                this.getNetUrl()
              })
            }
          }
        }
      }


    },
    tabClickThree (item) {
      if (this.isApplet == true) {
        if (item.tabUrlApplet !== '') {
          let url = item.tabUrlApplet + '&channelName=' + this.pageData.channl.channelKey
          window.location.href = url
        } else {
          if (item.tabName == '流量激活') {
            this.jihuo('点击激活')
          } else if (item.tabName == '一键反馈') {
            this.toPhone()
          } else if (item.tabName == '退订产品') {
            // this.beforeLogin('unBUy')
            this.unbuyShow = true
          } else if (item.tabName == '剩余流量查询' || item.tabName == '流量查询') {
            this.chaxun()
          }
        }
      } else {
        if (item.tabUrlBasics !== '') {
          let url = item.tabUrlBasics + '&channelName=' + this.pageData.channl.channelKey
          window.location.href = url
        } else {
          if (item.tabName == '流量激活') {
            this.jihuo('点击激活')
          } else if (item.tabName == '一键反馈') {
            this.toPhone()
          } else if (item.tabName == '退订产品') {
            this.unbuyShow = true
          } else if (item.tabName == '剩余流量查询' || item.tabName == '流量查询') {
            this.chaxun()
          }
        }
      }
    },
    itemClick (data) {
      this.unbuyShow = false
      this.pageData.mainProduct.cpid = data.cpid
      this.pageData.mainProduct.spid = data.spid
      this.pageData.mainProduct.id = data.id
      this.param.cpid = data.cpid
      this.param.spid = data.spid
      this.beforeLogin('unBUy')
    },
    ruleClick () {
      this.showRule = true;
      localStorage.setItem("startTime", new Date().getTime());
    },
    // 点击确定
    unBuySure () {
      addR.clickUnsubscribe();
      this.unBuyDrainage = false;
      this.showUnbuy = true;
    },
    getChildData (data) {
      this.isBuy = data;
    },
    // 一键拨号反馈
    toPhone () {
      addR.dialNumber();
      let phone = 4000600611;
      window.location.href = "tel://" + phone;
    },
    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.length > 0) {
            let productId = await strategytemplate(
              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.length > 0) {
          let productId = await strategytemplate(
            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;
      }
    },
    chaxun () {
      addR.clickFollow();
      this.showQr = true;
    },
    // 推荐产品跳转
    recommend (val) {
      strategytemplate(val).then(async (res) => {
        let info = await detMainProduct({
          productId: res.data.primaryProductId,
        });
        let productJson = JSON.parse(res.data.productJson).product;
        let mainProduct = {
          activeType: info.data.activeType,
          bannerPics: [
            productJson.bannerImg,
            productJson.jsonImg,
            productJson.upImg,
            productJson.topImg,
          ],
          bgColor: [
            productJson.pageBgcol,
            "",
            productJson.orderBgcol,
            productJson.orderBdcol,
          ],
          cacheSeatOne: [
            {
              dongHua: productJson.drawVal,
              memberUrl: info.data.cacheSeatOne[0].memberUrl,
              proC: {
                e: productJson.hideCol,
                s: productJson.pageTextcol,
              },
              productV: productJson.productV,
              rushC: {
                e: productJson.orderTextcol,
                s: productJson.orderNumcol,
              },
              tabC: {
                e: productJson.tabVicecol,
                s: productJson.tabMaincol,
              },
              btnUrl: "",
              relationIds: info.data.cacheSeatOne[0].relationIds ? info.data.cacheSeatOne[0].relationIds : "",
              isTreaty: info.data.cacheSeatOne[0].isTreaty ? info.data.cacheSeatOne[0].isTreaty : "0"
            },
          ],
          cpid: info.data.cpid,
          discountInfo: null,
          flowJumpUrl: info.data.flowJumpUrl,
          givePhoneInfo: info.data.givePhoneInfo,
          guidancePic: {
            c: productJson.orderImg,
            p: productJson.explainImg,
          },
          id: res.data.primaryProductId,
          isCompositeProduct: 0, //是否复合产品
          logoPic: productJson.logoPic,
          manualInfo: info.data.manualInfo,
          memberName: info.data.memberName,
          orderingInfo: info.data.orderingInfo,
          originalPrice: info.data.originalPrice,
          pageTitle: productJson.pageTitle,
          productName: info.data.productName,
          productType: info.data.productType,
          promotionPic: info.data.promotionPic,
          pushJumpUrl: info.data.pushJumpUrl,
          remark: info.data.remark,
          remark1: info.data.remark1,
          remark2: info.data.remark2,
          remark3: productJson.remark3,
          spid: info.data.spid,
          themeColor: [productJson.btnTopcol, productJson.btnBotcol],
        };
        let recommend = [];
        if (
          res.data.recommendStrategyIds.length > 0 &&
          res.data.recommendStrategyIds
        ) {
          res.data.recommendStrategyIds.forEach(async (val) => {
            let list = await strategytemplate(val);
            recommend.push(list.data);
          });
        }
        let pageData = {
          mainProduct: mainProduct,
          channl: {
            channelKey: this.pageData.channl.channelKey,
            channelName: this.pageData.channl.channelName,
            fullCode: this.pageData.channl.fullCode,
            edition: this.pageData.channl.edition,
          },
          recommend: recommend,
          remarks: JSON.parse(res.data.extJson), //策略信息
          otherJson: JSON.parse(res.data.otherJson), //备用json
          strategyInfo: res.data,
        };
        let title =
          mainProduct.pageTitle !== ""
            ? mainProduct.pageTitle
            : mainProduct.productName;
        document.title = title;
        MgtvApi.setWebviewTitle({
          title: title,
        });
        pageData.strategyInfo.recommendStrategyList =
          res.data.recommendStrategyIds;
        pageData.strategyInfo.unsubscribeStrategyList =
          res.data.unsubscribeStrategyIds;
        pageData.strategyInfo.viceProductStrategyList =
          res.data.viceProductIds;
        if (JSON.parse(res.data.productJson).viceProduct) {
          pageData.viceJson = JSON.parse(res.data.productJson).viceProduct;
        }
        pageData.mainJson = JSON.parse(res.data.productJson).product;
        this.$store.commit("setPageData", pageData);
        this.getIsBuy();
        setTimeout(() => {
          this.callSvg();
        }, 200);
        this.$store.commit("setTempName", res.data.templateCode);
      });

      this.unBuyDrainage = false;
    },
    buyBtn (item) {
      this.$store.commit("setProduct", item);
      if (this.checked == false) {
        this.$toast('请勾选隐私声明')
      } else {
        this.pageData.mainProduct.cpid = item.cpid
        this.pageData.mainProduct.spid = item.spid
        this.pageData.mainProduct.id = item.id
        this.param.cpid = item.cpid
        this.param.spid = item.spid
        this.openIframe()
      }
    },
    tabProduct (item, index) {
      if (this.productNum != index) {
        this.productNum = -1
        setTimeout(() => {
          this.productNum = index
        }, 0)
      }
      this.pageData.mainProduct.cpid = item.cpid
      this.pageData.mainProduct.spid = item.spid
      this.pageData.mainProduct.id = item.id
      this.param.cpid = item.cpid
      this.param.spid = item.spid

    },
    orderBtn () {
      if (this.phone == "") {
        this.$toast('请输入手机号')
      } else {
        if (/^1[3456789]\d{9}$/.test(this.phone)) {
          let str = this.phone.slice(0, 3);
          let str2 = this.phone.slice(0, 4);
          let number = this.$store.state.fictitious.split(",");
          let isDialog = true;
          if (number !== "") {
            number.forEach((element) => {
              if (element === str || element === str2) {
                isDialog = false;
              }
            });
          }
          if (isDialog == false) {
            Dialog({
              message: "您的号码为虚拟运营商号码，不支持办理此业务",
              theme: "round-button",
            });
            return false;
          }
          if (this.checked == false) {
            this.$toast('请勾选隐私声明')
          } else {
            this.openIframe()
          }
        } else {
          this.$toast('手机号格式错误')
        }
      }
    },
    // 调用svg动画
    callSvg () {
      let lottieBox = document.getElementById("lottie_box");
      lottieBox.innerHTML = "";
      if (this.pageData.mainJson.jsonImg !== '') {
        this.lottie = lottie.loadAnimation({
          container: lottieBox,
          renderer: "svg",
          loop: true,
          autoplay: true,
          path: this.imgUrl + this.pageData.mainJson.jsonImg,
        });
      }
    },
  }


}
</script>

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