// pages/confirmOrder/confirmOrder.js
import { CalcMethod } from '../../utils/comm.js'
const app = getApp(),
  { hostname, business_id } = app.globalData,
  Calc = new CalcMethod(),
  startHour = new Date().getHours().toString().length < 2 ? 0 + new Date().getHours().toString() : new Date().getHours().toString(),
  startMin = new Date().getMinutes().toString().length < 2 ? 0 + new Date().getMinutes().toString() : new Date().getMinutes().toString(),
  startTime = startHour + ':' + startMin
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrls: [
    ],
    pictures: [],
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    orderType: 1,
    floorIndex: 0,
    seatIndex: 0,
    showLimit: 3,
    meals_num: 1,
    time: '',
    time_interval: [
      "Morning",
      "Afternoon",
      "Evening"
    ],
    time_intervalIndex: 0,
    imgbBefore: 'https://jisu.shenmikj.com/canyin2/Uploads/'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    console.log(options)
    if (options.business_id) {
      app.globalData.business_id = options.business_id;
    }

    let floorIndex = wx.getStorageSync('floorIndex') || 0,
      seatIndex = wx.getStorageSync('seatIndex') || 0;
    // wx.showLoading({
    //   title: 'Loading',
    //   mask: true
    // })
    let newDay = new Date(),
      year = newDay.getFullYear(),
      month = newDay.getMonth() + 1,
      day = newDay.getDate(), //获取当前日(1-31)  
      time = (year.toString() + '-' + month.toString() + '-' + day.toString());
    this.setData({
      time
    })

    console.log(this.data.startDate)
    this.checkHack()
    // this.getStoreInfo()    // 获取商店信息
    this.getTableInfo()    // 获取桌位信息
    that.getSwiperImgUlrs(that)//获取轮播图片
    // 获取当前时间
    this.setData({ startTime, targetTime: startTime, floorIndex, seatIndex })
  },

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

  },

  /**
     * 用户点击右上角分享
     */
  onShareAppMessage: function (res) {
    var userid = wx.getStorageSync('users_id')
    // var userid = 1

    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: app.globalData.share_title,
      path: '/pages/confirm_appointment/confirm_appointment?u_openid=' + userid,
      success: function (res) {
        var pages = getCurrentPages()    //获取加载的页面
        var currentPage = pages[pages.length - 1]    //获取当前页面的对象
        //点击分享传进userid 截取userid 从onload拿到
        var url = currentPage.route + '?u_openid=' + userid;  //当前页面url
        console.log(url, '/pages/index/index?u_openid=' + userid);
      },
      fail: function (res) {
        // 转发失败
      },
    }
  },
  // // 获取商店信息
  // getStoreInfo() {
  //   let that = this
  //   var business_id = app.globalData.business_id
  //   wx.request({
  //     url: hostname + 'Goods/get_business_info',
  //     data: { business_id },
  //     header: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;' },
  //     method: 'POST',
  //     dataType: 'JSON',
  //     success: (res) => {
  //       console.log(res,"storeinfo")
  //       let storeInfo = JSON.parse(res.data).data
  //       storeInfo.delivery = storeInfo.delivery ? storeInfo.delivery : 0
  //       storeInfo.boxes = storeInfo.boxes ? storeInfo.boxes : 0
  //       storeInfo.up_to_send = storeInfo.up_to_send ? storeInfo.up_to_send : 0

  //       that.setData({ storeInfo })
  //       storeInfo.is_on_waimai > 0 && that.getLocationInfo()// 当商店支持外卖自动获取位置信息
  //       that.getGoodsInfo()    // 获取商品信息qqqq
  //     },
  //     fail: (res) => { },
  //     complete: (res) => { },
  //   })
  // },

  // 获取手机号姓名


  //获取轮播图图片
  getSwiperImgUlrs: function (that) {
    wx.request({
      url: app.globalData.hostname + 'Kaiguan/getChart',
      data: { business_id },
      header: { 'Content-type': 'application/x-www-form-urlencoded' },
      method: 'POST',
      dataType: '',
      success: function (res) {
        console.log(res, "轮播图片")
        if (res.statusCode == 200) {
          var imgUrls = [];
          var imgUrlsData = res.data.data;

          if (imgUrlsData.length != undefined) {
            for (var i = 0; i < imgUrlsData.length; i++) {
              imgUrls.push(imgUrlsData[i]);
            }
          }
          that.setData({
            imgUrls: imgUrls
          })
        } else {
          that.setData({
            imgUrls: []
          })
        }
      },
      fail: function (res) { },
      complete: function (res) {
        // that.getGoodsList(that, 1);
      },
    })
  },

  // 获取桌位号信息
  getTableInfo() {
    let that = this
    var business_id = app.globalData.business_id;
    wx.request({
      url: hostname + 'Order/get_reservation_seats',
      data: { business_id },
      header: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;' },
      method: 'POST',
      dataType: 'JSON',
      success: function (res) {
        console.log(res, "res")

        let tableInfo = JSON.parse(res.data).data,
          floorList = [],
          seatList = [],
          seatListT = [],
          index = 0

        for (let i in tableInfo) {
          floorList.push(i)
          seatList[index] = []
          seatListT[index] = []
          tableInfo[i].forEach((value) => {

            seatList[index].push(value.name)
            seatListT[index].push(value.table_id)
          })
          index++
        }
        console.log(seatListT)


        that.setData({ seatList, floorList, tableInfo, seatListT })
      },
      fail: (res) => { },
      complete: (res) => { },
    })
  },
  // 查看更多
  viewMore(e) {
    let { showLimit } = this.data
    showLimit = showLimit > 3 ? 3 : 999
    this.setData({ showLimit })
  },
  // 切换日期
  selectTime(event) {
    this.setData({
      time: event.detail.value
    })
  },
  // 切换楼层
  selectFloor(event) {
    this.setData({ floorIndex: event.detail.value })
  },
  //切换时段
  selectPeriod(e) {
    console.log(e)
    this.setData({ time_intervalIndex: e.detail.value })
  },
  // 切换座位
  selectSeat(e) {
    console.log(e)
    this.setData({ seatIndex: e.detail.value })
  },
  // 获取商品信息
  getGoodsInfo() {
    let cart = wx.getStorageSync('cart'),
      goodsArr = [],
      that = this
    cart.forEach((value) => { goodsArr.push(value.id) })
    goodsArr = JSON.stringify(goodsArr)
    // 请求商品价格
    wx.request({
      url: hostname + 'Order/get_goods_price',
      data: { ids: goodsArr },
      header: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;' },
      method: 'POST',
      dataType: 'JSON',
      success: (res) => {
        if (res.statusCode && JSON.parse(res.data).status == 1) {
          let goodsList = JSON.parse(res.data).data,
            totalPrice = 0
          cart.forEach((cartItem) => {
            goodsList.forEach((value, index) => {
              if (cartItem.id == value.goods_id) {
                value.count = cartItem.count
                totalPrice = Calc.add(totalPrice, Calc.mul(value.price, value.count))
              }
            })
          })
          that.setData({ sendAble: !(totalPrice < Number(that.data.storeInfo.up_to_send)) })
          totalPrice = totalPrice.toFixed(2)
          that.setData({ goodsList, totalPrice })
        } else {
          wx.showModal({
            content: JSON.parse(res.data).msg,
            showCancel: false,
            confirmColor: '#d31944'
          })
        }
        wx.hideLoading()
      },
      fail: (res) => { },
      complete: (res) => { },
    })
  },
  // checkHack
  checkHack() {
    let that = this
    wx.request({
      url: hostname + 'Goods/get_info',
      success: function (res) {
        that.setData({ checkHack: res.data })
      }
    })
  },
  // 获取定位信息
  getLocationInfo() {
    let that = this
    wx.getLocation({
      type: 'wgs84',
      success: (res) => {
        let { latitude, longitude } = res
        wx.request({
          url: 'https://apis.map.qq.com/ws/geocoder/v1/?location=' + latitude + ',' + longitude + '&key=J24BZ-LHMHD-7M74C-HD2OF-DPTL6-WCBII',
          dataType: 'JSON',
          success: (res) => {
            let data = JSON.parse(res.data),
              address_info = data.result.formatted_addresses.recommend,
              address_area = `${data.result.address_component.province}${data.result.address_component.city}${data.result.address_component.district}`
            that.setData({ address_info, address_area })
          },
          fail: (res) => { },
          complete: (res) => { },
        })
      },
      fail: (res) => { }
    })
  },
  // 切换订单类型
  switchOrderType(e) {
    let orderType = e.detail.value ? 2 : 1,
      that = this
    if (orderType == 2) {
      setTimeout(() => {
        let { totalPrice, storeInfo } = this.data
        totalPrice = Calc.add(Calc.add(totalPrice, storeInfo.delivery), storeInfo.boxes)
        totalPrice = totalPrice.toFixed(2)
        that.setData({ scrollTop: 999999, dPrice: totalPrice })
      }, 100)
    }
    this.setData({ orderType })
  },
  // 记录收货信息
  syncDelivery(e) {
    let { attr } = e.currentTarget.dataset,
      { value } = e.detail
    switch (attr) {
      case 'name':
        this.setData({ 'name': value })
        break
      case 'phone':
        this.setData({ 'phone': value })
        break
      case 'address':
        this.setData({ 'address_info': value })
        break
      case 'meals_num':
        this.setData({ 'meals_num': value })
        break
    }
  },
  // 记录备注信息
  syncRemarks(event) {
    this.setData({
      mark: event.detail.value
    })
  },
  // 选择时间
  selectTime(event) {
    this.setData({
      time: event.detail.value
    })
  },

  // 选择时间段
  selectTime_interval(event) {
    this.setData({
      time_interval: event.detail.value
    })
  },

  // 选择座位号
  selectTable_id(event) {
    console.log(event)

    this.setData({
      table_id: event.detail.value
    })
  },

  // getMobile(event) {
  //   this.setData({
  //     mobile: event.detail.value
  //   })
  // },

  // getName(event) {

  //   this.setData({
  //     name: event.detail.value
  //   })
  // },

  // getNums(event) {
  //   this.setData({
  //     nums: event.detail.value
  //   })
  // },

  //提交预约格式要求

  // btnask()



  //姓名
  getName: function (event) {
    this.setData({
      name: event.detail.value,
    })
  },
  //手机号
  getMobile: function (event) {
    this.setData({
      mobile: event.detail.value,
    })
  },
  // 获取输入框内人数
  getNums(event) {
    this.setData({
      nums: event.detail.value
    })
  },

  //取消或确认提交申请分销
  appbtn: function (e) {
    var that = this;
    var kind = e.currentTarget.dataset.kind;
    if (kind == 'cancle') {
      that.setData({
        showApply: false,
      })
    } else {
      //   var applyData = that.data.applyData;

      var errorContent;
      var reg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
      var phoneValid = reg.test(that.data.mobile);
      if (that.data.nums == undefined || that.data.nums == '' || that.data.nums == 0) {
        errorContent = '请输入人数';
      } else if (that.data.name == undefined || that.data.name == '') {
        errorContent = '请输入姓名';
      } else if (that.data.mobile == undefined || that.data.mobile == '') {
        errorContent = '请输入电话';
      } else if (!phoneValid) {
        errorContent = '请输入正确的手机号码';
      }
      if (errorContent) {
        wx.showModal({
          title: '温馨提示',
          content: errorContent,
          showCancel: false,
        })
        return false;
      }
      // console.log(applyData,'applyData');

      that.sureBtn(e)
    }
  },

  // 提交预订按钮

  sureBtn(e) {
    console.log(e)
    let that = this,
      { floorList, floorIndex, seatList, seatListT, seatIndex } = this.data,
      table_id = null;
    console.log(seatListT[floorIndex][seatIndex])

    // 拼接座位信息
    table_id = seatListT[floorIndex][seatIndex];

    wx.showModal({
      title: '预约',
      content: '是否确定预约',
      success: function (res) {
        if (res.confirm) {
          console.log(that.data.seatList[that.data.floorIndex][that.data.seatIndex])
          wx.request({
            url: hostname + 'Order/create_app_order',
            data: {
              mobile: that.data.mobile,
              name: that.data.name,
              nums: that.data.nums,
              time: that.data.time,
              time_interval: Number(that.data.time_intervalIndex) + 1,
              business_id,
              user_id: wx.getStorageSync("users_id"),
              table_id
              // openId: wx.getStorageSync("openId"),
            },
            header: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;' },
            method: 'POST',
            dataType: 'JSON',
            success: function (res) {
              console.log(res, "123")
              // wx.showToast({
              //   title: '预约成功',
              // }, 1500)      
            }
          })

          wx.showToast({
            title: '预约成功',
            success: setTimeout(() => {
              wx.switchTab({
                url: '../order/order',
              })
            }, 1500)
          })
        } else if (res.cancel) {
          wx.showToast({
            title: '取消成功',
          })
        }
      }
    })











  },















  // 预约按钮
  appointmentOrder() {

  }
})
