const util = require("../../../utils/util");
const app = getApp();
Page({
  data: {
    userInfo:{
      id:'',
      name:'',
      userAvatar:'',
      childName:'',
      age:0,
      city:'',
      sex:0,
      curriculum:{}
    },
    scroll:true,  //用于滚动条参数
    showBack:false,
    fixTop:false,
    currentIndex:1,
    fieldIndex:1,
    content:'',
    leaderid:0, //领队默认选中
    SevenDaysDate:[],
    showDatePopup:false,
    showChildPopup:false,
    showCode:false,
    headImg:'',
    list:[],
    pageIndex:1,
    cardPageIndex:1,
    scrollLeft:'0',
    searchText:'',
    completedate:'',
    cardList:[],
    canBuy:0,//是否可购买成长课
    methodView:0,//二维码弹窗显示文案
    allLeader:[
      {
        uid:0,
        avatar:'https://img.bbztx.com/image/upload/20230105/leader.png',
        leaderCity:'',
        nickname:'全部'
      },
    ],
    leaderList:[],
  },
  onLoad: function (options) {
    // this.getList()
    // this.getSevenDays()
  },
  onShow:function(){
    this.setData({cardPageIndex:1})
    this.getList()
    // this.getCardList();
    // this.bindSearch(2)
  },
  setTabbar(e){
    let i = e.currentTarget.dataset.index;
    this.setData({
      currentIndex:i,
      cardList:[],
      cardPageIndex:1
    })
    this.getCardList();
  },
  calendarClose(e){
    this.setData({
      showDatePopup:e.detail
    })
  },
  personnelClose(e){
    this.setData({
      showChildPopup:e.detail
    })
  },
  closeCode(e){
    this.setData({
      showCode:e.detail
    })
  },
  // 选择领域
  fieldSelect(e){
    let data = e.currentTarget.dataset;
    this.setData({
      fieldIndex:data.index,
      content:data.content == '全部'?'':data.content,
      cardPageIndex:1
    })
    this.getCardList()
  },
  // 获取人员名单
  getList() {
    var self = this;
    util.ajax({
      func: "v2/gwcourse/student/list",
    }, function (res) {
      if(res.code == 0){
        if (res.data.length >0) {
          let arr =res.data;
          arr.forEach((el,i) => {
            el.checked =i==0?true:false;
          });
          if (util.isEmpty(self.data.userInfo.id)) {
            self.setData({ 
              list:arr,
              canBuy:arr.length>0?1:0,
              'userInfo.childName':res.data[0].childName,
              'userInfo.userAvatar':res.data[0].userAvatar,
              'userInfo.id':res.data[0].id,
              'userInfo.age':res.data[0].age,
              'userInfo.city':res.data[0].city,
              'userInfo.sex':res.data[0].sex,
            });
            self.getCurriculumTotal(res.data[0].id)
          }
        }
      }else{
        util.showTips(res.reason)
      }
      self.bindSearch(2)
      self.getCardList()
      self.getSevenDays()
    });
  },
  // 获取儿童信息
  getChildInfo(e){
    if (e.detail.id) {
      this.getCurriculumTotal(e.detail.id)
    }
    this.setData({
      showChildPopup:false,
      'userInfo.childName':e.detail.childName,
      'userInfo.id':e.detail.id,
      'userInfo.age':e.detail.age,
      'userInfo.city':e.detail.city,
      'userInfo.sex':e.detail.sex,
      'userInfo.userAvatar':e.detail.userAvatar,
      completedate:'',
      leaderid:0,
      currentIndex:'1',
      cardPageIndex:1,
      cardList:[]
    })
    // this.getCardList()
    this.bindSearch(2)
  },
  // 获取弹窗选中的日期
  getCalendarInfo(e){
    this.setData({
      showDatePopup:false,
      dateActived:e.detail,
      completedate:e.detail,
      cardList:[]
    })
    this.getCardList();
  },
  // 通过儿童信息获取课程信息
  getCurriculumTotal(id){
    var self = this;
    // let studentId = id;
    util.ajax({
      func: `v2/gwcourse/student/statinfo`,
      data:{studentId:id}
    }, function (res) {
      if(res.code == 0){
        self.setData({'userInfo.curriculum':res.data})
      }else{
        util.showTips(res.reason)
      }
    });
  },
  // 选择领队
  selectLeader(e){
    let uid = e.currentTarget.dataset.uid;
    if (this.data.leaderid != uid) {
      this.setData({
        leaderid:uid,
        cardPageIndex:1,
      })
      this.getCardList();
    }
  },
  // 选择日期
  selectDate(e){
    let data = e.currentTarget.dataset;
    this.setData({
      dateActived:data.completedate,
      completedate:data.completedate,
      cardList:[],
      cardPageIndex:1
    })
    this.getCardList();
  },
  // 搜索输入框
  bindinput(e){
    this.setData({searchText:e.detail.value})
    if (e.detail.value == '') {
      // this.setData({leaderid:0})
      // this.getCardList();
      this.bindSearch(2)
    }
  },
  bindSearch(bol){
    var self = this;
    let index = bol==1 ? self.data.pageIndex:1;
    let data ={
      nickname:self.data.searchText,
      pageIndex:index,
    }
    if (!util.isEmpty(self.data.userInfo.id)) {
      data.studentId=self.data.userInfo.id
    }
    util.ajax({
      func: `v2/gwcourse/teacher/list`,
      data:data
    }, function (res) {
      if(res.code == 0){
        if (res.data.list&&res.data.list.length>0) {
          let arr =bol==1?self.data.leaderList.concat(res.data.list):self.data.allLeader.concat(res.data.list);
          self.setData({
            leaderList:arr,
            leaderid:(bol==2 || (self.data.searchText==''&& bol!=1))?0: bol==1? self.data.leaderid: res.data.list[0].uid
          })
          if (bol!=1) {
            self.getCardList();
            self.setData({scrollLeft:0})
          }
        }else{
          let arr =bol==1?self.data.leaderList:self.data.allLeader;
          self.setData({leaderList:arr})
          if (bol!=1) {
            self.setData({scrollLeft:0})
          }
        }
      }else{
        util.showTips(res.reason)
      }
    });
  },
  // 获取卡片列表信息
  getCardList(bol){
    let self = this,data={};
    if (self.data.currentIndex==1) {
      data.date = '';
      data.field = '';
      data.leaderUid=self.data.leaderid==0?'':self.data.leaderid;
    } else if (self.data.currentIndex==2) {
      data.leaderUid = '';
      data.date = self.data.dateActived;
    } else if (self.data.currentIndex==3){
      data.leaderUid = '';
      data.date = '';
      data.field = '';
    } else{
      data.leaderUid = '';
      data.date = '';
      data.field = self.data.content;
    }
    data.studentId= self.data.userInfo.id;
    data.book=self.data.currentIndex=='3'?1: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)
      }
    });
  },
  // 跳转到课程详情页
  jumpToDetail(e){
    let data = e.currentTarget.dataset
    let info = this.data.userInfo
    wx.navigateTo({
      url: '/pages/account/growthCourse/courseDetail/index?id='+data.id+'&studentId='+info.id+'&childName='+info.childName+'&age='+info.age+'&city='+info.city+'&sex='+info.sex+'&userAvatar='+info.userAvatar+'&canBuy='+this.data.canBuy+'&leaderRecom='+data.leaderrecom+'&currentIndex='+this.data.currentIndex
    })
  },
  // 立即购买
  jumpToHome(bol){
    wx.reLaunch({
      url:'/pages/home/index'
    })
  },
  // 跳转到待反馈页面
  jumpToEvaluate(e){
    let data = e.currentTarget.dataset;
    wx.navigateTo({
      url: '/pages/account/growthCourse/courseEvaluate/index?id='+data.id+'&studentId='+this.data.userInfo.id+'&leaderName='+data.leadername+'&courseTitle='+data.coursetitle+'&city='+data.city,
    })
  },
  // 预约
  appointment(e){
    let data = e.currentTarget.dataset;
    let self =this;
    if (self.data.list.length>0) {
      if (data.status==0) {
        wx.showModal({
          content: `确认为 ${self.data.userInfo.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: '/pages/home/index'
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  },
  // 无儿童信息的提示
  tip(){
    wx.showModal({
      content: '请先为儿童购买成长课，购买成功后预约课程即可在此查看记录。',
      confirmText:'前往购买',
      success (res) {
        if (res.confirm) {
          wx.reLaunch({
            url: '/pages/home/index'
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  // 预约课程接口
  appoint(data){
    let self = this;
    util.ajax({
      func: `v2/gwcourse/book`,
      data:{
        studentId:self.data.userInfo.id,
        courseId:data.item.id,
        status:data.status
      }
    }, function (res) {
      if(res.code == 0){
        self.data.cardList.forEach((el,i) => {
          if (el.id == data.item.id) {
            let STASTUS = 'cardList['+i+'].status';
            let STU = 'cardList['+i+'].students';
            let num='userInfo.curriculum.courseReservedNum',num1= 'userInfo.curriculum.courseActnum';
            if (data.status == 0) {
              let arr = {
                id:self.data.userInfo.id,
                userAvatar:self.data.userInfo.userAvatar
              };
              self.data.cardList[i].students.push(arr)
              self.setData({
                [STASTUS]:3,
                [STU]:self.data.cardList[i].students,
                [num]:self.data.userInfo.curriculum.courseReservedNum+1,
                [num1]:self.data.userInfo.curriculum.courseActnum-1
              })
            } else {
              self.data.cardList[i].students.forEach((el,index) => {
                if (el.id == self.data.userInfo.id) {
                  self.data.cardList[i].students.splice(index,1)
                }
              });
              self.setData({
                [STASTUS]:0,
                [STU]:self.data.cardList[i].students,
                [num]:self.data.userInfo.curriculum.courseReservedNum-1,
                [num1]:self.data.userInfo.curriculum.courseActnum+1
              })
            }
            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('用户点击确定')
                    }
                  }
                })
              }
            }
          }
        });
      }else{
        util.showTips(res.reason)
      }
    });
  },
  // 进群上课
  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('用户点击确定')
          }
        }
      })
    }
  },
  // 横向滑动滚动条
  pageLoad(){
    this.data.pageIndex++;
    this.setData({pageIndex:this.data.pageIndex})
    this.bindSearch(1)
  },
  // 下拉懒加载
  cardListLoad(){
    this.data.cardPageIndex++;
    this.setData({cardPageIndex:this.data.cardPageIndex});
    this.getCardList(1);
  },
  // 打开日历弹窗
  getDatepopup(){
    this.setData({showDatePopup:true})
  },
  // 获取当前时间后七天
  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
      })
    })
  },
  // 获取每日活动详情
  getDateActivited(date){
    return new Promise(function (resolve, reject) {
      util.ajax({
        func: "v2/gwcourse/schedule",
        data: { "startDate": date[0].completeDate, "endDate": date[date.length-1].completeDate}
      }, function (res) {
        if (res.code == 0) {
            resolve(res.data)
        }else{
          // reject()
          util.showTips(res.reason);
        }
      })
    }
    )
  },
  // 日期转换
  changeDate(date){
    let str = date>=10?date:'0'+date;
    return str;
  },
  selectChilds(){
    this.setData({showChildPopup:true})
  },
  //  页面上拉触底事件的处理函数
  onReachBottom: function () {
    this.cardListLoad();
  },
  toTop() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
  },
  onPageScroll(e) {
    let query = wx.createSelectorQuery(),self =this;
    query.select('.content').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})
    })
  },
  onShareAppMessage() {
    return {
      title:'让爱和快乐延续，小黄人成长课在线等你来约！',
      path:'/pages/account/growthCourse/index',
      imageUrl:'http://img.bbztx.com/image_test/upload/thumbs/20210223/logo/1614076819238032554.jpg'
    }
  },
})