// packageA//pages/checkin/checkin.js
var md5 = require("../../../utils/md5.js");
var ut = require("../../../utils/util.js");
const app = getApp();
const os = app.globalData.setting;
let self;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    year: '',
    month: '',
    day: '',
    weekArr: ['日', '一', '二', '三', '四', '五', '六'],
    dateArr: [],
    n_dateArr: [],  //本月的日期
    s_dateArr: [],  //上月的日期

    firstDay: '',
    lastDay: '',
    param: null,
    clockNum: 3,

    res: null,
    isShowRules: false,
    isCheckIn: false,
    checkInDays: 0,			//连续签到天数
    integral: 0,				//积分
    checkInNums: 0,		  //补签次数
    isCheckInDay: '',

    flag: true,
    isLogin: false,
    imgUrl: app.globalData.setting.imghost,
    show_no_integral: false

  },

  loadQd(callback) {
    app.request.get('/api/weshop/qdrecord/getUser/' + app.globalData.setting.stoid + '/' + app.globalData.user_id, {
      success: function (res) {
        if (res.data.code == 0) {
          if (callback) callback();
          self.setData({
            res: res.data.data
          });
          self.loadCheckedRecord();
        } else {
          if (res.data.msg.indexOf('未开启签到') != -1) {
            self.setData({ show_no_integral: true });
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 2000
            })
          }

        }
      },
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('执行onload');
    self = this;
    this.getDate();
    this.setDate();
    var res = wx.getSystemInfoSync();
    this.setData({
      param: res.windowHeight / 12,
    })

    // 判断会员是否授权登录，
    // 没有登录则跳转到登录页，
    // 已登录则设置已登录状态，请求加载签到数据
    this.isLogin().then(function () {
      self.setData({
        isLogin: true
      });
      self.loadQd();
    });

    // 广告
    getApp().request.promiseGet("/api/weshop/ad/page?pid=1205&store_id=" + os.stoid, {
      data: {
        enabled: 1
      }
    }).then(res => {
      if (res.data.code == 0 && res.data.data && res.data.data.pageData && res.data.data.pageData.length > 0) {
        var a = res.data.data.pageData;
        var narr = [];
        for (var i in a) {
          var tt = {
            'ad_code': os.imghost + a[i].ad_code,
            'media_link': '',
            'ad_weapplink': a[i].ad_weapplink
          };
          narr.push(tt);
        }
        self.setData({ ad_data: narr });
      }
    });


  },

  onShow() {
    if (app.globalData.userInfo instanceof Object) {
      if (this.data.isLogin) {
        return;
      } else {
        this.setData({
          isLogin: true
        });
        this.loadQd();
      };
    }
  },

  onHide() {
    console.log('执行onHide');
  },

  // 是否登录
  isLogin() {
    return new Promise(function (resolve, reject) {
      let user_info = getApp().globalData.userInfo;
      if (user_info == null || user_info.mobile == undefined || user_info.mobile == "" || user_info.mobile == null) {
        wx.navigateTo({
          url: '/packageE/pages/togoin/togoin',
        })
        return false;
      } else {
        resolve();
      };
    });
  },

  // 点击"我的积分"和"去购物"进行跳转
  goto(e) {
    let url = e.target.dataset.url;
    app.goto(url);
  },

  // 点击显示签到规则
  showRules() {
    if (this.data.isShowRules) {
      this.setData({
        isShowRules: false
      });
    } else {
      this.setData({
        isShowRules: true
      });
    }
  },


  // 加载签到记录
  loadCheckedRecord() {
    let newDateArr = [];
    let list;
    let bqlist;
    //--判断什么日子是签到的,上个月的--
    if (this.data.res && this.data.res.qdsdaylist) {
      list = this.data.res.qdsdaylist.split(',');
      for (var i in this.data.s_dateArr) {
        var item = this.data.s_dateArr[i];
        if (this.check_is_qd(item, list)) {
          item.isCheckIn = true;
        } else {
          item.isCheckIn = false;
        }
      }
    }
    newDateArr = newDateArr.concat(this.data.s_dateArr);
    //--判断什么日子是签到的，这个月的--
    if (this.data.res && this.data.res.qddaylist) {
      list = this.data.res.qddaylist.split(',');
      for (var i in this.data.n_dateArr) {
        var item = this.data.n_dateArr[i];
        if (this.check_is_qd(item, list)) {
          item.isCheckIn = true;
        } else {
          item.isCheckIn = false;
        }
      }
    }
    newDateArr = newDateArr.concat(this.data.n_dateArr);

    //--判断什么日子是要补签的--
    if (this.data.res && this.data.res.curbqdaynum) {
      bqlist = this.data.res.curbqdaynum.split(',');
      for (var i in newDateArr) {
        var item = newDateArr[i];
        if (this.check_is_bq(item, bqlist)) {
          item.isBq = true;
        } else {
          item.isBq = false;
        }
      }
    }
    this.setData({
      dateArr: newDateArr
    });
  },


  //判断是不是同一个日期，签到的
  check_is_qd(item, bqlist) {
    for (var i in bqlist) {
      var c_item = JSON.parse(JSON.stringify(item));
      if (c_item.num < 10) c_item.num = "0" + c_item.num;
      if (c_item.num == bqlist[i]) {
        return true;
      }
    }
    return false;
  },

  //判断是不是同一个日期,补签到的
  check_is_bq(item, bqlist) {
    for (var i in bqlist) {
      if (item.date == bqlist[i]) {
        return true;
      }
    }
    return false;
  },

  // 点击签到
  checkInToday() {

    var ck = this.data.day;
    if (parseInt(ck) < 10) ck = "0" + ck;
    if(this.data.res && this.data.res.qddaylist){
      var isCheckInToday = this.data.res.qddaylist.indexOf(ck);
      //已经签到
      if (isCheckInToday >-1) {
         return false;
      }
    }
    

    if(this.data.td_cked) return false;
    if(this.data.cking) return false;
    this.setData({cking:1});
 
    const self = this;
    getApp().request.get("/api/weshop/users/getServerTime", {
      success: function (res) {
        if (res.data.code == 0) {
          var getnowtime = res.data.data;
          if (!getnowtime) {
            self.setData({cking:0});
            getApp().showWarning("获取服务时间失败");
            return;
          } else {
            // 获取今天的签到状态
            //let isCheckInToday = this.data.dateArr[this.data.day-1].isCheckIn;
            var ck = self.data.day;
            if (parseInt(ck) < 10) ck = "0" + ck;
            var isCheckInToday = self.data.res.qddaylist.indexOf(ck);

            // 如果还没签到, 可以点击签到
            if (isCheckInToday == -1) {

              getnowtime = getnowtime.replace(/-/g, "/")
              var timeid = Date.parse(getnowtime)/1000;
              var key = "rgqsqLYhw67sgaIQBF6dw9JK7CDKSS";
              var str = app.globalData.setting.stoid + ":" + app.globalData.user_id + ":" + timeid + ":" + key
              var sign = md5(str);

              var qdbh='qd'+ut.format(null,'yyyyMMddhhmmssS')+(Math.floor(Math.random()*9999)+1000)+app.globalData.user_id;

              app.request.promisePost('/api/weshop/qdrecord/saveQd', {
                data: {
                  store_id: app.globalData.setting.stoid,
                  user_id: app.globalData.user_id,
                  timeid: timeid,
                  sign: sign,
                  qdbh:qdbh
                }
              }).then(res2 => {
                // 改变签到状态,由false置为true
                // let newDateArr = self.data.dateArr;
                // newDateArr[self.data.day-1].isCheckIn = true;
                self.setData({cking:0});

                if (res2.data.code == 0) {

                  self.data.td_cked=1;
                  for (var i in self.data.dateArr) {
                    self.data.dateArr[i].isCheckIn = false;
                    self.data.dateArr[i].isBq = false;
                  }
                  self.setData({
                    dateArr: self.data.dateArr
                  });

                  self.loadQd(function () {
                    wx.showToast({
                      title: self.data.res.qdintro,
                      icon: 'none',
                      duration: 1500,
                      success: function () {

                      }
                    });
                  });
                } else {
                  getApp().showWarning(res2.data.msg);
                  setTimeout(()=>{
                    wx.reLaunch({
                      url: '/packageA/pages/checkin/checkin',
                    })
                  },2000)
                }


              })
            }
            else{
              self.data.td_cked=1;
              self.setData({cking:0});
            }
          }

        } else {
          self.setData({cking:0});
          getApp().showWarning(res.data.msg);
          setTimeout(()=>{
            wx.reLaunch({
              url: '/packageA/pages/checkin/checkin',
            })
          },2000)
        }
      }
    })

  },


  // 补签
  reCheckIn() {


    if(this.data.cking) return false;
    this.setDate({cking:1});

    var self = this;
    // var i = 0;
    console.log('补签~');
    if (this.data.flag) {
      this.data.flag = false;

      app.request.promisePost('/api/weshop/qdrecord/saveBQd', {
        data: {
          store_id: app.globalData.setting.stoid,
          user_id: app.globalData.user_id,
          daynum: self.data.res.getBQIntegral1,
          bqnum: self.data.res.getbqnum2,
          bqintegral: self.data.res.getBQIntegral
        }
      }).then(res => {
        // 改变签到状态,由false置为true
        // let newDateArr = self.data.dateArr;
        // newDateArr[self.data.day-1].isCheckIn = true;
        //var bqlist = self.data.res.curbqdaynum.split(',').sort();
        //var list = [];
        /*--
        for(let item of bqlist) {
          var date = new Date(item);
          list.push(date.getDate());
        }--*/
        self.setDate({cking:0});
        if (res.data.code == 0) {
          for (var i in self.data.dateArr) {
            self.data.dateArr[i].isCheckIn = false;
            self.data.dateArr[i].isBq = false;
          }
          self.setData({
            dateArr: self.data.dateArr
          });
          self.loadQd(function () {
            self.data.flag = true;
            wx.showToast({
              title: '补签成功',
              icon: 'success',
              duration: 1500,
              success: function () {

              }
            });
          });
        } else {
          getApp().showWarning(res.data.msg);
          setTimeout(()=>{
            wx.reLaunch({
              url: '/packageA/pages/checkin/checkin',
            })
          },2000)
        }

      })
    }
  },

  getDate: function () { //获取当月日期
    var mydate = new Date();
    var year = mydate.getFullYear();
    var month = mydate.getMonth();  			//0~11: 一月至十二月
    var months = month + 1;         			//1~12：一月至十二月
    this.data.year = year;
    this.data.month = months;
    this.data.day = mydate.getDate(); 		//获取当月日期: 1~31
    var fist = new Date(year, month, 1);
    this.data.firstDay = fist.getDay();		//获取当月第一天		
    var last = new Date(year, months, 0); //0表示当月最后一天
    this.data.lastDay = last.getDate();   //获取当月最后一天

    this.setData({
      year: this.data.year,
      month: this.data.month,
      day: this.data.day,
      firstDay: this.data.firstDay,
      lastDay: this.data.lastDay,
      fist: fist
    })
    console.log("今天：" + this.data.day);
  },

  setDate: function () {
    var day;
    for (var i = 0; i < this.data.firstDay; i++) {
      //获取前几天的时间数组
      var arr_d = this.getNextDate(this.data.fist, i - this.data.firstDay)
      day = { num: arr_d[1], date: arr_d[0] };
      this.data.s_dateArr.push(day);
    }

    for (var i = 1; i < this.data.lastDay + 1; i++) {
      var date = this.data.month + "";
      if (this.data.month < 10) date = "0" + date;
      if (i < 10) {
        date = date + "-0" + i;
      } else {
        date = date + "-" + i;
      }
      day = { num: i, date: date };
      this.data.n_dateArr.push(day);
    }
  },

  //获取相隔是多少天的日期
  getNextDate(date, day) {
    var dd = date;
    dd.setDate(dd.getDate() + day);
    //var y = dd.getFullYear();
    var m = dd.getMonth() + 1 < 10 ? "0" + (dd.getMonth() + 1) : dd.getMonth() + 1;
    var d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();
    //return y + "-" + m + "-" + d;
    return [m + "-" + d, dd.getDate()];
  },
  go_url(e) {
    let url = e.currentTarget.dataset.url;
    if (url) {
      getApp().goto(url);
    }
  },

  back_to() {
    wx.navigateBack();
  },

  setDate_is_act(){
    let year=this.data.year;
    let sday3=res.sday3;
    let qddaylist=res.qddaylist;


    var date = getDate(year + '-' + startDate);
    date.setDate(date.getDate() + num);
    date = getDate(date).getDate();
    if(date<10) date="0"+date;
    if(!qdlist) return false;
    if(qdlist.indexOf(date)!=-1){
      return true
    }
    return false;



  },
  onShareAppMessage: function (e) {}

})
