// packageC/hotel/HotelHome/HotelHome.js
var location = require("../../../mybehaviors/location/location");
var app = getApp();
Page({
  behaviors: [location],
  /**
	 * 页面的初始数据
	 */
  data: {
    language: '',
    data_info: {},
    show1: true,
    show2: true,
    detail: "",
    star_num: "",
    location: {},
    phone: "",
    is_cashier: false,
    PageNameList: {}, //自定义标题
    address: "",
    point: {
      lat: '',
      lng: ''
    },
    city: '',
    title: '',
    cityData: '',
    HOME_PAGE_URL: "plugin.hotel.frontend.hotel.get-hotel-info.get-info-by-hotel-id",
    start: '',
    end: '',
    show3: false,
    room_arr: [],
    loading: false,
    allLoaded: false,
    goload: true,
    isLoadMore: true,
    page: 1,
    total_page: 0,
    night_day: "",
    banner_img: "",
    name: "",
    catagory_name: "",
    toolbar: false,
    wxTitie: "",
    id: "",
    ROOM_URL: "plugin.hotel.frontend.hotel.goods.get-goods-to-page"
  },

  /**
	 * 生命周期函数--监听页面加载
	 */
  onLoad: function(options) {
    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      console.log(scene);
      if (scene) {
        var info_arr = [];
        info_arr = scene.split('&');
        console.log(info_arr);

        for (let i = 0; i < info_arr.length; i++) {
          let chil_arr = [];
          chil_arr = info_arr[i].split('=');
          // 这是自提点
          console.log(chil_arr);
          if (chil_arr[0] == 'id') {
            this.setData({
              id: chil_arr[1]
            });
          }
        }
      }
    }
    if (options.id) {
      this.setData({
        id: options.id
      });
    }
    if (options.city) {
      this.setData({
        cityData: options.city
      });
    }
    if (options.start) {
      this.setData({
        start: options.start
      });
    }
    if (options.end) {
      this.setData({
        end: options.end
      });
    }
    this._getLocation(() => {this.getHomePageData();});
    this.getInitTime();
    this.getDays(this.data.start, this.data.end);
    this.initData();
    this.getData();
    this.getCustomizeHotelHead();

  },

  /**
	 * 生命周期函数--监听页面初次渲染完成
	 */
  onReady: function() {
    let language = wx.getStorageSync('langIndex');
    this.setData({ 'language': language.en});
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

  getHomePageData() {
    var that = this;
    let urlStr = app.getNetAddresss(that.data.HOME_PAGE_URL);
    urlStr += '&hotel_id=' + this.data.id;
    urlStr += '&lng=' + this.data.point.lng;
    urlStr += '&lat=' + this.data.point.lat;
    urlStr += '&city_name=' + this.data.cityData;
    app._getNetWork({
      url: urlStr,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            data_info: res.data,
            phone: res.data.mobile,
            is_cashier: res.data.is_cashier == 1 ? true : false,
          });
          that.getStar(res.data.star_rated);
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  //星级
  getStar(vaule) {
    switch (vaule) {
    case 0:
      this.setData({
        star_num: "未评星"
      });
      break;
    case 2:
      this.setData({
        star_num: "二星级经济型"
      });
      break;
    case 3:
      this.setData({
        star_num: "三星级舒适性"
      });
      break;
    case 4:
      this.setData({
        star_num: "四星级高档型"
      });
      break;
    case 5:
      this.setData({
        star_num: "五星级豪华型"
      });
      break;
    default:
      break;
    }
  },
  //获取酒店自定义字段
  getCustomizeHotelHead() {
    let that = this;
    let isQuestHotel = "";
    try {
      const value = wx.getStorageSync('customizeHotelHead');
      if (value) {
        isQuestHotel = value;
        // Do something with return value
      }
    } catch (e) {
      // Do something when catch error
    }
    if (!app._isTextEmpty(isQuestHotel)) {
      this.setData({
        PageNameList: JSON.parse(isQuestHotel)
      });
      wx.setNavigationBarTitle({
        title: this.data.PageNameList.hotel_home_page
      });
    } else {
      let urlStr = app.getNetAddresss("plugin.hotel.frontend.hotel.get-hotel-info.get-custom-name");
      app._getNetWork({
        url: urlStr,
        success: function(resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              PageNameList: res.data
            });
            wx.setNavigationBarTitle({
              title: res.data.hotel_home_page ? res.data.hotel_home_page : ''
            });
            try {
              wx.setStorageSync('customizeHotelHead', JSON.stringify(res.data));
            } catch (e) {
              console.log(e);
            }
          }
        },
        fail: function(res) {
          console.log(res);
        }
      });
    }
  },
  gotoCashier() {
    wx.navigateTo({
      url: '/packageC/cashier/cashier_pay/cashier_pay?hotel_id=' + this.data.id
    });
  },
  goToAdress() {
    let latitude = this.data.data_info.latitude;
    let longitude = this.data.data_info.longitude;
    let hotel_name = this.data.data_info.hotel_name;
    let point = app.BMapTransqqMap(parseFloat(longitude),parseFloat(latitude));
    wx.openLocation({
      latitude: point.lat,
      longitude: point.lng,
      scale: 18,
      name: hotel_name
    });
  },
  gophone() {
    let mobile = this.data.phone;
    wx.makePhoneCall({
      phoneNumber: mobile
    });
  },
  gotoCheckRoom() {
    wx.navigateTo({
      url: '/packageC/hotel/HotelChooseRoom/HotelChooseRoom?id=' + this.data.data_info.id + '&start=' + this.data.start +
				'&end=' + this.data.end + '&city=' + this.data.cityData
    });
  },
  toggleShow1() {
    this.setData({
      show1: (!this.data.show1)
    });
  },
  toggleShow2() {
    this.setData({
      show2: (!this.data.show2)
    });
  },
  getInitTime() {
    if (app._isTextEmpty(this.data.start) || app._isTextEmpty(this.data.end)) {
      this.getTime();
    }
  },
  getTime() {
    let now = new Date();
    let next = new Date(now.getTime() + 24 * 60 * 60 * 1000);
    this.setData({
      start: `${now.getFullYear()}-${now.getMonth() + 1 < 10 ? `0${now.getMonth() + 1}` : `${now.getMonth() + 1}` 
      }-${now.getDate() < 10 ? `0${now.getDate()}` : `${now.getDate()}`}`
    });
    this.setData({
      end: `${next.getFullYear()}-${next.getMonth() + 1 < 10 ? `0${next.getMonth() + 1}` : `${next.getMonth() + 1}`
      }-${next.getDate() < 10 ? `0${next.getDate()}` : `${next.getDate()}`}`
    });
  },
  //时间日期
  getDays(strDateStart, strDateEnd) {
    let strSeparator = "-"; //日期分隔符
    let oDate1, oDate2, iDays;
    oDate1 = strDateStart.split(strSeparator);
    oDate2 = strDateEnd.split(strSeparator);
    let strDateS = new Date(oDate1[0], oDate1[1] - 1, oDate1[2]);
    let strDateE = new Date(oDate2[0], oDate2[1] - 1, oDate2[2]);
    iDays = parseInt(Math.abs(strDateS - strDateE) / 1000 / 60 / 60 / 24); //把相差的毫秒数转换为天数
    this.setData({
      night_day: iDays
    });
  },
  initData() {
    this.setData({
      page: 1,
      total_page: 0,
      goload: true,
      loading: true,
      allLoaded: false,
      isLoadMore: true,
      room_arr: []
    });
  },
  getData() {
    var that = this;
    let urlStr = app.getNetAddresss(that.data.ROOM_URL);
    urlStr += '&page=' + this.data.page;
    urlStr += '&hotel_id=' + this.data.id;
    urlStr += '&enter_at=' + this.data.start;
    urlStr += '&leave_at=' + this.data.end;
    app._getNetWork({
      url: urlStr,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            room_arr: res.data.list.data,
            total_page: res.data.list.last_page
          });
          if (app._isTextEmpty(that.data.banner_img)) {
            that.setData({
              banner_img: res.data.hotel.banner_thumb
            });
          }
          if (app._isTextEmpty(that.data.name)) {
            that.setData({
              name: res.data.hotel.hotel_name
            });
          }
          if (app._isTextEmpty(that.data.catagory_name)) {
            that.setData({
              catagory_name: res.data.hotel.has_one_category.name
            });
          }
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500,
            success: function() {
              setTimeout(function() {
                //要延时执行的代码
                wx.navigateBack({
                  delta: 1
                });
              }, 1500); //延迟时间
            }
          });
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  show2btn() {
    this.setData({
      show2: true
    });
  },
  show3btn() {
    this.setData({
      show3: true
    });
  },
  acceptTime(e) {
    let type = e.detail.type;
    let date = e.detail.date;
    if (type == "离店") {
      this.setData({
        end: date
      });
    } else if (type == "入住") {
      this.setData({
        start: date
      });
    }
    this.checkDate(type);
  },
  checkDate(type) {
    //入住日期不能为空
    //离店日期不能小于住店日期
    //离店日期不能和住店日期同一天
    let start = new Date(this.data.start).getTime();
    let end = new Date(this.data.end).getTime();
    if (app._isTextEmpty(this.data.start)) {
      wx.showToast({
        title: '请先选择入住日期',
        icon: 'none',
        duration: 2000
      });
      this.setData({
        end: ""
      });
      return;
    } else {
      if (start == end) {
        wx.showToast({
          title: '入住和离店日期不能为同一天',
          icon: 'none',
          duration: 2000
        });
        this.setData({
          end: ""
        });
        return;
      }
      if (start > end) {
        wx.showToast({
          title: '离店日期需要大于入店日期',
          icon: 'none',
          duration: 2000
        });
        this.setData({
          end: ""
        });
        return;
      }
      //关闭弹窗
      if (type == "离店") {
        //计算多少晚
        this.getDays(this.data.start, this.data.end);
        this.setData({
          show3: false
        });
      } else if (type == "入住") {
        this.setData({
          show2: false
        });
      }
    }
  },
  close(e) {
    let type = e.detail;
    if (type == "离店") {
      this.setData({
        show3: false
      });
    } else if (type == "入住") {
      this.setData({
        show2: false
      });
    }
  },
  show2closebtn() {
    this.setData({
      show2: false
    });
  },
  show3closebtn() {
    this.setData({
      show3: false
    });
  },
  gotoGoods(e) {
    let val = e.currentTarget.dataset.id;
    if (app._isTextEmpty(this.data.start)) {
      wx.showToast({
        title: '住店时间不能为空',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    if (app._isTextEmpty(this.data.end)) {
      wx.showToast({
        title: '离店时间不能为空',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    wx.navigateTo({
      url: '/packageA/detail_v2/detail_v2?id=' + val + '&start=' + this.data.start + '&end=' + this.data.end
    });
  },
});
