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

Page({

  /**
   * 页面的初始数据
   */
  data: {
    room: {},
    startTime: null, // 入住开始时间
    endTime: null, // 入住结束时间
    roomId: null,
    count: 1, // 入住几晚
    date: '', //入住区间
    date02: '', //入住区间-页面显示
    name: '', //住客姓名
    mobile: '', //联系电话
    activeOrder: null, //创建的订单
    tradeNo: null, //订单号
    showPayment: false, //显示支付组件
    //显示日历选择
    show: false,
    order: null, //创建的订单-parse类型
    formatter: null, //标记被占用日期
    scope: null, //日历范围-今日至180天之后
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const {
      objectId,
      date_start,
      date_end,
    } = options;
    console.log(date_start,
      date_end, )
    let minDate = new Date()
    let maxDate = new Date()
    maxDate.setDate(maxDate.getDate() + 180)
    let scope = {
      minDate: minDate.getTime(),
      maxDate: maxDate.getTime()
    }
    this.setData({
      startTime: date_start,
      endTime: date_end,
      roomId: objectId,
      scope
    })
    this.refersh()
  },
  async refersh() {
    await this.getroom()
    this.getdate()

  },
  /** 获取房间信息*/
  async getroom() {
    let {
      startTime,
      endTime
    } = this.data
    let room = new Parse.Query('ShopRoom');
    room.include('shop', 'shop.user');
    let d = await room.get(this.data.roomId)
    let timeList = ['12:00', '14:00']
    if (d?.get('open_time')) {
      timeList = d?.get('open_time').split("-");
    }
    console.log(d.toJSON())
    startTime = new Date(startTime + ' ' + timeList[0])
    endTime = new Date(endTime + ' ' + timeList[1])

    await this.setData({
      room: d.toJSON(),
      startTime,
      endTime
    })
  },
  /** 用户入住离店日期，并生成日期范围和价格信息。*/
  async getdate() {
    let {
      startTime,
      endTime
    } = this.data
    var dataAll = dateServ.getDayAll(startTime, endTime);
    dataAll.pop()
    await this.setData({
      date02: `${dateF.formatTime('mm月dd日 入住',startTime)} - ${dateF.formatTime('mm月dd日 离店',endTime)}`,
      date: `${this.formatDate(startTime)} - ${this.formatDate(endTime)}`,
      count: dataAll.length
    })
    this.getTotalPrice()
  },

  /** 开日历*/
  async onDisplay() {
    let {
      roomId
    } = this.data
    let list = await sev.getRoomOccupiaDate(roomId)
    // console.log(list)
    let formatter = (day) => {
      let year = day.date.getFullYear()
      let month = day.date.getMonth()
      let date = day.date.getDate()
      let isSame = list.findIndex(item => item.year == year && item.month == month && item.date == date)
      if (isSame != -1) {
        day.topInfo = '被预定'
      }
      return day
    }
    this.setData({
      formatter,
      show: true
    });
  },
  /** 关日历*/
  onClose() {
    this.setData({
      show: false
    });
  },
  /** 选好日期点击完成后*/
  async onConfirm(event) {
    const [start, end] = event.detail;
    start.setHours(12, 0, 0);
    end.setHours(14, 0, 0);
    let {
      roomId
    } = this.data
    let isFree = await sev.isFree({
      from: start,
      to: end
    }, roomId)
    console.log(isFree)
    if (!isFree) {
      await this.onDisplay()
      wx.showToast({
        title: '时间段内存在被预定日期,请重新选择',
        icon: 'none'
      })
    } else {
      await this.setData({
        show: false,
        startTime: start,
        endTime: end,
      });
      this.getdate()
    }
  },

  /** 判断是否可创建订单*/
  judgeOrder() {
    let {
      room,
      name,
      mobile
    } = this.data
    console.log(name, mobile)
    if (!name || !mobile) {
      wx.showToast({
        title: '住客姓名或联系电话为空',
        icon: 'none',
      });
      return false
    }
    if (!real.isPoneAvailable(mobile)) {
      wx.showToast({
        title: '手机号有误',
        icon: 'none',
      });
      return false
    }
    return true
  },

  /**创建订单 */
  async submitOrder() {
    let now = new Date()
    tradeNo = "C" +
      String(now.getFullYear()) +
      (now.getMonth() + 1) +
      now.getDate() +
      now.getHours() +
      now.getMinutes() +
      now.getSeconds() +
      Math.random().toString().slice(-6);
    await this.setData({
      tradeNo
    })
    let {
      room,
      name,
      mobile,
      startTime,
      endTime,
      totalPrice,
      order,
      tradeNo
    } = this.data
    console.log(startTime,
      endTime, )
    let isPass = this.judgeOrder()
    if (!isPass) return
    this.getTotalPrice()

    let o = order
    if (!order?.id) {
      let now = new Date()
      tradeNo = "C" +
        String(now.getFullYear()) +
        (now.getMonth() + 1) +
        now.getDate() +
        now.getHours() +
        now.getMinutes() +
        now.getSeconds() +
        Math.random().toString().slice(-6);
      let Order = Parse.Object.extend("RoomOrder");
      o = new Order()
      o.set("company", {
        __type: 'Pointer',
        className: 'Company',
        objectId: company
      })
      o.set("user", {
        __type: 'Pointer',
        className: '_User',
        objectId: uid
      })
      o.set("room", {
        __type: 'Pointer',
        className: 'ShopRoom',
        objectId: room?.objectId
      })
      o.set("shopStore", {
        __type: 'Pointer',
        className: 'ShopStore',
        objectId: room?.shop?.objectId
      })
      o.set("orderNum", tradeNo);
      o.set("merber", room?.merber || 0);
      o.set('status', 105) //未支付
    }
    o.set("name", name);
    o.set("mobile", mobile);
    o.set("startTime", startTime);
    o.set("endTime", endTime);
    o.set("price", totalPrice || 0);
    try {
      order = await o.save()
      this.setData({
        tradeNo,
        order: o,
        showPayment: true,
      })
      wx.showToast({
        title: '已创建订单',
        icon: 'none'
      })
    } catch (error) {
      wx.showToast({
        title: '出错了请检查后重试',
        icon: 'error'
      })
    }
  },

  /**支付回调 */
  async acceptResult(e) {
    let {
      order,
      room
    } = this.data
    let {
      params
    } = e.detail
    if (params == 'ok') {
      wx.showLoading({
        title: '加载中',
      })
      order.set('status', 100)
      order.set('isPay', true)
      try {
        await order.save()
        // let userParse = Parse.User.current()
        // console.log(userParse?.get('invite'))
        // if (!userParse?.get('invite')) {
        //   let uid = Parse.User.current()?.id
        //   let a = await sev.bindShop(uid, room.shop?.objectId)
        //   console.log(a)
        // }
        setTimeout(() => {
          wx.hideLoading()
          wx.redirectTo({
            url: '/nova-tourism/pages/my/my-order/index?active=0',
          })
        }, 1000);
      } catch (error) {
        wx.showToast({
          title: '保存订单出错，请联系客服核对订单',
          icon: 'none'
        })
      }
    } else {
      wx.showToast({
        title: '支付失败',
        icon: 'none'
      })
    }
  },

  /**计算总价 */
  getTotalPrice() {
    let {
      room,
      count
    } = this.data
    let totalPrice = parseFloat(room?.price) * parseFloat(count)
    this.setData({
      totalPrice: parseFloat(totalPrice.toFixed(2) || 0) || 0
    })
  },
  /**获取日期格式 */
  formatDate(date) {
    date = new Date(date);
    const today = new Date();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const weekDays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
    const weekDay = weekDays[date.getDay()];
    let dateDescription = '';
    if (date.toDateString() === today.toDateString()) {
      dateDescription = '今天';
    } else if (date.toDateString() === new Date(today.getTime() + 86400000).toDateString()) {
      dateDescription = '明天';
    } else {
      dateDescription = weekDay;
    }
    return `${month}月${day}日 ${dateDescription}`;
  },
  /** 发送短信*/
  formSubmit() {
    wx.request({
      url: 'https://server.fmode.cn/api/apig/message',
      method: "post", //请求方式
      data: {
        company: 'EbxZUK5lBI',
        mobile: '15279240198',
        templateId: '28754',
        apiName: 'message',
      },
      success(res) {
        console.log(res);
      }
    })
  },


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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

})