import {
  postBuy,
  orderList,
  searchResult,
  changeBackUserid,
  changeUseridToPhone,
  memberGive,
  getCode,
  login,
  seniorStrategy,
  strategyGetID,
  postByte
} from '../api'
import util from '../util'
import addR from "../common/addRecord";
import {
  Dialog
} from 'vant';
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: "",
      },
      loginForm: {
        phone: "",
        vcode: "",
      },
      codeState: {
        state: false,
        time: 60,
        task: null,
      },
      payState: false,
      iframe: {},
      showZhezhao: false,
      showTimeout: false,
      callback: "",
      // 临时实现
      bgc: '#ffffff',
      showVcode: false,
      dateTime: new Date()
    }
  },
  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
    }
  },
  created() {
    addR.openPage() // 页面打开事件
    let {
      mappid,
      callback,
      userid,
      tid
    } = 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 (userid) {
      changeUseridToPhone({
        userid: decodeURIComponent(userid)
      }).then(res => {
        this.$store.commit('setUser', {
          userid: decodeURIComponent(userid),
          phone: res.data
        })
        addR.loginSuccess()
      })
    }
    if (callback) {
      this.callback = callback;
    }

    if (tid) { // 任务id获取
      this.$sensors.registerPage({
        taskid: tid
      });
      //  addr相关埋点也需要增加该参数  旭哥在改接口  今天更新
      this.$store.commit('setTid', tid)
    }
  },
  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));
    }
  },
  methods: {
    onSearchResult() {
      let fromSource = localStorage.getItem('beCome')
      searchResult({
        anonymousId: this.$sensors.store._state.$device_id, //cap接口新增神策id
        testId: this.$store.state.testId,
        testGroupId: this.$store.state.testGroupId,
        productId: this.pageData.mainProduct.id,
        cpid: this.param.cpid,
        spid: this.param.spid,
        userid: this.user.userid,
        fromSource: fromSource,
        needJoinActivity: this.pageData.remarks.isZhic === '1' ? 1 : 0,
      })
      this.showTimeout = true
      this.getIsBuy()
    },
    checkVcode() {
      if (this.loginForm.vcode.length > 6) {
        this.loginForm.vcode = this.loginForm.vcode.slice(0, 6);
      }
    },
    openIframe() {
      document.body.style.overflow = 'hidden';
      var that = this
      // if (!localStorage.getItem('key')) {
      //   this.$toast.fail('渠道无效')
      //   return false
      // }
      this.$toast.loading({
        message: '请求中...'
      });
      let now = Date.now()
      that.param.timestamp = now
      if (that.phone) {
        that.param.phone = that.phone
      }
      that.param.sign = that.$md5(this.param.cpid + now + '!QAZ2wsx')
      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) {
      this.iframe.remove();
      this.showZhezhao = false
      // this.$sensors.login(decodeURIComponent(data.userid))
      addR.getToken()

      let params = {
        anonymousId: this.$sensors.store._state.$device_id,
        channleKey: localStorage.getItem("key"),
        spId: this.param.spid,
        userId: decodeURIComponent(data.userid),
      };
      let item = await seniorStrategy(params);
      if (item.data !== null) {
        // 判断高级策略是否开启遮罩;
        if (item.data.enableMask !== null) {
          this.pageData.remarks.isMask = String(item.data.enableMask);
          // 判断高级策略是否有遮罩文案 并替换
          if (item.data.maskText !== null && item.data.maskText !== "") {
            this.pageData.remarks.maskText = item.data.maskText;
          }
        }
        // 判断高级策略是否开启有推荐
        if (
          item.data.recommendStrategy !== "" &&
          item.data.recommendStrategy !== null
        ) {
          let itemList = item.data.recommendStrategy.split(",");
          this.pageData.recommend = [];
          itemList.forEach((v) => {
            strategyGetID({
              id: v,
            }).then((resp) => {
              this.pageData.recommend.push(resp.data);
            });
          });
        }
        if (item.data.cancelRule !== "" && item.data.cancelRule !== null) {
          this.pageData.strategyInfo.unsubscribeStrategyList =
            item.data.cancelRule.split(",");
        }
        if (item.data.interceptRule === "1") {
          this.pageData.interceptRule = item.data.interceptRule;
        }
        if (item.data.location !== "" && item.data.location !== null) {
          this.pageData.location = item.data.location.split(",");
        }
      }
      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,
          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,
        }
        await postBuy(updata).then(res => {
          if (res.code == 10000) {
            this.isBuy = '已订购'
            this.payState = true
            addR.buySuccess()
            this.$toast.success('订购成功');
            this.postApi()

            if (this.pageData.remarks.isZhic === '1') {
              setTimeout(() => {
                this.giveMember()
              }, 1500)
            }
            if (this.pageData.mainProduct.cpid === 'mangtv16') {
              setTimeout(() => {
                window.location.href = this.pageData.mainProduct.flowJumpUrl
              }, 1500)

            }
            // if (this.pageData.mainProduct.threshold > 0 && this.pageData.mainProduct.threshold !== null) {
            //   if (res.data.toMember === 1) {
            //     setTimeout(() => {
            //       this.giveMember()
            //     }, 1500)
            //   }
            // } else {
            //   if (this.pageData.remarks.isZhic === '1') {
            //     setTimeout(() => {
            //       this.giveMember()
            //     }, 1500)
            //   }
            // }
          }
        }, response => {
          if (response.code !== 500) {
            // this.onSearchResult()
            this.showTimeout = true
            this.postApi()
          } 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() {
      let {
        phone,
        vcode
      } = this.loginForm;
      if (!/^1[23456789]\d{9}$/.test(phone)) {
        return this.$toast("请输入正确手机号");
      }
      if (!vcode) {
        return this.$toast("请输入验证码");
      }
      addR.buyClick()
      return login({
        phone,
        vcode
      }).then(res => {
        clearInterval(this.codeState.task);
        addR.getToken()
        this.codeState.task = null;
        this.codeState.state = false;
        this.codeState.time = 60;
        let flag = this.user.userid === ''
        this.$store.commit('setUser', {
          userid: res.data.userid,
          phone: this.loginForm.phone
        })
        if (flag) {
          addR.loginSuccess()
        }
        this.loginForm = {}
        let params = {
          anonymousId: this.$sensors.store._state.$device_id,
          channleKey: localStorage.getItem("key"),
          spId: this.param.spid,
          userId: res.data.userid,
        };
        seniorStrategy(params).then(item => {
          if (item.data !== null) {
            // 判断高级策略是否开启遮罩;
            if (item.data.enableMask !== null) {
              this.pageData.remarks.isMask = String(item.data.enableMask);
              // 判断高级策略是否有遮罩文案 并替换
              if (item.data.maskText !== null && item.data.maskText !== "") {
                this.pageData.remarks.maskText = item.data.maskText;
              }
            }
            // 判断高级策略是否开启有推荐
            if (
              item.data.recommendStrategy !== "" &&
              item.data.recommendStrategy !== null
            ) {
              let itemList = item.data.recommendStrategy.split(",");
              this.pageData.recommend = [];
              itemList.forEach((v) => {
                strategyGetID({
                  id: v,
                }).then((resp) => {
                  this.pageData.recommend.push(resp.data);
                });
              });
            }
            if (item.data.cancelRule !== "" && item.data.cancelRule !== null) {
              this.pageData.strategyInfo.unsubscribeStrategyList =
                item.data.cancelRule.split(",");
            }
            if (item.data.interceptRule === "1") {
              this.pageData.interceptRule = item.data.interceptRule;
            }
            if (item.data.location !== "" && item.data.location !== null) {
              this.pageData.location = item.data.location.split(",");
            }
          }
        })
        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,
            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,
          }
          postBuy(updata).then(res => {
            if (res.code == 10000) {
              this.isBuy = '已订购'
              this.payState = true
              addR.buySuccess()
              this.$toast.success('订购成功');
              this.postApi()
              if (this.pageData.remarks.isZhic === '1') {
                setTimeout(() => {
                  this.giveMember()
                }, 1500)
              }
              if (this.pageData.mainProduct.cpid === 'mangtv16') {
                setTimeout(() => {
                  window.location.href = this.pageData.mainProduct.flowJumpUrl
                }, 1500)
              }
              // if (this.pageData.mainProduct.threshold > 0 && this.pageData.mainProduct.threshold !== null) {
              //   if (res.data.toMember === 1) {
              //     setTimeout(() => {
              //       this.giveMember()
              //     }, 1500)
              //   }
              // } else {
              //   if (this.pageData.remarks.isZhic === '1') {
              //     setTimeout(() => {
              //       this.giveMember()
              //     }, 1500)
              //   }
              // }
            }
          }, response => {
            if (response.code !== 500) {
              // this.onSearchResult()
              this.showTimeout = true
              this.postApi()
            } else {
              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
                })
              }
              // this.$toast.fail({
              //   message: response.message
              // })
              addR.buyFail(response)
              this.getIsBuy()
            }
          }).catch(res => {
            console.log(res)
          })
        } else {
          Dialog({
            message: '您不能订购当前产品!',
            theme: 'round-button',
          })
        }

      }, res => {
        this.$toast(res.message);
      })
    },
    getCode() {
      if (this.codeState.state) return;
      let {
        phone
      } = this.loginForm;
      if (!/^1[23456789]\d{9}$/.test(phone)) {
        return this.$toast("请输入正确手机号");
      }
      if (this.checked === false) {
        return this.$toast.fail("请先勾选隐私声明");
      }
      getCode({
        phone
      }).then(res => {
        this.$toast("验证码已发送");
        this.codeState.state = true;
        this.codeState.task = setInterval(() => {
          if (this.codeState.time <= 0) {
            clearInterval(this.codeState.task);
            this.codeState.task = null;
            this.codeState.state = false;
            this.codeState.time = 60;
          } else {
            this.codeState.time--;
          }
        }, 1000);
      }, res => {
        this.$toast(res.message);
      })

    },
    // 直接领取会员
    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() {
      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 = "已退订";
            }
          }
        }
      });
    },
    // 字节埋点回传
    postApi() {
      let apiQuery = util.query2obj(location.search)
      if (apiQuery.clickid) {
        let nowTime = new Date().getTime()
        let params = {
          event_type: "form",
          context: {
            ad: {
              callback: apiQuery.clickid
            },
          },
          timestamp: nowTime
        }
        postByte(params)
      }
    },
  }
}