// packageH/blindBox/blindBoxDetail/blindBoxDetail.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    currentTime: parseInt(new Date().getTime() / 1000),
    timeData: {},
    checked: false,
    //组合商品弹窗
    multiplePopupInfo: {
      title: "",
      info: {},
      show: false
    },

    //商品详情弹窗
    goodsDetailsPopupInfo: {
      show: false,
      info: {}
    },

    //单商品弹窗
    singlePopupInfo: {
      title: "",
      show: false,
      info: {}
    },
    //海报弹窗信息
    posterPopupInfo: {
      show: false,
      src: ''
    },
    contactShow: false, //联系我们 弹窗
    friendsShow: false,
    seePrizeShow: false,
    seePrizeAnimation: false,

    gifShow: false, //动图显示

    goods: [], //商品
    activity: {}, //盲盒详情
    assist: {}, //助力信息
    member: {}, //个人信息

    timer: null, //抽奖倒计时对象
    luckdrawCountDown: 0, //抽奖倒计时

    isBlindBoxTap: true, //盲盒抽取按钮
    isBlindBoxTapPay: false, //盲盒付费按钮
    isInvitePlan: false, //盲盒邀请好友按钮
    isAddress: false, //填写地址按钮

    integral: "积分",

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      if (scene) {
        var info_arr = [];
        info_arr = scene.split(",");
        for (let i = 0; i < info_arr.length; i++) {
          let chil_arr = [];
          chil_arr = info_arr[i].split("=");
          if (chil_arr[0] == "mid") {
            app._setMid(chil_arr[1]);
          }
          if (chil_arr[0] == "id") {
            this.setData({
              id: chil_arr[1],
            });
          }
        }
      }
    }
    if (options.ids) {
      this.getBlindBoxGoods(options.ids);
    }
    if (options.id) {
      this.setData({
        id: options.id
      });
      // this.getData();
    }

    let value = wx.getStorageSync('integral');
    if (value) {
      this.setData({
        integral: value
      });
    }
  },
  onChange(e) {
    this.setData({
      timeData: e.detail,
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  // drawTap() {
  //   this.setData({
  //     gifShow: true
  //   })
  // },
  previewImage: function (e) {
    console.log('浏览图片');
    var current = this.data.activity.cservice_code_src; //这里获取到的是一张本地的图片
    wx.previewImage({
      current: current, //需要预览的图片链接列表
      urls: [current] //当前显示图片的链接
    });
  },
  previewImagesss() {
    var current = this.data.posterPopupInfo.src; //这里获取到的是一张本地的图片
    wx.previewImage({
      current: current, //需要预览的图片链接列表
      urls: [current] //当前显示图片的链接
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.animation = wx.createAnimation({
      duration: 3000,
      timingFunction: 'ease',
    });
    console.log(this.data.timer);
    if (this.data.id) {
      if (this.data.timer) {
        clearInterval(this.data.timer);
      }
      this.getData();
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log('asdasdasdassdadasd');
    clearInterval(this.data.timer);

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let that = this;
    // 免费
    let assist_id = this.data.assist.id;
    let member_id = this.data.assist.member_id;
    let _path = '/packageH/blindBox/blindBoxHelping/blindBoxHelping?assist_id=' + assist_id + '&member_id=' + member_id; //免费去协助路径
    let pricePath = 'packageH/blindBox/blindBoxDetail/blindBoxDetail?id=' + that.data.id; //付费的路径
    // that.data.activity.activity_type == 0是付费，1是免费
    return {
      title: that.data.activity.activity_name ? that.data.activity.activity_name : '',
      path: that.data.activity.activity_type ? _path : pricePath,
      imageUrl: that.data.activity.activity_img_src ? that.data.activity.activity_img_src : ''
    };

  },
  callPhone() {
    let that = this;
    wx.makePhoneCall({
      phoneNumber: that.data.activity.cservice_phone //仅为示例，并非真实的电话号码
    });
  },
  // 我的订单
  goOrder() {
    wx.navigateTo({
      url: '/packageA/member/myOrder_v2/myOrder_v2?status=0',
    });
  },
  contactShowTap() {
    this.setData({
      contactShow: true
    });
  },
  contactShowClose() {
    this.setData({
      contactShow: false
    });
  },
  getData() {
    let that = this;
    let urlStr = app.getNetAddresss('plugin.blind-box.api.index.activity-info');
    app._postNetWork({
      url: urlStr,
      data: {
        id: this.data.id
      },
      success: (resdata) => {
        let res = resdata.data;
        wx.hideLoading({
          success: (res) => {},
        });
        if (res.result == 1) {
          that.setData({
            goods: res.data.goods,
            activity: res.data.activity,
            assist: res.data.assist,
            member: res.data.member,
          });
          let html = that.data.activity.activity_rule.replace(/<img/g, '<img style="width:100%"');
          that.setData({
            ['activity.activity_rule']: html
          });
          // wx.setNavigationBarTitle({
          //   title: res.data.activity.activity_name,
          // })
          if (that.data.assist && that.data.assist.expire) {
            console.log("currentTime", that.data.currentTime, that.data.assist.expire);
            if (that.data.currentTime <= that.data.assist.expire || that.data.assist.status == 1) {
              that.setData({
                isBlindBoxTap: false,
                isInvitePlan: true
              });
              // that.initShare();
              return;
            }
          }
          that.setData({
            luckdrawCountDown: that.data.activity.extract_time
          });
          this.startLuckCountDown();
        } else {
          console.log(res);
        }
      },
      fail: function (res) {
        console.log(res.msg);
      }
    });
  },
  //开始倒计时
  startLuckCountDown() {
    let that = this;
    that.data.timer = setInterval(() => {
      if (that.data.luckdrawCountDown <= 0) {
        clearInterval(that.data.timer);
        return;
      }
      that.setData({
        luckdrawCountDown: that.data.luckdrawCountDown - 1
      });
    }, 1000);
  },
  freePrize() {
    let that = this;
    setTimeout(() => {
      that.setData({
        seePrizeAnimation: true
      });
      setTimeout(() => {
        that.setData({
          gifShow: false
        });
      }, 500);
      // setTimeout(() => {
      //   that.setData({
      //     isInvitePlan: false,
      //     seePrizeShow: false,
      //     isAddress: true,
      //     gifShow: false,
      //     seePrizeAnimation:false
      //   })
      // }, 3500);
    }, 1500);
    that.setData({
      gifShow: true,
      seePrizeShow: true,
      isAddress: true
    });
  },
  // 开始抽奖
  startLuckDraw() {
    let that = this;
    if (that.data.luckdrawCountDown <= 0) {
      wx.showToast({
        title: '请刷新或重新进入',
        duration: 1000,
        icon: 'none'
      });
      return;
    }
    that.addJoinLog();
    if (that.data.activity.activity_type == 0) {

      setTimeout(() => {
        that.setData({
          seePrizeAnimation: true
        });
        setTimeout(() => {
          that.setData({
            gifShow: false
          });
        }, 500);
        // setTimeout(() => {
        //   that.setData({
        //     isBlindBoxTap: false,
        //     seePrizeShow: false,
        //     gifShow: false,
        //     seePrizeAnimation:false
        //   })
        // }, 3500);
      }, 1500);
      that.setData({
        gifShow: true,
        isBlindBoxTapPay: true,
        seePrizeShow: true
      });
    } else if (that.data.activity.activity_type == 1) {
      //免费
      this.generateAssist();
    }
  },
  addJoinLog() {
    let that = this;
    let urlStr = app.getNetAddresss('plugin.blind-box.api.index.join-log');
    app._postNetWork({
      url: urlStr,
      data: {
        id: that.data.activity.id
      },
      success: (resdata) => {},
      fail: function (res) {
        console.log(res.msg);
      }
    });
  },
  //免费-第一次发起助力
  generateAssist() {
    let that = this;
    let urlStr = app.getNetAddresss('plugin.blind-box.api.assist.generate-assist');
    app._postNetWork({
      url: urlStr,
      data: {
        id: that.data.id
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          that.setData({
            isBlindBoxTap: false,
            isInvitePlan: true,
            assist: res.data.assist,
            ['assist.assist_log_count']: res.data.assist.assist_log.length,
            ['assist.status']: 0,
          });
          // that.initShare()
        } else {
          console.log(res);
        }
      },
      fail: function (res) {
        console.log(res.msg);
      }
    });
  },
  seePrizeShowTap() {
    wx.redirectTo({
      url: '/packageH/blindBox/blindBoxDetail/blindBoxDetail?id=' + this.data.id,
    });
  },
  // 再抽一次
  onceMore(e) {
    wx.redirectTo({
      url: '/packageH/blindBox/blindBoxDetail/blindBoxDetail?id=' + this.data.id,
    });
    // let that = this;
    // that.setData({
    //     isBlindBoxTap: false,
    //     seePrizeShow: false,
    //     isBlindBoxTapPay: true,
    //     gifShow: false,
    //     seePrizeAnimation:false
    //   })
    // let urlStr = app.getNetAddresss('plugin.blind-box.api.tips.invalid-tips');
    // app._postNetWork({
    //   url: urlStr,
    //   data: {
    //     id: that.data.id
    //   },
    //   success: (resdata) => {
    //     let res = resdata.data;
    //     if (res.result == 1) {
    //       this.setData({
    //         seePrizeShow: true
    //       })
    //       setTimeout(() => {
    //         that.setData({
    //           seePrizeAnimation:true
    //         })
    //         // setTimeout(() => {
    //         //   that.setData({
    //         //     isBlindBoxTap: false,
    //         //     seePrizeShow: false,
    //         //     isBlindBoxTapPay: true,
    //         //     gifShow: false,
    //         //     seePrizeAnimation:false
    //         //   })
    //         // }, );
    //         setTimeout(() => {
    //           that.setData({
    //             gifShow:false
    //           })
    //         }, 500);
    //       }, 1500)
    //       that.setData({
    //         gifShow: true,
    //         seePrizeShow:true
    //       })
    //     } else {
    //       console.log(res)
    //     }
    //   },
    //   fail: function (res) {
    //     console.log(res.msg)
    //   }
    // });
  },
  openGoodsDetailsPopup(e) {
    console.log(e);
    let item = e.currentTarget.dataset.item;
    this.setData({
      ['goodsDetailsPopupInfo.info']: item,
      ['goodsDetailsPopupInfo.show']: true
    });
    console.log(this.data.goodsDetailsPopupInfo);
  },
  seeCombinationGoods(e) {
    let item = e.currentTarget.dataset.item;
    this.setData({
      ['multiplePopupInfo.info']: item.combination,
      ['multiplePopupInfo.title']: item.combination.combination_name,
      ['multiplePopupInfo.show']: true,
    });
  },
  multiplePopupInfoTap() {
    this.setData({
      ['multiplePopupInfo.show']: false,
    });
  },
  singlePopupInfoTap() {
    this.setData({
      ['singlePopupInfo.show']: false
    });
  },
  // 提示
  seeTips() {
    let that = this;
    if (this.data.activity.tips - this.data.activity.tips_count <= 0) {
      wx.showModal({
        title: `提示一次需要消耗${that.data.activity.tips_consume}${that.data.integral}`,
        content: `当前${that.data.integral}${this.data.member.credit1}`,
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定');
            that.getTips();
          }
        }
      });
      return;
    }
    this.getTips();
  },
  getTips() {
    let that = this;
    let urlStr = app.getNetAddresss('plugin.blind-box.api.tips.get-tips');
    app._postNetWork({
      url: urlStr,
      data: {
        id: that.data.id
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          that.setData({
            ['activity.tips_count']: this.data.activity.tips_count + 1,
            ['singlePopupInfo.title']: '不可能抽中',
            ['singlePopupInfo.info']: res.data.activityGoods,
            ['singlePopupInfo.show']: true
          });
          console.log(this.data.singlePopupInfo);
        } else {
          wx.showToast({
            title: res.msg,
            duration: 1000,
            icon: 'none'
          });
          console.log(res);
        }
      },
      fail: function (res) {
        console.log(res.msg);
      }
    });
  },
  // end
  // 预下单
  gotoOrder(e) {
    console.log(e);
    wx.navigateTo({
      url: '/packageD/buy/myOrder_v2/myOrder_v2?tag=blindBox&goodsId=' + this.data.activity.goods_id + '&at_id=' + this.data.activity.id + '&total=1&optionsId=',
    });
  },
  // 获取抽中的盲盒商品
  getBlindBoxGoods(ids) {
    let that = this;
    let urlStr = app.getNetAddresss('plugin.blind-box.api.index.blind-box-goods');
    app._postNetWork({
      url: urlStr,
      data: {
        order_id: ids
      },
      success: (resdata) => {
        let res = resdata.data;
        wx.hideLoading({
          success: (res) => {},
        });
        if (res.result == 1) {

          if (res.data.combination == null) {
            that.setData({
              ['blindBoxInfo.pattern']: 0
            });
          } else {
            that.setData({
              ['blindBoxInfo.pattern']: 1,
              ['blindBoxInfo.combination']: res.data.combination
            });
          }
          that.setData({
            ['blindBoxInfo.show']: true,
            ['blindBoxInfo.goods']: res.data.goods
          });
        } else {
          console.log(res);
        }
      },
      fail: function (res) {
        console.log(res.msg);
      }
    });
  },

  //海报
  getPoster(e) {
    if (this.data.posterPopupInfo.src != '') {
      // this.data.posterPopupInfo.show=true;
      this.setData({
        ['posterPopupInfo.show']: true
      });
      return;
    }
    let that = this;
    let urlStr = app.getNetAddresss('plugin.blind-box.api.index.poster');
    app._postNetWork({
      url: urlStr,
      data: {
        activity_id: that.data.id,
        ingress: 'weChatApplet'
      },
      success: (resdata) => {
        let res = resdata.data;
        wx.hideLoading({
          success: (res) => {},
        });
        if (res.result == 1) {
          that.setData({
            ['posterPopupInfo.src']: res.data.poster,
            ['posterPopupInfo.show']: true
          });
        } else {
          console.log(res);
          wx.showToast({
            title: res.meg,
            duration: 1000,
            icon: 'none'
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      }
    });
  },
  posterPopupInfoClose() {
    this.setData({
      ['posterPopupInfo.show']: false
    });
  }
});