// pages/member/ClockPunch/ClockPunch.js
var yz_pay = require("../../../mycomponent/yz_pay/yz_pay");
var app = getApp();
Page({
  behaviors: [yz_pay],
  /**
   * 页面的初始数据
   */
  data: {
    language: '',
    //总共余额
    totalAmonut: "",
    //总共参与人数
    totalNumber: "",
    //总共参与会员
    totalMember: [],
    //已打卡数量
    clockInNum: 0,
    clockFirstShow: false,
    //第一名打卡会员
    clockFirstMember: {},
    luckyMemberShow: false,
    //连续打卡会员
    continueMember: {},
    continueMemberShow: false,
    //未打卡数量
    notClockInNum: 0,
    btnStatus: "",
    amount: "1",
    //弹窗按钮控制
    actionSheetShow: false,
    actionSheetItemsData: [],
    clockin_title: "早起打卡",
    share_title: "",
    share_icon: "",
    share_desc: "",
    clock_begintime: "",
    clock_endtime: "",
    ios_virtual_pay: false,
    forbidden: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.checkrouter();
    try {
      var value = wx.getStorageSync('ios_virtual_pay');
      if (value) {
        this.setData({
          ios_virtual_pay: value
        });
      }
    } catch (e) { console.log(e); }
  },
  checkrouter() {
    try {
      // 推广中心是否开启该功能，没开启跳转到指定路径
      let basic_info = wx.getStorageSync("yz_basic_info");
      let stop_info = basic_info.popularize_page.mini.vue_route;
      for (let i = 0; i < stop_info.length; i++) {
        if (stop_info[i] == 'ClockPunch') {
          console.log(basic_info.popularize_page.mini.mini_url + "跳转的路径");
          wx.showToast({
            title: '未开启推广权限',
            duration: 1000,
            icon: 'none',
            success: function () {
              setTimeout(() => {
                wx.redirectTo({
                  url: basic_info.popularize_page.mini.mini_url,
                });
              }, 1000);
            }
          });
          return;
        }
      }
    } catch (e) {
      console.log(e);
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync('langIndex');
    this.setData({ 'language': language.en });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.showShareMenu({
      withShareTicket: false,
      menus: ['shareAppMessage', 'shareTimeline']
    });
    this._initData();
    this._getTodayPay();
    this._getTodayClockOn();
    this._getCurrentPayStatus();
    this._getPayData();
    this._getClockin();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

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

  },

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

  },

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

  },

  /**
   * 用户点击右上角分享
   */
  onShareTimeline() {
    return {
      title: this.data.share_title,
      imageUrl: this.data.share_icon
    };
  },
  onShareAppMessage: function () {
    return {
      title: this.data.share_title,
      imageUrl: this.data.share_icon
    };
  },
  //获取今日支付数据
  _getTodayPay() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.clock-in.api.clock-in.get-today-pay-data");
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            totalAmonut: res.data.today_pay_amount,
            totalNumber: res.data.today_pay_num,
            totalMember: res.data.today_pay_member
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  //获取今日打卡数据
  _getTodayClockOn() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.clock-in.api.clock-in.get-today-clock-data");
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          if (app._isTextEmpty(res.data.clock_firat_member)) {
            that.setData({
              clockFirstShow: false
            });
          } else {
            that.setData({
              clockFirstShow: true,
              clockFirstMember: res.data.clock_firat_member
            });
          }

          if (app._isTextEmpty(res.data.reward_lucky_member)) {
            that.setData({
              luckyMemberShow: false
            });
          } else {
            that.setData({
              luckyMemberShow: true,
              luckyMember: res.data.reward_lucky_member
            });
          }

          if (app._isTextEmpty(res.data.clock_continuity_member)) {
            that.setData({
              continueMemberShow: false
            });
          } else {
            that.setData({
              continueMemberShow: true,
              continueMember: res.data.clock_continuity_member
            });
          }
          that.setData({
            clockInNum: res.data.clock_in_num,
            notClockInNum: res.data.not_clock_in_num
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  //获取当前支付打卡状态
  _getCurrentPayStatus() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.clock-in.api.clock-in.get-member-pay-status");
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            amount: res.data.amount,
            btnStatus: res.data.status
          });
          that.initBtnView(res.data);
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1000
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  //初始化btn状态
  initBtnView(data) {
    let that = this;
    switch (data.status) {
    case -1:
      that.setData({
        message: "支付" + that.data.amount + (that.data.language['元'] ? that.data.language['元'] : '元') + "参与挑战"
      });
      break;
    case 0:
      that.setData({
        message: "支付" + that.data.amount + (that.data.language['元'] ? that.data.language['元'] : '元') + "参与挑战"
      });
      break;
    case 1:
      that.setData({
        forbidden: true,
        cutDownTime: this.getCutDownTime(data)
      });
      that._countDown();
      break;
    case 2:
      that.setData({
        message: '打卡'
      });
      break;
    case 3:
      that.setData({
        forbidden: true,
        cutDownTime: this.getCutDownTime(data)
      });
      that._countDown();
      break;
    case 4:
      that.setData({
        forbidden: true,
        cutDownTime: this.getCutDownTime(data)
      });
      that._countDown();
      break;
    default:
      break;
    }
  },
  //倒计时
  _countDown: function () {
    if (!this.data.forbidden) {
      return false;
    }
    let newTime = new Date().getTime();
    let endTime = this.data.cutDownTime;
    let obj = null;
    if (endTime - newTime > 0) {
      let time = (endTime - newTime) / 1000;
      // 获取天、时、分、秒
      let day = parseInt(time / (60 * 60 * 24));
      let hou = parseInt(time % (60 * 60 * 24) / 3600);
      let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
      let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
      obj = {
        day: this._timeFormat(day),
        hou: this._timeFormat(hou),
        min: this._timeFormat(min),
        sec: this._timeFormat(sec)
      };
    } else { //活动已结束，全部设置为'00'
      obj = {
        day: '00',
        hou: '00',
        min: '00',
        sec: '00'
      };
    }
    this.setData({
      message: '倒计时' + obj.day + '天' + obj.hou + '时' + obj.min + '分' + obj.sec + '秒'
    });
    if (endTime - newTime < 0) {
      this.setData({
        forbidden: false,
      });
      this._getTodayClockOn();
      this._getCurrentPayStatus();
    } else {
      setTimeout(this._countDown.bind(this), 1000);
    }

  },
  //小于10的格式化函数
  _timeFormat(param) { //小于10的格式化函数
    return param < 10 ? '0' + param : param;
  },
  //获取倒计时
  getCutDownTime(data) {
    var currentTime = parseInt(data.current_time);
    var startTime = parseInt(data.start_time);
    var restTime = 0;
    if (currentTime < startTime) {
      restTime = startTime;
    }
    return restTime * 1000;
  },
  //获取支付数据
  _getPayData() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.clock-in.api.clock-in-pay.get-pay-button");
    app._getNetWork({
      url: urlStr,
      success: (resdata)=> {
        var res = resdata.data;
        if (res.result == 1) {
          let btnData = res.data.buttons;
          if (!app._isTextEmpty(btnData) && btnData.length > 0) {
            let actionSheetItemsData = [];
            for (let i = 0; i < btnData.length; i++) {
              actionSheetItemsData.push({
                name: btnData[i].name,
                openType: btnData[i].value
              });
            }
            that.setData({
              actionSheetItemsData: actionSheetItemsData,
            });
          }
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  //初始化支付回调
  initPayCallBack(type) {
    let that = this;
    switch (type) {
    case 1:
      that.weChatPay();
      break;
    case 55:
      that.weChatPay();
      break;
    case 3:
      that.balancePay();
      break;
    case 28:
      that.balanceHjPay();
      break;
    default:
      break;
    }
  },
  //微信支付
  weChatPay() {
    this.payPost(1);
  },
  //余额支付
  balancePay() {
    this.payPost(3);
  },
  // 第三方汇聚支付
  balanceHjPay() {
    this.payPost(28);
  },
  //支付
  payPost(type) {
    let urlStr = app.getNetAddresss("plugin.clock-in.api.clock-in-pay.run-clock-pay");
    urlStr += '&pay_method=' + type;
    urlStr += '&amount=' + this.data.amount;
    urlStr += "&client_type=2";
    app._getNetWork({
      url: urlStr,
      success: (resdata)=> {
        var res = resdata.data;
        if (res.result == 1) {
          this.rechargePay(type, res, res.data.ordersn, 'clock');
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1000
          });
        }
      },
      fail: (res)=> {
        console.log(res);
      }
    });
  },
  clokinBtnCallBack() {
    let that = this;
    if (this.data.ios_virtual_pay) {
      wx.showModal({
        title: '提示',
        content: '十分抱歉，由于相关规定，你暂时无法在这里充值！',
        confirmText: '知道了',
        showCancel: false,
        success(res) {
          console.log(res);
        }
      });
      return false;
    }
    switch (this.data.btnStatus) {
    case -1:
      that.setData({
        actionSheetShow: true
      });
      break;
    case 0:
      that.setData({
        actionSheetShow: true
      });
      break;
    case 1:
      break;
    case 2:
      that.postClockIn();
      break;
    case 3:
      that.setData({
        actionSheetShow: true
      });
      break;
    case 4:
      break;
    default:
      break;
    }
  },
  //打卡
  postClockIn() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.clock-in.api.clock-in.run-clock-in");
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that._getCurrentPayStatus();
          that._getTodayPay();
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1000
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1000
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  actionbtn(e) {
    let openType = e.detail.openType;
    this.initPayCallBack(openType);
  },
  onClose() {
    this.setData({
      actionSheetShow: false
    });
  },
  goClockPunchRule() {
    wx.navigateTo({
      url: '/packageA/member/ClockPunchRule/ClockPunchRule'
    });
  },
  goClockPunchRecord() {
    wx.navigateTo({
      url: '/packageA/member/ClockPunchRecord/ClockPunchRecord'
    });
  },
  //获取早起打卡设置
  _getClockin() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.clock-in.api.clock-in.get-set");
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            clockin_title: res.data.plugin_name,
            share_title: res.data.share.share_title,
            share_icon: res.data.share.share_icon,
            share_desc: res.data.share.share_desc,
            clock_begintime: res.data.clock_time.starttime,
            clock_endtime: res.data.clock_time.endtime,
          });
        } else {
          if(res.data.is_clock_in==0){
            let plugin_name = res.data.plugin_name;
            wx.showModal({
              title: '提示',
              content: `${plugin_name}已禁用`,
              showCancel:false,
              success (res) {
                if (res.confirm) {
                  wx.redirectTo({
                    url: '/packageG/member_v2/member_v2',
                  });
                }
              }
            });

          }
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  _initData() {
    this.setData({
      //总共余额
      totalAmonut: "",
      //总共参与人数
      totalNumber: "",
      //总共参与会员
      totalMember: [],
      //已打卡数量
      clockInNum: 0,
      clockFirstShow: false,
      //第一名打卡会员
      clockFirstMember: {},
      luckyMemberShow: false,
      //连续打卡会员
      continueMember: {},
      continueMemberShow: false,
      //未打卡数量
      notClockInNum: 0,
      btnStatus: "",
      amount: "1",
      //弹窗按钮控制
      actionSheetShow: false,
      actionSheetItemsData: [],
      clockin_title: "早起打卡",
      share_title: "",
      share_icon: "",
      share_desc: "",
      clock_begintime: "",
      clock_endtime: "",
    });
  }
});
