var app = getApp();
//util.js 工具类
var util = require('../../utils/util.js'); 
// pages/book/book.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    token: '',
    timer: '',
    gotCode: false,
    checkOrder: false,
    restTime:120,
    venuesInfoId: '',
    selectVenuesProject:'',
    venuesProjectList: [],
    projectDetail:{},
    bookingOrderDateList:[],
    bookingOrderDate: '',
    selectGround:'',
    groundList:[],
    itemTimeList:[],
    mySelectItem:[],
    totalPrice:'0',
    phoneNumber:'',
    smsCode:''
  },

  //保存
  saveBookingInfo: function(){
    var self = this;
    if(self.data.mySelectItem.length == 0){
      wx.showToast({
        title: '请先选择您的预订信息',
        icon: 'none',
      })
      return false;
    }
    if(!self.checkPhoneNumber()){
      return false;
    }
    if(self.data.smsCode == ''){
      wx.showToast({
        title: '请填写验证码',
        icon: 'none',
      })
      return false;
    }
    var param = {
      smsCode : self.data.smsCode,
      phoneNumber : self.data.phoneNumber,
      venuesProjectId : self.data.selectVenuesProject,
      bookingItemList : self.data.mySelectItem
    }
    wx.showLoading({
      title: '请稍等...',
      mask: true
    })
    app.restAjax.post(app.restAjax.path('{venueUrl}/app/booking/savebookinginfo',[app.venueUrl]), param, {headers : {token:self.data.token}}, function(code,data){
      if(code == 200){
        wx.showToast({
          title: '预订成功',
        });
        setTimeout( () =>{
          wx.navigateBack({
            delta: 1,
          })
        },1500);
      }
    },function(code,data){
      app.dialog.msg(data.msg);
    },function(){
      wx.hideLoading();
    });
  },

  /**
   * 获取项目列
   */
  listVenuesProject: function(){
    var self = this;
    app.restAjax.get(app.restAjax.path('{venueUrl}/app/venuesproject/listprojectinforelease/{venuesInfoId}',
      [app.venueUrl,self.data.venuesInfoId]), {}, null, 
      function(code,data){
        self.setData({
          venuesProjectList: data
        });
        if(self.data.venuesProjectList.length > 0){
          self.setData({
            selectVenuesProject: self.data.venuesProjectList[0].venuesProjectId
          });
          self.getVenuesProjectDetail();
          self.getItemTimeList();
        };
      },function(code,data){
        app.dialog.msg(data.msg);
      }
    );
  },

  //获取项目详情信息
  getVenuesProjectDetail: function(){
    var self = this;
    app.restAjax.get(app.restAjax.path('{venueUrl}/app/venuesproject/getvenuesprojectdetailrelease/{venuesProjectId}',
      [app.venueUrl,self.data.selectVenuesProject]), {}, null, 
      function(code,data){
        self.setData({
          projectDetail:data.data
        });
        // console.log(self.data.projectDetail);
      },function(code,data){
        app.dialog.msg(data.msg);
      }
    );
  },

  //获取预订时刻表
  getItemTimeList: function(){
    var self = this;
    if(self.data.selectVenuesProject == ''){
      return false;
    }
    app.restAjax.get(app.restAjax.path('{venueUrl}/app/booking/listgrouninfoanditemrelease/{venuesProjectId}',
      [app.venueUrl,self.data.selectVenuesProject]), null, {headers : {token:self.data.token}}, 
      function(code,data){
			if(data.data.length > 0 ){
          self.setData({
            groundList: data.data,
            selectGround:data.data[0].groundInfoId,
            itemTimeList:data.data[0].groundItemList
          });
        } else {
          self.setData({
            groundList: [],
            selectGround:'',
            itemTimeList:[]
          });
        }
        self.checkSelectType();
        // console.log(data.data);
      },function(code,data){
        app.dialog.msg(data.msg);
      }
    );
  },

  //用户点选时刻
  selectItemTime: function(options){
    var obj = options.currentTarget.dataset;
    if(obj.data.checked == '0'){
      var item = {
        bookingOrderDate: this.data.bookingOrderDate,
        timeStr: obj.data.timeStr,
        timeEnd: obj.data.timeEnd,
        groundName: obj.data.groundName,
        groundItemId: obj.data.groundItemId,
        price: obj.data.price
      }
      var mySelectItem = this.data.mySelectItem;
      mySelectItem.push(item)
      this.setData({
        mySelectItem :mySelectItem
      })
    }
    if(obj.data.checked == '1'){
      var self = this;
      var mySelectItem = self.data.mySelectItem;
      for(var i = 0; i < mySelectItem.length; i++){
        if(mySelectItem[i]['groundItemId'] == obj.data.groundItemId && mySelectItem[i]['bookingOrderDate'] == self.data.bookingOrderDate){
          mySelectItem.splice(i,1);
          self.setData({
            mySelectItem: mySelectItem
          })
          break;
        }
      }
    }
    this.checkSelectType();
    this.checkPrice();
  },

  //切换当前选择项目
  changeProject: function(options){
    var venuesProjectId = options.currentTarget.dataset.id;
    if(this.data.selectVenuesProject == venuesProjectId){
      return false;
    };
    this.setData({
      selectVenuesProject: venuesProjectId,
      mySelectItem: []
    });
    this.getVenuesProjectDetail();
    this.getItemTimeList();
    this.getBookingDate()
    this.setData({
      mySelectItem:[],
      totalPrice : 0
    });
  },

  //切换场地
  changeGround: function(options){
    var groundInfoId = options.currentTarget.dataset.id;
    var index = options.currentTarget.dataset.index;
    var groundList = this.data.groundList;
    this.setData({
      selectGround: groundInfoId,
      itemTimeList: groundList[index].groundItemList
    })
    this.checkSelectType();
  },

   //判断已选择的状态
   checkSelectType: function(){
    var self = this;
    self.data.itemTimeList.forEach(element =>{
      element['checked'] = '0';
      self.data.mySelectItem.forEach(my =>{
        if(element['groundItemId'] == my['groundItemId'] && self.data.bookingOrderDate == my['bookingOrderDate']){
          element['checked'] = '1';
        }
      })
    });
    // console.log(self.data.itemTimeList);
    self.setData({
      itemTimeList: self.data.itemTimeList
    })
  },

  //预订日期
  getBookingDate: function(){
    var dateList = [];
    var day = new Date();
    day.setTime(day.getTime() + 24*60*60*1000)
    dateList.push(util.formatDate(day));
    day.setTime(day.getTime() + 24*60*60*1000)
    dateList.push(util.formatDate(day));
    day.setTime(day.getTime() + 24*60*60*1000)
    dateList.push(util.formatDate(day));
    this.setData({
      bookingOrderDate: dateList[0],
      bookingOrderDateList: dateList
    })
  },
  
  //切换日期
  changeDate: function(options){
    this.setData({
      bookingOrderDate: options.currentTarget.dataset.date
    })
    this.checkSelectType();
  },

  //计算金额
  checkPrice: function(){
    var total = 0;
    this.data.mySelectItem.forEach(element=>{
      total = total + Number(element['price']);
    })
    this.setData({
      totalPrice: total
    })
  },

  checkPhoneNumber: function(){
    if(this.data.phoneNumber == ''){
      wx.showToast({
        title: '请填写手机号',
        icon: 'none',
      })
      return false;
    }
    if (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(this.data.phoneNumber)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    return true;
  },

  //获取验证码
  getSmsCoce: function (){
    var self = this;
    if(!self.checkPhoneNumber()){
      return false;
    }
    wx.showLoading({
      title: '请稍等...',
      mask: true
    })
    app.restAjax.get(app.restAjax.path('{venueUrl}/app/sms/verify-code/' + self.data.phoneNumber, [app.venueUrl]), {}, null, 
      function (code, data) {
        if (code == 200) {
          self.setData({
            gotCode: true
          })
          self.data.timer = setInterval(function () {
            var cur = self.data.restTime - 1
            if (cur == 0) {
              clearInterval(self.data.timer)
              self.setData({
                restTime: 120,
                gotCode: false
              })
            } else {
              self.setData({
                restTime: cur
              })
            }
          }, 1000)
          wx.hideLoading();
        }
      },
      function (code, data) {
        wx.showToast({
          title: data.msg,
          icon: 'none',
          duration: 1500
        })
      })
  },

  doCheckOrder: function () {
    if(this.data.mySelectItem.length == 0){
      return false;
    }
    this.setData({
      checkOrder: true
    })
  },

  closeCheckOrder: function () {
    this.setData({
      checkOrder: false
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.getStorage({
      key: 'token',
      success: (result) => {
        this.setData({
          token : result.data
        })
      }
    })
    this.setData({
      venuesInfoId: options.venuesInfoId
    });
    this.listVenuesProject();
    this.getBookingDate();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

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

  },

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

  },

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

  },

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

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})