// nova-tourism/pages/homestay/homestay-detail/index.js
let Parse = getApp().Parse;
const company = getApp().globalData.company
import dateServ from '../../../service/date';
const dateF = require("../../../../utils/date")
let sev = require("../../../service/request")
const uid = Parse.User.current()?.id
const req = require('../../../../utils/request')
const login = require("../../../../utils/login");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //屏幕高度
    statusBarHeight: 0, // 状态栏高度
    screenHeight: 0, // 屏幕高度
    customHeight: 0, // 自定义导航栏高度（如小程序右上角胶囊按钮）
    bottomNavHeight: 0, // 底部导航栏高度
    contentHeight: 0, // 可用内容高度
    //  轮播图数组
    imageUrls: [],
    index: 1,
    roomIndex: 1,
    //
    decodedDateStart: '',
    decodedDateEnd: '',
    objectId: "",
    daysBetween: 0,
    istoday: null,
    storeList: [],
    roomList: [],

    //地图
    longitude: 0,
    latitude: 0,
    markers: [],

    //
    start: '',
    end: '',

    //
    show: false,
    date_start1: '',
    date_end1: '',
    showRoom: false, //显示房间详情
    chickRoom: null, //选中的房间
    specDateMap: {}, //特殊日期标识-今天/明天
    gift: [], //望仙礼遇-商品

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const today = new Date();
    const tomorrow = new Date();
    tomorrow.setDate(today.getDate() + 1);
    let specDateMap = {}
    specDateMap[dateF.formatTime('mm月dd日', today)] = '今天'
    specDateMap[dateF.formatTime('mm月dd日', tomorrow)] = '明天'
    // 计算
    const systemInfo = wx.getSystemInfoSync();
    const statusBarHeight = systemInfo.statusBarHeight || 0;
    const screenHeight = systemInfo.screenHeight || 0;
    const custom = wx.getMenuButtonBoundingClientRect();
    const customHeight = custom.height + 10 + 2 || 0;
    const bottomNavHeight = systemInfo.screenHeight - systemInfo.safeArea.bottom || 0;
    const contentHeight = (screenHeight - bottomNavHeight - statusBarHeight - customHeight) * 750 / systemInfo.windowWidth;
    if (bottomNavHeight) {
      const padding_bottom = bottomNavHeight * 750 / systemInfo.windowWidth
      this.setData({
        bottomNavHeight: padding_bottom
      })
    } else {
      this.setData({
        bottomNavHeight: 40
      })
    }

    this.setData({
      statusBarHeight,
      screenHeight,
      customHeight,
      contentHeight
    });

    const {
      store_id,
      start,
      end,
    } = options;
    let startDate = new Date(`${start} 12:00:00`)
    let endDate = new Date(`${end} 14:00:00`)
    this.setData({
      decodedDateStart: dateF.formatTime('mm月dd日', startDate),
      decodedDateEnd: dateF.formatTime('mm月dd日', endDate),
      objectId: store_id,
      daysBetween: sev.getDays(startDate, endDate),
      start: startDate,
      end: endDate,
      specDateMap
    })
    console.log(this.data.start, this.data.end);
    // this.hanshu()
    this.refersh()
  },

  async refersh() {
    this.getShopStore()
    this.getRoom()
    this.getGift()
  },
  /**获取当前店铺 */
  async getShopStore() {
    let {
      objectId
    } = this.data
    let query = new Parse.Query('ShopStore')
    let d = await query.get(objectId)
    let shopStore = d?.toJSON()
    let cQuery = new Parse.Query('DramaShopCollect')
    cQuery.equalTo('company', company)
    cQuery.equalTo('user', uid)
    cQuery.equalTo('homestayStore', objectId)
    cQuery.equalTo('isCollect', 'true')
    cQuery.notEqualTo('isDeleted', "true")
    let count = await cQuery.count()
    shopStore.iscollect = count
    console.log(shopStore)
    let longitude = shopStore?.location?.longitude || 0
    let latitude = shopStore?.location?.latitude || 0
    this.setData({
      shopStore,
      longitude,
      latitude,
      markers: [{
        id: 1,
        longitude,
        latitude,
        iconPath: 'https://file-cloud.fmode.cn/13WZ0W7u3l/20240724/7ebg0k104325941.png?imageView2/1/w/200/h/200', /// 自定义标记图标
        width: 20,
        height: 20,
      }]
    })
  },
  /**获取店铺房间 */
  async getRoom() {
    let {
      objectId
    } = this.data
    let query = new Parse.Query('ShopRoom');
    query.equalTo('company', company);
    query.equalTo('shop', objectId);
    query.equalTo('isEnabled', 'true');
    query.notEqualTo('isDeleted', 'true');
    query.ascending('index')
    let d = await query.find();
    let roomList = d?.map(item => item?.toJSON())
    await this.setData({
      roomList
    })
    this.judRoom()
  },
  /**打开地图 */
  callMap() {
    let {
      shopStore,
      latitude,
      longitude,
    } = this.data
    wx.openLocation({
      name: shopStore?.storeName || '',
      latitude,
      longitude,
      scale: 18
    })
  },
  /** 开日历*/
  openCalendar() {
    this.setData({
      show: true
    });
  },
  /** 关日历*/
  closeCalendar() {
    this.setData({
      show: false
    });
  },
  /** 选好日期点击完成后*/
  async onConfirm(event) {
    const [start, end] = event.detail;
    let daysBetween = sev.getDays(start, end)
    await this.setData({
      start: new Date(start.setHours(12, 0, 0)),
      end: new Date(end.setHours(14, 0, 0)),
      decodedDateStart: dateF.formatTime('mm月dd日', start),
      decodedDateEnd: dateF.formatTime('mm月dd日', end),
      daysBetween
    });
    this.judRoom()
    this.closeCalendar()
  },
  /**遍历房间判断当前时段房间状态 */
  async judRoom() {
    let {
      start,
      end,
      roomList
    } = this.data
    for (let i in roomList) {
      let item = roomList[i]
      /**是否空闲-true（可预约），false（不可预约） */
      let isFree = await sev.isFree({
        from: start,
        to: end
      }, item.objectId)
      roomList[i].isFree = isFree
    }
    this.setData({
      roomList
    })
  },
  /** 点击预定*/
  navigate(e) {
    let userInfo = wx.getStorageSync("userLogin");
    if ( userInfo == ''||!userInfo) {
      console.log(userInfo);
      login.loginNow()
      return
    }
    const {
      index
    } = e.currentTarget.dataset;
    let {
      start,
      end,
      roomList
    } = this.data
    console.log(roomList, roomList[index])
    if (!roomList[index].isFree) {
      wx.showToast({
        title: '时段内房间被预约',
        icon: 'none'
      })
      return
    }
    let date_start = dateF.formatTime("YYYY-mm-dd", start)
    let date_end = dateF.formatTime("YYYY-mm-dd", end)
    
    wx.navigateTo({
      url: `../homestay-order2/index?objectId=${roomList[index].objectId}&date_start=${date_start}&date_end=${date_end}`
    })
  },
  /** 点击预定*/
  navigatePopup() {
    let userInfo = wx.getStorageSync("userLogin");
    if ( userInfo == ''||!userInfo) {
      console.log(userInfo);
      login.loginNow()
      return
    }
    let {
      start,
      end,
      chickRoom
    } = this.data
    if (!chickRoom.isFree) {
      wx.showToast({
        title: '时段内房间被预约',
        icon: 'none'
      })
      return
    }
    let date_start = dateF.formatTime("YYYY-mm-dd", start)
    let date_end = dateF.formatTime("YYYY-mm-dd", end)
    wx.navigateTo({
      url: `../homestay-order2/index?objectId=${chickRoom.objectId}&date_start=${date_start}&date_end=${date_end}`
    })
  },
  /**房间弹框-开 */
  showRoom(e) {
    let {
      roomList
    } = this.data
    let {
      index
    } = e.currentTarget.dataset
    console.log(roomList[index])
    this.setData({
      chickRoom: roomList[index],
      showRoom: true
    });
  },
  /**房间弹框-关 */
  onCloseRoom() {
    this.setData({
      showRoom: false
    });
  },
  /**拨打电话 */
  phone() {
    let userInfo = wx.getStorageSync("userLogin");
    if ( userInfo == ''||!userInfo) {
      console.log(userInfo);
      login.loginNow()
      return
    }
    let phone = this.data.shopStore.mobile
    wx.makePhoneCall({
      phoneNumber: phone
    })
  },
  /** 获取望仙礼遇-商品*/
  async getGift() {
    let {
      objectId
    } = this.data
    let sql = `SELECT good."objectId",good."name",good."price",good."image"
  FROM "ShopGoods" good
  WHERE good."company" = '${company}'
  AND good."isDeleted" IS NOT TRUE
  AND good."status" IS TRUE
  AND good."shopStore"='${objectId}'
  ORDER BY COALESCE(good."isHome", FALSE) DESC,
  CASE WHEN good."top"= 0 THEN 1 ELSE 0 END,
  good."top" ASC,good."createdAt"
  LIMIT 4`
    let gift = await req.customSQL(sql) || []
    console.log(gift)
    this.setData({
      gift
    })
  },





/**预览图片 */
preview(e){
  let {
    list,index
  } = e.currentTarget.dataset
  sev.previewImgs(list,index)
},
  /** 跳转*/
  tourl(e) {
    let userInfo = wx.getStorageSync("userLogin");
    if ( userInfo == ''||!userInfo) {
      console.log(userInfo);
      login.loginNow()
      return
    }
    const url = e.currentTarget.dataset.url
    wx.navigateTo({
      url: `${url}` // 目标页面的路径
    });
  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let {
      roomList
    } = this.data
    if (roomList?.length) {
      this.judRoom()
    }
  },

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

  },

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

  },

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

  },

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

  },

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

  },
  //随轮播图变化而变化
  onSwiperChange: function (event) {
    const currentIndex = event.detail.current; // 获取当前索引
    this.setData({
      index: currentIndex + 1
    })
  },
  //随轮播图变化而变化
  onRoomChange: function (event) {
    const currentIndex = event.detail.current; // 获取当前索引
    this.setData({
      roomIndex: currentIndex + 1
    })
  },
})