// 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: {
    orderType: 1,
    floorIndex: 0,
    seatIndex: 0,
    showLimit: 3,
    meals_num: 1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    app.globalData.business_id = options.business_id;
    let floorIndex = wx.getStorageSync('floorIndex') || 0,
      seatIndex = wx.getStorageSync('seatIndex') || 0;
    wx.showLoading({
      title: 'Loading',
      mask: true
    })
    this.checkHack()
    this.getStoreInfo()    // 获取商店信息
    this.getTableInfo()    // 获取桌位信息
    // 获取当前时间
    this.setData({ startTime, targetTime: startTime, floorIndex, seatIndex })
  },

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

  },

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

    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: app.globalData.share_title,
      path: '/pages/index/index?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) => {
        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) => { },
    })
  },
  // 获取桌位号信息
  getTableInfo() {
    let that = this
    var business_id = app.globalData.business_id;
    console.log(business_id)
    wx.request({
      url: hostname + 'Order/get_seats',
      data: { business_id },
      header: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;' },
      method: 'POST',
      dataType: 'JSON',
      success: function (res) {
        let tableInfo = JSON.parse(res.data).data,
          floorList = [],
          seatList = [],
          index = 0
          
        for (let i in tableInfo) {
          floorList.push(i)
          seatList[index] = []
          tableInfo[i].forEach((value) => {
            seatList[index].push(value)
          })
          index++
        }
        console.log(floorList)
        console.log(seatList,2)
        that.setData({ seatList, floorList, tableInfo })
      },
      fail: (res) => { },
      complete: (res) => { },
    })
  },
  // 查看更多
  viewMore(e) {
    let { showLimit } = this.data
    showLimit = showLimit > 3 ? 3 : 999
    this.setData({ showLimit })
  },
  // 切换楼层
  selectFloor(e) {
    this.setData({ floorIndex: e.detail.value })
  },
  // 切换座位
  selectSeat(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(e) {
    this.setData({ mark: e.detail.value })
  },
  // 选择时间
  selectTime(e) {
    this.setData({ targetTime: e.detail.value })
  },
  // 提交订单并请求支付
  submitOrder(e) {
    wx.showLoading({
      title: '提交中...',
    })
    let { orderType, goodsList, mark = '', targetTime, seatIndex, meals_num, seatList, floorIndex, floorList } = this.data,   // 1为点餐  2为外卖
      car_content = [],
      users_id = wx.getStorageSync('users_id'),
      seat = null
    console.log("楼层号", floorList)
    console.log("座位号号", seatList)
    // 拼接座位信息
    seat = floorList[floorIndex] + ' ' + seatList[floorIndex][seatIndex]
    // 处理商品数据
    goodsList.forEach((value) => {
      car_content.push({
        'goods_id': Number(value.goods_id),
        'goods_num': value.count,
        'sum_price': Calc.mul(value.count, value.price).toFixed(2)
      })
    })
    car_content = JSON.stringify(car_content)
    if (orderType == 1) {
      var business_id = app.globalData.business_id;
      console.log(business_id)
      wx.request({
        url: hostname + 'Order/create_order',
        data: {
          business_id,
          users_id,
          car_content,
          mark,
          order_type: 2,
          seat,
          meals_num
        },
        header: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;' },
        method: 'POST',
        dataType: 'JSON',
        success: (res) => {
          let result = JSON.parse(res.data)
          if (result.status == 1) {
            wx.showToast({
              title: '下单成功',
              success: (res) => {
                wx.removeStorage({
                  key: 'cart',
                  success: function (res) {
                    let { order_sn } = result.data
                    wx.request({
                      url: hostname + 'api/paymoney',
                      data: { order_num: order_sn },
                      success: function (res) {
                        if (res.statusCode == 200) {
                          console.log(res)
                          // wx.request({
                          //   url: hostname + 'api/paychange',
                          //   data: {
                          //     trade_no: order_sn,
                          //     transaction_id: Date.parse(new Date())
                          //   },
                          //   success: (res) => {
                          //     console.log(res)
                          //     wx.showToast({
                          //       title: '支付成功',
                          //       duration: 1500,
                          //       success: function (res) {
                          //         setTimeout(() => {
                          //           wx.switchTab({
                          //             url: '../order/order',
                          //           })
                          //         }, 1500)
                          //       }
                          //     })
                          //   }
                          // })
                          wx.requestPayment({
                            timeStamp: res.data.timeStamp.toString(),
                            nonceStr: res.data.nonceStr,
                            package: res.data.package,
                            signType: res.data.signType,
                            paySign: res.data.paySign,
                            success: (res) => {
                              wx.showToast({
                                title: '支付成功',
                                duration: 1500,
                                success: function (res) {
                                  setTimeout(() => {
                                    wx.switchTab({
                                      url: '../order/order',
                                    })
                                  }, 1500)
                                }
                              })
                            },
                            fail: (res) => {
                              wx.showToast({
                                title: '支付失败',
                                duration: 1500,
                                image: '/images/toast/tips_icon.png',
                                success: function (res) {
                                  setTimeout(() => {
                                    wx.switchTab({
                                      url: '../order/order',
                                    })
                                  }, 1500)
                                }
                              })
                            },
                            complete: () => { }
                          })
                        }
                      },
                      fail: function (res) { },
                      complete: function (res) { },
                    })
                  },
                })
              }
            })
          }
        },
        fail: (res) => { },
        complete: (res) => { wx.hideLoading() },
      })
    } else if (orderType == 2) {
      let { name, phone, address_info, address_area, targetTime } = this.data
      if (name && phone && meals_num && address_info) {
        var business_id = app.globalData.business_id;
        wx.request({
          url: hostname + 'Order/create_order',
          
          data: {
            business_id,
            users_id,
            fachu_time: targetTime,
            address_name: name,
            address_phone: phone,
            address_area,
            address_info,
            mark,
            order_type: 1,
            car_content,
            meals_num
          },
          header: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;' },
          method: 'POST',
          dataType: 'JSON',
          success: (res) => {
            let result = JSON.parse(res.data)
            if (result.status == 1) {
              wx.showToast({
                title: '下单成功',
                success: (res) => {
                  wx.removeStorage({
                    key: 'cart',
                    success: function (res) {
                      let { order_sn } = result.data
                      wx.request({
                        url: hostname + 'api/paymoney',
                        data: { order_num: order_sn },
                        success: function (res) {
                          if (res.statusCode == 200) {
                            wx.requestPayment({
                              timeStamp: res.data.timeStamp.toString(),
                              nonceStr: res.data.nonceStr,
                              package: res.data.package,
                              signType: res.data.signType,
                              paySign: res.data.paySign,
                              success: (res) => {
                                wx.showToast({
                                  title: '支付成功',
                                  duration: 1500,
                                  success: function (res) {
                                    setTimeout(() => {
                                      wx.switchTab({
                                        url: '../order/order',
                                      })
                                    }, 1500)
                                  }
                                })
                              },
                              fail: (res) => {
                                wx.showToast({
                                  title: '支付失败',
                                  duration: 1500,
                                  image: '/images/toast/tips_icon.png',
                                  success: function (res) {
                                    setTimeout(() => {
                                      wx.switchTab({
                                        url: '../order/order',
                                      })
                                    }, 1500)
                                  }
                                })
                              },
                              complete: () => {
                                console.log(res)
                              }
                            })
                          }
                        },
                        fail: function (res) { },
                        complete: function (res) { },
                      })
                    },
                  })
                }
              })
            } else {
              wx.showModal({
                title: '提示',
                content: result.msg,
                showCancel: false,
                confirmColor: '##d31944'
              })
            }
          },
          fail: (res) => { },
          complete: (res) => { wx.hideLoading() },
        })
      } else {
        wx.hideLoading()
        wx.showModal({
          title: '提示',
          content: '请完善收货信息',
          showCancel: false,
          confirmColor: '##d31944'
        })
      }
    }
  }
})
