import {
  postBuy,
  postNewBuy,
  orderList,
  changeBackUserid,
  changeUseridToPhone,
  memberGive,
  login,
  aqyUser,
  numberSearch,
  getPhoneAddres
} from '../api'
import util from '../util'
import addR from "../common/addRecord";
import sensors from "sa-sdk-javascript";
import {
  Dialog
} from "vant";
import {
  outsideJs,
  biliUser,
  activation
} from '../api/JS'
export default {
  data () {
    return {
      iframeUrl: process.env.VUE_APP_IFAMRE,
      param: {
        cpid: '',
        spid: '',
        channel: "boyuan",
        channeltype: "1",
        timestamp: "",
        clienttype: "3",
        sign: "",
        phone: "",
        theme: "",
        version: "1.0.0",
        servicephone: "",
      },
      payState: false,
      iframe: {},
      showZhezhao: false,
      showTimeout: false,
      callback: "",
      // 临时实现
      bgc: '#ffffff',
      showVcode: false,
      dateTime: new Date(),
      getIsNum: 0,
      userid: "",
      indexNum: 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
      return this.$store.state.pageData
    }
  },
  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)
    }
    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()
          }
        }

      })
    }
    this.userMatch()
  },
  mounted () {
    var that = this
    let channelKey = that.pageData.channl.channelKey
    if (!channelKey) {
      localStorage.setItem('key', channelKey)
    }
    // 统一认证监听
    window.addEventListener('message', e => {
      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": //处理成功
              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) { }
      }
    }, 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));
    }
    let anonymousId = sensors.store._state.$device_id
    if (anonymousId) {
      this.$store.commit('setAnonymousId', anonymousId)
    }
  },
  methods: {
    openIframe () {
      document.body.style.overflow = 'hidden';
      // outsideJs()
      var that = this
      this.$toast.loading({
        message: '请求中...'
      });
      let now = Date.now()
      that.param.timestamp = now
      that.param.sign = that.$md5(this.param.cpid + now + '!QAZ2wsx')
      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)
      this.iframe = iframe
      addR.buyClick()
      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()
            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
            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 != "指定时间内重复请求") {
              if (response.message == "您已订购，请不要重复订购！" && this.pageData.remarks.orderRepeat && this.pageData.remarks.orderRepeat !== '' && this.pageData.remarks.orderRepeat !== null) {
                this.repeatShow = true
              } 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
            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 (message === "短信校验出现问题{token}为空->验证码有误或失效，请重新获取") {
                this.$toast.fail({
                  message: "验证码已失效，请重新获取"
                })
              } else {
                this.$toast({
                  message: "验证失败,请重试"
                })
              }

            }
            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) => {
            addR.memberFail(response);
            this.$toast(response.message);
          }
        )
        .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) => {
          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 = "已退订";
              }
            }
          }
        });
      }

    },
    // 客户端免流激活
    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,
      } = util.query2obj(location.search)
      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
          })
          addR.loginSuccess()
          this.number(res.data)
        })
      }
      if (localStorage.getItem('phone')) {
        this.number(localStorage.getItem('phone'))
      }
      if (this.pageData.remarks.dispose && this.pageData.remarks.dispose !== '' && this.$route.query.token) {
        this.pageData.remarks.dispose.split(',').forEach(val => {
          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;
    },
  }
}
