import {
  postBuy,
  postNewBuy,
  orderList,
  changeBackUserid,
  changeUseridToPhone,
  memberGive,
  changeUserid,
  login,
  aqyUser,
  numberSearch,
  getPhoneAddres,
  detMainProduct,
  ssotoken,
  getUrl,
  phoneNet,
  llgetCap
} from '../api'
import exitModal from "../components/exitModal.vue";
import util from '../util'
import addR from "../common/addRecord";
import wx from "weixin-js-sdk";
import { Dialog } from "vant";
import { outsideJs, biliUser, activation } from '../api/JS'
import { mapState } from 'vuex';
import ll from './ll'
export default {
  components: {
    exitModal
  },
  data () {
    return {
      iframeUrl: process.env.VUE_APP_IFAMRE, //iframe 地址
      param: {
        cpid: '',
        spid: '',
        // channel: "GDTCvivo0001",
        channel: "boyuan",
        channeltype: "1",
        timestamp: "",
        clienttype: "3",
        sign: "",
        phone: "",
        theme: "",
        version: "1.0.0",
        servicephone: "",
        spchannelId: ''
      },
      payState: false,
      iframe: {},
      iframeNet: {},
      showZhezhao: false,
      showTimeout: false,
      callback: "",
      // 临时实现
      bgc: '#ffffff',
      showVcode: false,
      dateTime: new Date(),
      getIsNum: 0,
      userid: "",
      indexNum: 0,
      isApplet: false,
      isNet: false,
      isNet2: true,
      exitShow: false,
      memberShow: false,
      memberCode: false,
      memberNum: 0
    }
  },
  computed: {
    user () {
      return this.$store.state.user
    },
    pageData () {
      this.param.cpid = this.$store.state.pageData.mainProduct.cpid
      this.param.spid = this.$store.state.pageData.mainProduct.spid
      this.param.spchannelId = this.$store.state.pageData.channl.fullCode
      return this.$store.state.pageData
    },
    ...mapState(['channelInfo', 'fog'])
  },
  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);
    }
  },
  async created () {
    addR.openPage() // 页面打开事件
    let {
      callback,
      tid
    } = util.query2obj(location.search)
    if (callback) {
      this.callback = callback;
    }
    if (tid) { // 任务id获取
      this.$sensors.registerPage({
        taskid: tid
      });
      //  addr相关埋点也需要增加该参数  旭哥在改接口  今天更新
      this.$store.commit('setTid', tid)
    }
    await this.userMatch()
    if (this.pageData.remarks.attestation != 0) {
      if (this.$route.query.phone) {
        this.phone = this.$route.query.phone;
      }
    }
  },
  mounted () {
    wx.miniProgram.getEnv(res => {
      this.isApplet = res.miniprogram
    })
    var that = this
    let channelKey = that.pageData.channl.channelKey
    if (!channelKey) {
      localStorage.setItem('key', channelKey)
    }
    // 统一认证监听
    window.addEventListener('message', e => {
      // console.log(e)
      if (!this.isNet) {
        document.body.style.overflow = '';
        if (e.data.type === 'onActiveCallback') { } else if (e.data.type === 'onBuyCallback') {
          window.console.log(e.data.data.msg)
          // this.$toast(e.data.data.msg)
        } else {
          try {
            var data = JSON.parse(e.data);
            switch (data.resultcode) {
              case "0": //处理成功
                if (this.fog) {
                  let params = {
                    fes: this.channelInfo.fes,
                    sou: this.channelInfo.sou,
                    fog: this.fog,
                    userid: decodeURIComponent(data.userid),
                    usermob: data.usermob,
                    token: data.token,
                    useraccount: "",
                    fullCode: this.channelInfo.fullCode,
                    channelKey: this.channelInfo.channelKey,
                    channelId: "",
                    productId: this.pageData.mainProduct.id,
                    productName: this.pageData.mainProduct.productName,
                    spid: this.pageData.mainProduct.cpid,
                    cpid: this.pageData.mainProduct.spid,
                    phone: this.phone,
                    handleType: 0,
                    remark: ""
                  }
                  addR.getToken()
                  ll.llorder(params).then(res => {
                    // console.log(res)
                    if (res.code == 10000) {
                      if (res.data.resultCode == '0000') {
                        this.$toast.success('订购成功！')
                        addR.buySuccess()
                      } else {
                        this.$toast.fail(res.data.errorInfo)
                        addR.buyFail(res.data.errorInfo)
                      }
                      this.showZhezhao = false
                      this.iframe.remove();
                      // this.$toast.clear()
                    }
                  })
                } else {
                  changeUseridToPhone({
                    userid: decodeURIComponent(data.userid)
                  }).then(res => {
                    this.$store.commit('setUser', {
                      userid: decodeURIComponent(data.userid),
                      phone: res.data
                    })
                    this.$sensors.login(res.data)
                    this.onMessageSuccess(data);
                  })
                }

                break;
              case "0001": //auth_no无效
              case "0003": //client_id不存在
              case "4444": //服务暂时不可用（系统忙/系统队列满）
              case "9001": //关闭H5认证页面
                that.showZhezhao = false
                that.iframe.remove();
                that.$toast(res.data);
                break;
              default:
                that.$toast(res.data)
                break;
            }
          } catch (e) { }
        }
      } else {
        if (e.data.code) {
          if (e.data.code == '2007') {
            this.getTotast(1)
          } else if (e.data.code == '1000') {
            this.getTotast(3)
          } else if (e.data.code == '-2') {
            this.getTotast(4)
          }
        } else {
          if (e.data) {
            let time = new Date().getTime()
            localStorage.setItem('net5g', time)
            this.getPhoneNet(e.data)
          } else {
            this.getTotast(2)
          }

        }
      }
    }, false);
    // 关闭页面监听
    if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
      window.addEventListener("pagehide", e => this.unloadHandler(e));
    } else {
      window.addEventListener("unload", e => this.unloadHandler(e));
    }
    // 判断  渠道中是否有流量产品 参数  并获取流量产品信息fog
    // console.log(this.channelInfo.fes)
    if (this.channelInfo.fes && this.channelInfo.fes != '') {
      this.llgetSgin()
    }
  },
  methods: {
    // 确认取号
    getTotast (num) {
      this.iframeNet.remove();
      if (num == 1) {
        let time = new Date().getTime()
        localStorage.setItem('net5g', time)
        this.$toast('取号次数已达上限,请手动输入')
      } else if (num == 2) {
        this.isNet2 = false
        this.$toast('验证失败,请重新输入')
      } else if (num == 3) {
        this.isNet2 = false
      } else {
        this.isNet2 = false
        let unicom = new Date().getTime()
        localStorage.setItem('unicomTime', unicom)
        this.$toast('请手动输入')
      }

    },
    jihuoChange () {
      this.handelShow = false
      let tabArr = this.pageData.remarks.tabArr
      let obj = tabArr.find(val => val.tabName === "流量激活")
      this.tabClick(obj)
    },
    tabClick (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.beforeLogin('manual')
          } else if (item.tabName == '流量激活') {
            this.jihuo('点击激活')
          } else if (item.tabName == '一键反馈') {
            this.toPhone()
          } else if (item.tabName == '退订产品') {
            this.beforeLogin('unBUy')
          } else if (item.tabName == '剩余流量查询' || item.tabName == '流量查询') {
            this.chaxun()
          } else if (item.tabName == '会员领取') {
            this.beforeLogin('member')
          }
        }
      } else {
        if (item.tabUrlBasics !== '') {
          let url = item.tabUrlBasics + '&channelName=' + this.pageData.channl.channelKey
          window.location.href = url
        } else {
          if (item.tabName == '订购记录') {
            this.beforeLogin('manual')
          } else if (item.tabName == '流量激活') {
            this.jihuo('点击激活')
          } else if (item.tabName == '一键反馈') {
            this.toPhone()
          } else if (item.tabName == '退订产品') {
            this.beforeLogin('unBUy')
          } else if (item.tabName == '剩余流量查询' || item.tabName == '流量查询') {
            this.chaxun()
          } else if (item.tabName == '会员领取') {
            this.beforeLogin('member')
          }
        }
      }
    },
    openIframe () {

      var that = this
      addR.buyClick()
      if (that.fog) {
        llgetCap({ fog: that.fog, channel: "" }).then(resp => {
          resp.data.orderChannel = that.channelInfo.fes + '_' + that.channelInfo.sou
          resp.data.phone = that.phone
          let iframe = document.createElement('iframe');
          let bodyDom = document.getElementById('temp');
          iframe.id = 'iframe'
          iframe.classList.add('iframe')
          iframe.src = "https://800.wo.cn/cap/CAP-AUTH.html"
          that.iframe = iframe
          bodyDom.insertBefore(iframe, bodyDom.lastChild)
          iframe.onload = function () {
            iframe.contentWindow.postMessage(JSON.stringify(resp.data), 'https://800.wo.cn')
          }
        })
      } else {
        document.body.style.overflow = 'hidden';
        that.$toast.loading({
          message: '请求中...'
        });
        let now = Date.now()
        that.param.timestamp = now
        that.param.sign = that.$md5(that.param.cpid + now + '!QAZ2wsx')
        // that.param.sign = that.$md5(that.param.cpid + now + 'hxBz!3!n')
        if (that.phone) {
          that.param.phone = that.phone
        }
        let iframe = document.createElement('iframe');
        let bodyDom = document.getElementById('temp');
        iframe.id = 'iframe'
        iframe.classList.add('iframe')
        iframe.src = that.iframeUrl
        bodyDom.insertBefore(iframe, bodyDom.lastChild)
        that.iframe = iframe
        iframe.onload = function () {
          iframe.contentWindow.postMessage(JSON.stringify(that.param), that.iframeUrl)
          if (that.pageData.remarks.isMask === '1') {
            that.showZhezhao = true
          }
          that.$toast.clear();
        }
      }


    },
    async onMessageSuccess (data) {
      addR.getToken()
      this.iframe.remove();
      this.showZhezhao = false
      let fromSource = localStorage.getItem('beCome')
      let updata = {
        cpid: this.param.cpid,
        spid: this.param.spid,
        productId: this.pageData.mainProduct.id,
        channelKey: this.pageData.channl.channelKey,
        token: data.token,
        type: '0',
        userid: decodeURIComponent(data.userid),
        needJoinActivity: this.pageData.remarks.isZhic === '1' ? 1 : 0,
        fromSource: fromSource,
        anonymousId: this.$sensors.store._state.$device_id,
        testId: this.$store.state.testId,
        testGroupId: this.$store.state.testGroupId,
      }
      this.handel(updata)
    },
    // 订购111
    handel (updata) {
      if (this.pageData.remarks.returnApi && this.pageData.remarks.returnApi !== '' && this.pageData.remarks.returnApi === '0') {
        if (this.pageData.remarks.dispose && this.pageData.remarks.dispose !== '') {
          outsideJs()
        }
      }
      if (this.pageData.interceptRule !== "1") {
        postBuy(updata).then(res => {
          if (res.code == 10000) {
            this.isBuy = '已订购'
            this.payState = true
            addR.buySuccess()
            if (this.pageData.remarks.handelVal == '1') {
              this.handelShow = true
            } else {
              this.$toast.success('订购成功');
            }
            if (this.pageData.remarks.isZhic === '1') {
              setTimeout(() => {
                this.giveMember()
              }, 1000)
            }
            if (this.pageData.remarks.returnApi && this.pageData.remarks.returnApi !== '' && this.pageData.remarks.returnApi === '1') {
              if (this.pageData.remarks.dispose && this.pageData.remarks.dispose !== '') {
                outsideJs()
              }
            }
            if (this.pageData.remarks.activation && this.pageData.remarks.activation === '1') {
              setTimeout(() => {
                activation()
              }, 1500)

            }
          }
        }, response => {
          if (response.code !== 500) {
            this.showTimeout = true
            addR.overtime()
            if (this.pageData.remarks.returnApi && this.pageData.remarks.returnApi !== '' && this.pageData.remarks.returnApi === '1') {
              if (this.pageData.remarks.dispose && this.pageData.remarks.dispose !== '') {
                outsideJs()
              }
            }
          } else {
            if (response.message.indexOf('已订购') != -1) {
              Dialog({
                message: '您已订购此产品或同类产品',
                theme: 'round-button',
              })
            } else if (response.message.indexOf('欠费') != -1 || response.message.indexOf('停机') != -1 || response.message.indexOf('半停') != -1) {
              Dialog({
                message: '该号码已欠费，请缴费后重新发起',
                theme: 'round-button',
              })
            } else {
              Dialog({
                message: '系统错误',
                theme: 'round-button',
              })
            }
            // if (response.message != "指定时间内重复请求") {
            //   if (response.message == "您已订购，请不要重复订购！" && this.pageData.remarks.orderRepeat && this.pageData.remarks.orderRepeat !== '' && this.pageData.remarks.orderRepeat !== null) {
            //     this.repeatShow = true
            //   } else if (response.message == '调用能力共享平台订购接口异常') {
            //     this.$toast.fail({
            //       message: '当前套餐暂不支持订购该商品',
            //       duration: 5000
            //     })
            //   } else {
            //     this.$toast.fail({
            //       message: response.message,
            //       duration: 5000
            //     })
            //   }
            // }
            addR.buyFail(response)
            this.getIsBuy()
          }
        }).catch(res => {
          console.log(res)
        })
      } else {
        Dialog({
          message: '您不能订购当前产品!',
          theme: 'round-button',
        })
      }
    },
    unloadHandler (e) {
      addR.closePage()   //页面关闭事件
      let startTime = this.dateTime.getTime()
      let endTime = new Date().getTime()
      let duration = endTime - startTime
      localStorage.setItem('duration', duration)
      addR.pageBrowseTime()
      localStorage.removeItem('duration')
    },
    // 短信认证
    toBuy (infoForm) {
      let {
        phone,
        vcode
      } = infoForm;
      addR.buyClick()
      return login({
        phone,
        vcode
      }).then(async res => {
        let flag = this.user.userid === ''
        this.$store.commit('setUser', {
          userid: res.data.userid,
          phone: infoForm.phone
        })
        if (this.param.spid == "1048") { // 对广东用户拦截
          let jixu = await this.getPhoneInfo(res.data.userid)
          if (jixu !== 1) return false
        }

        if (flag) {
          addR.loginSuccess()
          setTimeout(() => {
            addR.getToken()
          }, 500);
        }
        infoForm = {}
        let fromSource = localStorage.getItem('beCome')
        let updata = {
          cpid: this.param.cpid,
          spid: this.param.spid,
          productId: this.pageData.mainProduct.id,
          channelKey: this.pageData.channl.channelKey,
          token: res.data.token ? res.data.token : "0",
          type: '0',
          userid: res.data.userid,
          needJoinActivity: this.pageData.remarks.isZhic === '1' ? 1 : 0,
          fromSource: fromSource,
          anonymousId: this.$sensors.store._state.$device_id,
          testId: this.$store.state.testId,
          testGroupId: this.$store.state.testGroupId,
        }
        this.handel(updata)
      }, res => {
        this.$toast(res.message);
      })
    },
    // 简单认证
    async toNewBuy (infoForm) {
      let {
        vcode
      } = infoForm;
      addR.buyClick()
      if (this.pageData.interceptRule !== "1") {
        let fromSource = localStorage.getItem('beCome')
        let updata = {
          cpid: this.param.cpid,
          spid: this.param.spid,
          productId: this.pageData.mainProduct.id,
          channelKey: this.pageData.channl.channelKey,
          type: '0',
          userid: this.user.userid,
          vcode: vcode,
          anonymousId: this.$sensors.store._state.$device_id,
          fromSource: fromSource,
          needJoinActivity: this.pageData.remarks.isZhic === '1' ? 1 : 0,
          testId: this.$store.state.testId,
          testGroupId: this.$store.state.testGroupId,
          subchannel: this.pageData.channl.fullCode
        }
        if (this.pageData.remarks.returnApi && this.pageData.remarks.returnApi !== '' && this.pageData.remarks.returnApi === '0') {
          if (this.pageData.remarks.dispose && this.pageData.remarks.dispose !== '') {
            outsideJs()
          }
        }
        addR.getToken()
        if (this.param.spid == "1048") { // 对广东用户拦截
          let jixu = await this.getPhoneInfo(this.user.userid)
          if (jixu !== 1) return false
        }
        postNewBuy(updata).then(res => {
          if (res.code == 10000) {
            this.isBuy = '已订购'
            this.payState = true
            this.$toast.success('订购成功');
            infoForm = {}
            if (this.pageData.remarks.isZhic === '1') {
              setTimeout(() => {
                this.giveMember()
              }, 1000)
            }
            if (this.pageData.remarks.returnApi && this.pageData.remarks.returnApi !== '' && this.pageData.remarks.returnApi === '1') {
              if (this.pageData.remarks.dispose && this.pageData.remarks.dispose !== '') {
                outsideJs()
              }
            }
            if (this.pageData.remarks.activation && this.pageData.remarks.activation === '1') {
              setTimeout(() => {
                activation()
              }, 1500)
            }
            addR.buySuccess()

          }
        }, response => {
          if (response.code !== 500) {
            this.showTimeout = true
            addR.overtime()
            if (this.pageData.remarks.returnApi && this.pageData.remarks.returnApi !== '' && this.pageData.remarks.returnApi === '1') {
              if (this.pageData.remarks.dispose && this.pageData.remarks.dispose !== '') {
                outsideJs()
              }
            }
          } else {
            // let message = response.message
            // if (response.message == "您已订购，请不要重复订购！" && this.pageData.remarks.orderRepeat && this.pageData.remarks.orderRepeat !== '' && this.pageData.remarks.orderRepeat !== null) {
            //   this.repeatShow = true
            // } else if (response.message == '调用能力共享平台订购接口异常') {
            //   this.$toast.fail({
            //     message: '当前套餐暂不支持订购该商品',
            //     duration: 5000
            //   })
            // } else {
            //   if (message === "短信校验出现问题{token}为空->验证码有误或失效，请重新获取") {
            //     this.$toast.fail({
            //       message: "验证码已失效，请重新获取"
            //     })
            //   } else {
            //     this.$toast({
            //       message: message
            //     })
            //   }

            // }
            if (response.message.indexOf('已订购') != -1) {
              Dialog({
                message: '您已订购此产品或同类产品',
                theme: 'round-button',
              })
            } else if (response.message.indexOf('欠费') != -1 || response.message.indexOf('停机') != -1 || response.message.indexOf('半停') != -1) {
              Dialog({
                message: '该号码已欠费，请缴费后重新发起',
                theme: 'round-button',
              })
            } else {
              if (response.message.indexOf('验证码') != -1) {
                Dialog({
                  message: '验证码有误，请稍后重试',
                  theme: 'round-button',
                })
              } else if (response.message.indexOf('非联通') != -1) {
                Dialog({
                  message: '仅支持联通号码订购',
                  theme: 'round-button',
                })
              } else {

              }
            }
            addR.buyFail(response)
            this.getIsBuy()
          }
        }).catch(res => {
          console.log(res)
        })
      } else {
        Dialog({
          message: '您不能订购当前产品!',
          theme: 'round-button',
        })
      }
    },
    // 直接领取会员
    giveMember () {
      let updata = {
        activeType: this.pageData.mainProduct.activeType,
        userid: this.user.userid,
        channelKey: this.pageData.channl.channelKey,
        isCompositeProduct: this.pageData.mainProduct.isCompositeProduct,
      };
      addR.memberClick();
      memberGive(updata).then((res) => {
        addR.memberSuccess();
        this.$toast.success('会员领取成功');
      }, (response) => {
        if (this.memberNum == 0) {
          if (response.message == '用户为无效订购状态不能赠送会员') {
            this.memberShow = true
          } else {
            this.$toast(response.message);
          }
        } else {
          this.memberCode = true
        }
        addR.memberFail(response);
      }
      ).catch(() => {
        this.$toast.fail('会员领取失败，请手动领取')
      });
    },
    // 刷新订购状态
    getIsBuy () {
      if (this.pageData.remarks.dispose && this.pageData.remarks.dispose !== '') {
        this.pageData.remarks.dispose.split(',').forEach(val => {
          if (val === 'ksJhuo' || val === 'kuaishou') {
            activation()
          }
        })
      }
      if (this.user.userid) {
        orderList({
          userid: this.user.userid,
          cpid: this.param.cpid,
          spid: this.param.spid,
        }).then((res) => {
          // console.log(res)
          let data = res.data;
          if (data.length === 0) {
            this.getBuyList('未订购')
          } else {
            for (let i = 0; i < data.length; i++) {
              if (data[i].STATUS === "0") {
                this.isBuy = "已订购";
              } else {
                this.getBuyList('已退订')
              }
            }
          }
        });
      }
    },
    // 查询关联产品订购记录
    async getBuyList (isBuy) {
      let arr = []
      if (this.pageData.mainProduct.cacheSeatOne[0].relationIds && this.pageData.mainProduct.cacheSeatOne[0].relationIds != '') {
        let ids = this.pageData.mainProduct.cacheSeatOne[0].relationIds.split(',')
        for (let j = 0; j < ids.length; j++) {
          let info = await detMainProduct({ productId: ids[j] })
          let obj = {
            userid: this.user.userid,
            spid: info.data.spid,
            cpid: info.data.cpid
          }
          await orderList(obj).then(result => {
            if (result.data.length > 0) {
              arr = result.data
              return false
            }
          })
        }
      } else {
        this.isBuy = isBuy
      }
      if (arr.length > 0) {
        arr.forEach(val => {
          if (val.STATUS === "0") {
            this.isBuy = "已订购";
          } else {
            this.isBuy = "已退订";
          }
        })
      } else {
        this.isBuy = isBuy
      }
    },
    // 客户端免流激活
    jihuo (val) {
      if (val === '点击激活') {
        addR.flowJihuo()
      }
      let userid = this.user.userid
      if (userid) {
        activation()
      } else {
        this.type = 'jihuo'
        this.showLogin = true
      }

    },
    // 号段匹配
    number (userid) {
      numberSearch({
        userId: userid
      }).then(res => {
        if (res.data.authType !== null) {
          let pageData = {
            mainProduct: this.pageData.mainProduct,
            strategyInfo: this.pageData.strategyInfo,
            remarks: this.pageData.remarks,
            channl: {
              channelKey: this.pageData.channl.channelKey,
              channelName: this.pageData.channl.channelName,
              fullCode: this.pageData.channl.fullCode,
            },
            recommend: this.pageData.recommend,
          };
          pageData.remarks.attestation = Number(res.data.authType)
          this.$store.commit("setPageData", pageData);
        }
      })
      this.getIsBuy()
    },
    // 免登匹配
    userMatch () {
      let {
        mappid,
        userid,
        ticket
      } = util.query2obj(location.search)
      // alert(ticket)
      if (mappid) {
        changeBackUserid({
          userid: decodeURIComponent(mappid),
          cpid: this.pageData.mainProduct.cpid
        }).then(res => {
          // this.$sensors.registerPage({
          //     attr3: "外链活动"
          // });
          // localStorage.setItem('beCome', '盲盒活动')
          this.$store.commit('setUser', {
            userid: res.data.userid,
            phone: res.data.phone
          })
          addR.loginSuccess()
          if (res.data.userid) {
            this.number(res.data.phone)
          }
        })
        return false
      }
      if (userid) {
        changeUseridToPhone({
          userid: decodeURIComponent(userid)
        }).then(res => {
          this.$store.commit('setUser', {
            userid: decodeURIComponent(userid),
            phone: res.data
          })
          if (this.pageData.remarks.attestation != 0) {
            this.phone = res.data
          }
          addR.loginSuccess()
          this.number(res.data)
        })
      } else if (localStorage.getItem('phone')) {
        this.number(localStorage.getItem('phone'))
        this.phone = localStorage.getItem('phone')
      }
      if (this.pageData.remarks.dispose && this.pageData.remarks.dispose !== '') {
        this.pageData.remarks.dispose.split(',').forEach(val => {
          if (val === 'ksInfo' || val === 'kuaishou') {
            if (this.$store.state.global.js === 0) {
              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);
            }
          } else if (val === 'bili') {
            biliUser()
          } else if (val === 'tencent') {
            if (QQVideoBridge.auth) {
              QQVideoBridge.auth()
            }
          } else if (val === "ticket") {
            if (ticket) {
              ssotoken({ ticket: ticket }).then(res => {
                if (res.code == 10000) {
                  let data = JSON.parse(res.data)
                  this.$store.commit('setUser', {
                    userid: data.user_id,
                    phone: data.phone
                  })
                  if (this.pageData.remarks.attestation != 0) {
                    this.phone = data.phone
                  }
                  addR.loginSuccess()
                  this.number(data.phone)
                }
              })
            }
          } else if (val === 'aqy') {
            if (this.$route.query.token) {
              let token = this.$route.query.token
              aqyUser({
                orderId: token
              }).then(res => {
                if (res.code === 10000) {
                  this.$store.commit("setUser", {
                    userid: res.data.userId,
                    phone: res.data.phone,
                  });
                  this.phone = res.data.phone
                  this.number(res.data.phone)
                }
              })
            }
          }
        })
      }
    },

    getPhoneInfo (userid) {  //验证归属地 拦截广东用户 优酷合约专用
      let pResult = new Promise((resolve, reject) => {
        getPhoneAddres({
          userId: decodeURIComponent(userid),
        }).then((res) => {
          if (res.data.province == "广东") {
            Dialog({
              message: '由于系统升级原因，请广东用户到“联通畅视”公众号进行订购',
              theme: 'round-button',
            })
            resolve(2);
          } else {
            resolve(1);
          }
        }).catch(err => {
          resolve(1);
        });

      })
      return pResult;
    },
    // 活动链接跳转
    onGoLink () {
      if (this.pageData.strategyInfo.activityType === 99) {
        window.location.href = this.pageData.strategyInfo.linkUrl;
      } else {
        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 {
            // 临时调整  为无活动适配跳转
            let url = this.pageData.strategyInfo.linkUrl;
            window.location.href = url;
          }
        } else {
          this.loginType = " 登录 ";
          this.showLogin = true;
          addR.loginClick();
        }
      }
    },
    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.cacheSeatOne[0].memberUrl && this.pageData.mainProduct.cacheSeatOne[0].memberUrl !== "") {
          if (this.isApplet == false) {
            if (this.pageData.mainProduct.cacheSeatOne[0].memberUrl.includes('http')) {
              window.location.href = this.pageData.mainProduct.cacheSeatOne[0].memberUrl;
            } else {
              window.location.href = "https://cs.mige.tv/H"
            }
            return false;
          } else {
            if (this.pageData.mainProduct.cacheSeatOne[0].memberUrl.includes('http')) {
              window.location.href = "https://cs.mige.tv/H"
            } else {
              wx.miniProgram.navigateTo({
                url: this.pageData.mainProduct.cacheSeatOne[0].memberUrl
              })
            }

            return false;
          }

        } else {
          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,
        },
      });
    },
    //net取号
    getNetUrl () {
      getUrl({}).then(res => {
        if (res.code == 10000) {
          this.netIfream(JSON.parse(res.data).url)
        }
      })
    },
    netIfream (url) {
      this.isNet = true
      let iframe = document.createElement('iframe');
      let bodyDom = document.getElementById('temp');
      iframe.id = 'iframe'
      iframe.classList.add('iframe')
      iframe.src = url
      this.iframeNet = iframe
      bodyDom.insertBefore(iframe, bodyDom.lastChild)
    },
    getPhoneNet (e) {
      this.isNet = false
      this.iframeNet.remove();
      phoneNet({ phone: e }).then(res => {
        if (res.code == 10000) {
          localStorage.setItem('phone', res.data)
          this.phone = res.data
          this.$store.commit("setUser", {
            userid: "",
            phone: res.data,
          });
          setTimeout(() => {
            this.openIframe()
          }, 1000)
        }
      })
    },
    //流量产品获取sgin
    llgetSgin () {
      ll.getllSgin(this.channelInfo.fes, this.channelInfo.sou).then(res => {
        if (res.code == 10000) {
          if (res.data.resultCode == '0000') {
            this.$store.commit('setFog', res.data.product[0].fog)
          } else {
            this.$toast({
              message: res.data.errorInfo,
              duration: 0
            })
          }

        } else {
          this.$toast({
            message: "获取失败",
            duration: 0
          })
        }
      })
    }

  }
}
