// packageC/redPacket/redIndex/redIndex.js
var app = getApp();
// import { util } from "../../../utils/util";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    language: '',
    one_url: 'https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/bg_1@2x.png',
    showCart: false,
    tapOne: false,
    setTime: null,
    countdown: '00:00:00',
    link: {},
    bonus: {},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.mid) {
      app._setMid(option.mid);
    }
  },
  golink() {
    // 是否有跳转链接
    if (!app._isTextEmpty(this.data.link.app_advert_url)) {
      if (this.data.type_status.value == 3) {
        // 没观看过，请求记录接口
        let that = this;
        let urlStr = app.getNetAddresss("plugin.red-packet.api.red-packet-logs.set-link-log");
        app._getNetWork({
          url: urlStr,
          data: {
            red_packet_id: that.data.amount.id,
          },
          success: function (resdata) {
            var res = resdata.data;
            if (res.result == 1) {
              try {
                wx.navigateTo({
                  url: that.data.link.app_advert_url,
                });
              } catch (err) {
                wx.reLaunch({
                  url: that.data.link.app_advert_url,
                });
              }
            }
          },
          fail: function (res) {
            setTimeout(() => {
              that.setData({
                tapOne: false
              });
            }, 1000);
            console.log(res);
          }
        });
      } else {
        // 已经观看过了，不请求接口
        try {
          wx.navigateTo({
            url: this.data.link.app_advert_url,
          });
        } catch (err) {
          wx.reLaunch({
            url: this.data.link.app_advert_url,
          });
        }
        return;
      }
    }
  },
  gettap(e) {
    let kid = e.currentTarget.dataset.id;
    if (this.data.redData.type_status.value != 1) {
      if (this.data.redData.type_status.value == 3) {
        app.tips("请先点击顶部图片进行浏览");
      }
      return;
    } else if (this.data.redData.type_status.value == 1) {
      this.getHb(kid);
    }

  },

  // 领取额外奖励
  receiveBonus () {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.red-packet.api.red-packet-logs.receiveBonus");
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 0) {
          wx.showToast({
            title: res.msg,
            icon: 'none'
          });
        } else {
          that.setData({
            linMoney: Number(res.data.amount).toFixed(2),
            showCart: true
          });
          this.getData();
        }
      },
      fail: function (res) {
        wx.showToast({
          title: res,
          icon: 'none'
        });
        console.log(res);
      }
    });
  },

  trggleCart(e) {
    this.setData({
      showCart: false
    });
    this.getData();
  },
  closeShow(e) {
    this.setData({
      show1: false
    });
  },
  golingqu(e) {
    let tag = e.currentTarget.dataset.tag;
    wx.navigateTo({
      url: '/packageC/redPacket/get_red_record/get_red_record?tag='+ tag,
    });
  },
  goedu(e) {
    wx.navigateTo({
      url: '/packageC/redPacket/red_amount/red_amount',
    });
  },
  goRank() {
    wx.navigateTo({
      url: '/packageC/redPacket/redRank/redRank',
    });
  },
  tapGo(e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/packageA/detail_v2/detail_v2?id=' + id,
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync('langIndex');
    this.setData({
      'language': language.en
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getData();
    this.getShare();
  },


  /**
   * 用户点击右上角分享
   */
  onShareTimeline: function () {
    var value = wx.getStorageSync('yz_uid');
    var mid = '';
    if (value) {
      mid = value;
    }
    return {
      title: this.data.share_title,
      query: 'mid=' + mid,
      imageUrl: this.data.share_pictures
    };
  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var value = wx.getStorageSync('yz_uid');
    var mid = '';
    if (value) {
      mid = value;
    }
    return {
      title: this.data.share_title,
      path: '/packageC/redPacket/daily_red/daily_red?mid=' + mid,
      imageUrl: this.data.share_pictures
    };
  },
  getData() {
    wx.showLoading({
      title: '加载中',
    });
    let that = this;
    let urlStr = app.getNetAddresss("plugin.red-packet.api.red-packet-logs.index");
    app._postNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          wx.hideLoading({
            success: (res) => {},
          });
          that.setData({
            redData: res.data,
            amount: res.data.amount,
            receive_log: res.data.receive,
            // 自定义背景颜色
            bjcolor: res.data.color,
            // receive_color:res.data.receive_color,
            link: res.data.link,
            type_status: res.data.type_status,
            // 红包剩余额度
            syMun: (res.data.receive.amount_sum - res.data.receive.receive_amount).toFixed(2),
            content: res.data.content,
            goods_list: res.data.goods_list,
            // 额外奖金
            bonus: res.data.bonus,
          });
          wx.setNavigationBarTitle({
            title: res.data.red_packet_title
          });
          if (that.data.syMun) {
            that.setData({
              bfbMum: (Number(res.data.receive.receive_amount) / Number(res.data.receive.amount_sum).toFixed(2) * 100)
            });
          }
          if (that.data.type_status.value == 2 && that.data.redData.business_hours_start != 0 && !app._isTextEmpty(that.data.redData.business_hours_start) && that.data.redData.business_hours_start != null) {
            var timestamp = (new Date()).getTime();
            let date = new Date();
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();
            // 可以领取红包的时间
            let assgin_hours = `${year}/${month}/${day} ${res.data.business_hours_start}:00`;
            assgin_hours = Date.parse(assgin_hours);
            let Difference = Number(assgin_hours) - Number(timestamp);
            that.setData({
              Difference: Difference
            });
          }

        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  finished(e) {
    console.log('倒计时结束');
    this.getData();
  },
  daojishi() {
    var that = this;
    let millisecond = this.data.Difference;
    console.log(millisecond);
    this.data.setTime = setInterval(function () {
      console.log('循环中');
      millisecond -= 1000;
      if (millisecond <= 0) {
        clearInterval(that.data.setTime);
        that.setData({
          statusa: 0
        });
        return;
      }
      that.transformRemainTime(millisecond);
      console.log(that.data.countdown, '这是时分秒');
    }, 1000);

  },
  transformRemainTime: function (millisecond) {
    var that = this;
    // var countdownObj = that.data.countdown;
    // 秒数
    var seconds = Math.floor(millisecond / 1000);
    console.log(seconds);
    console.log(Math.floor(seconds / 3600 / 24));
    // 天数
    let day = that.formatTime(Math.floor(seconds / 3600 / 24));
    console.log(day);
    // 小时
    let hour = that.formatTime(Math.floor(seconds / 3600 % 24));
    // // 分钟
    let minute = that.formatTime(Math.floor(seconds / 60 % 60));
    // // 秒
    let second = that.formatTime(Math.floor(seconds % 60));
    if (day == '00') {
      that.setData({
        countdown: `${hour}:${minute}:${second}`
      });
    } else {
      that.setData({
        countdown: `${day}:${hour}:${minute}:${second}`
      });
    }

  },
  //格式化时间为2位
  formatTime: function (time) {
    console.log(time);
    if (time < 10) {
      return '0' + time;
    } else {
      return time;
    }
  },
  getHb(id) {
    if (this.data.link.is_advert && !this.data.link.is_browse) {
      wx.showModal({
        title: '请先点击顶部图片进行浏览!',
        icon: 'none',
        duration: 1500,
        showCancel: false
      });
      return;
    }
    if (this.data.tapOne) {
      console.log('正在领取');
      return;
    }
    this.setData({
      tapOne: true
    });
    let that = this;
    that.getData(id);
    let urlStr = app.getNetAddresss("plugin.red-packet.api.red-packet-logs.memberAmount");
    app._getNetWork({
      url: urlStr,
      data: {
        red_packet_id: id,
        uid: wx.getStorageSync('yz_uid')
      },
      success: function (resdata) {
        var res = resdata.data;
        console.log(res.data);
        that.setData({
          linMoney: Number(res.data).toFixed(2),
          backsta: true
        });
        setTimeout(() => {
          that.setData({
            tapOne: false
          });
        }, 1000);
        if (res.result == 0) {
          that.setData({
            showCart: false
          });

          wx.showToast({
            title: res.msg,
            icon: 'none'
          });
        } else {
          if (res.data.price) {
            if (res.data.price == '0') {
              that.setData({
                showCart: false
              });
              wx.showToast({
                title: res.msg,
                icon: 'none'
              });
            }
          } else {
            that.setData({
              showCart: true
            });
          }
        }
      },
      fail: function (res) {
        setTimeout(() => {
          that.setData({
            tapOne: false
          });
        }, 1000);
        console.log(res);
      }
    });
  },
  getShare() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.red-packet.api.red-packet-logs.share");
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        console.log(res);
        that.setData({
          share_title: res.data.share_title,
          share_content: res.data.share_content,
          share_pictures: res.data.share_pictures
        });
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  goqg(e) {
    console.log(e);
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/packageA/detail_v2/detail_v2?id=' + id,
    });

  }
});