const util = require("../../../../utils/util");
const app = getApp();
Page({
  data: {
    currentIndex:1,
    fixTop:false,
    SevenDaysDate:[],
    dateActived:'',
    completedate:'',
    cardList:[],
    cardPageIndex:1,
    showDatePopup:false,
    showBack:false,
    param:{},
    leaderInfo:{},
    canBuy:0,
    showCode:false,
    methodView:0,
    headImg:''
  },
  onLoad: function (options) {
    this.setData({
      'param.studentId':options.studentId,
      'param.teacherUid':options.teacherUid,
      'param.teacherName':options.teacherName,
      'param.teacherCity':options.teacherCity,
      'param.childName':options.childName,
      canBuy:options.canBuy
    })
    this.getSevenDays()
    this.getCardList()
  },
  //  生命周期函数--监听页面显示
  onShow: function () {
    this.getInfo()
  },
  // 打开日历弹窗
  getDatepopup(){
    this.setData({showDatePopup:true})
  },
  // tab栏切换
  setTabbar(e){
    let i = e.currentTarget.dataset.index;
    this.setData({
      currentIndex:i,
    })
  },
  // 获取卡片列表信息
  getCardList(bol){
    let self = this,data={};
    data.leaderUid = self.data.param.teacherUid;
    data.date = self.data.dateActived;
    data.studentId= self.data.param.studentId;
    data.book=0;
    data.pageIndex=self.data.cardPageIndex;
    util.ajax({
      func: `v2/gwcourse/list`,
      data:data
    }, function (res) {
      if(res.code == 0){
        if (res.data.list&&res.data.list.length>0) {
          let arr = self.data.cardList.concat(res.data.list)
          self.setData({cardList:bol==1?arr:res.data.list})
        }else{
          self.setData({cardList:bol==1?self.data.cardList:[]})
        }
      }else{
        util.showTips(res.reason)
      }
    });
  },
  // 获取领队信息
  getInfo(){
    let that=this;
    util.ajax({
      func:'v2/leader/style/detail',
      data:{
        uid:that.data.param.teacherUid
      }
    },function (res) {
      if (res.code ==0) {
        let data =res.data,arr=[];
        arr.push(data.avatar)
        data.avatar=arr;
        data.pics =util.isEmpty(data.pics)?[]:data.pics.split(',');
        data.videos =util.isEmpty(data.videos)?[]: data.videos.split(',');
        that.setData({
          leaderInfo:data,
          currentIndex:(data.pics.length>0 || data.videos.length>0)?1:2
        })
      }else{
        util.showTips(res.reason);
      }
    })
  },
  // 选择日期
  selectDate(e){
    let data = e.currentTarget.dataset;
    this.setData({
      dateActived:data.completedate,
      completedate:data.completedate,
      cardList:[],
      cardPageIndex:1
    })
    this.getCardList();
  },
  // 获取当前时间后七天
  getSevenDays(){
    let date = new Date(),timeNow=date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate(),arr=[];
    for (let index = 0; index < 7; index++) {
      var NewDate = new Date(date);
      NewDate.setDate(date.getDate()+index);
      var time = NewDate.getFullYear()+"-"+this.changeDate(NewDate.getMonth()+1)+"-"+this.changeDate(NewDate.getDate());
      let date1 = (NewDate.getMonth()+1)+"."+NewDate.getDate(),week = "日一二三四五六".charAt(new Date(time).getDay());
      let dateInfo = {
        date:date1,
        week:week,
        completeDate:time,
        num:0
      }
      if (index==0) {
        this.setData({
          dateActived:time
        })
      }
      arr.push(dateInfo);
    }
    this.getDateActivited(arr).then(res=>{
      if (res && res.length>0) {
        arr.forEach((el,i) => {
        res.forEach(item => {
          if (el.completeDate == item.date) {
            el.num = item.num
          }
        });
      });
      }
    this.setData({
      SevenDaysDate:arr
    })
    })
  },
  // 日期转换
  changeDate(date){
    let str = date>=10?date:'0'+date;
    return str;
  },
  closeCode(e){
    this.setData({
      showCode:e.detail
    })
  },
  // 获取每日活动详情
  getDateActivited(date){
    let self =this;
    return new Promise(function (resolve, reject) {
      util.ajax({
        func: "v2/gwcourse/schedule",
        data: { 
          "startDate": date[0].completeDate, 
          "endDate": date[date.length-1].completeDate,
          "leaderUid":self.data.param.teacherUid
        }
      }, function (res) {
        if (res.code == 0) {
            resolve(res.data)
        }else{
          // reject()
          util.showTips(res.reason);
        }
      })
    }
    )
  },
  toTop() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
  },
  calendarClose(e){
    this.setData({
      showDatePopup:e.detail
    })
  },
  // 获取弹窗选中的日期
  getCalendarInfo(e){
    this.setData({
      showDatePopup:false,
      dateActived:e.detail,
      completedate:e.detail,
      cardList:[],
      cardPageIndex:1
    })
    this.getCardList();
  },
  
  // 预约
  appointment(e){
    let data = e.currentTarget.dataset;
    let self =this;
    if (parseInt(self.data.canBuy) ==1) {
      if (data.status==0) {
        wx.showModal({
          content: `确认为 ${self.data.param.childName} 小朋友预约这节成长课吗？`,
          success (res) {
            if (res.confirm) {
              self.appoint(data)
            } else if (res.cancel) {
              console.log('放弃预约')
            }
          }
        })
      } else {
        self.appoint(data)
      }
    }else {
      wx.showModal({
        content: '请先为儿童购买成长课，购买成功后即可预约课程。',
        success (res) {
          if (res.confirm) {
            wx.reLaunch({
              url: 'url',
            })({
              url:'/pages/home/index'
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  },
  // 进群上课
  groupCodeView(e){
    let data = e.currentTarget.dataset.item;
    if (!util.isEmpty(data.qrCode)) {
      this.setData({
        showCode:true,
        headImg:data.qrCode,
        methodView:1
      })
    } else {
      wx.showModal({
        content: '您已预约！请耐心等待宝大大联系。',
        showCancel:false,
        success (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          }
        }
      })
    }
  },
  // 课程预约接口
  appoint(data){
    let self =this;
    util.ajax({
      func: `v2/gwcourse/book`,
      data:{
        studentId:self.data.param.studentId,
        courseId:data.item.id,
        status:data.status
      }
    }, function (res) {
      if(res.code == 0){
        if (data.status== 0) {
          if (!util.isEmpty(data.item.qrCode)) {
            self.setData({
              showCode:true,
              headImg:data.item.qrCode,
              methodView:0,
            })
          }else{
            wx.showModal({
              content: '恭喜您预约成功！请耐心等待宝大大联系。',
              showCancel:false,
              success (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                }
              }
            })
          }
        }
        self.setData({
          cardPageIndex:1
        })
        self.getCardList()
      }else{
        util.showTips(res.reason)
      }
    });
  },
  // 跳转到待反馈页面
  jumpToEvaluate(e){
    let data = e.currentTarget.dataset;
    wx.navigateTo({
      url: '/pages/account/growthCourse/courseEvaluate/index?id='+data.id+'&studentId='+this.data.param.studentId+'&leaderName='+data.leadername+'&courseTitle='+data.coursetitle+'&city='+data.city,
    })
  },
  // 下拉懒加载
  cardListLoad(){
    this.data.cardPageIndex++;
    this.setData({cardPageIndex:this.data.cardPageIndex});
    this.getCardList(1);
  },
  //  页面上拉触底事件的处理函数
  onReachBottom: function () {
    this.cardListLoad();
  },
  onPageScroll(e) {
    let query = wx.createSelectorQuery(),self =this;
    query.select('.detail_Info').boundingClientRect();
    query.select('.tabSelect').boundingClientRect();
    query.exec(function (res) {
      self.setData({showBack :res[0].top<=0 ? true:false})
      // self.setData({fixTop:res[1].top<=0 ? (res[0].top<=0?true:false): false})
      self.setData({fixTop:res[0].top<0 ? true: false})
    })
  }
})