// 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: {
    pay1: true,
    pay2: false,
    orderType: 1,
    floorIndex: 0,
    seatIndex: 0,
    showLimit: 3,
    meals_num: 1,
    pay_type: 2,
    hui: false

  },

  //余额支付
  yuepay: function (e) {
    var that = this;
    var pay_type = e.currentTarget.dataset.pay_type
    // console.log(that.data.balanceInfo.balance, that.data.finalPrice, Number(that.data.balanceInfo.balance) < Number(that.data.finalPrice))
    if (that.data.hui == true) {
      that.setData({
        pay1: false,
        pay2: true,
        pay_type: 1
      })
    } else {
      that.setData({
        pay1: true,
        pay2: false,
        pay_type: pay_type
      })
    }

  },

  //微信支付
  weixin: function (e) {
    var that = this;
    var pay_type = e.currentTarget.dataset.pay_type
    that.setData({
      pay1: false,
      pay2: true,
      pay_type: pay_type
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    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()    // 获取桌位信息
    that.getCardsMoney();  // 获取余额信息
    that.getPrelist();    //获取优惠券
    // 获取当前时间
    this.setData({ startTime, targetTime: startTime, floorIndex, seatIndex, finalPrice: options.finalPrice })
    // this.orderReduction(that)
  },

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

  },

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

    if (res.from === 'button') {
      // 来自页面内转发按钮
    }
    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
      },
      fail: function (res) {
        // 转发失败
      },
    }
  },
  // 获取优惠券
  getPrelist() {
    let that = this
    wx.request({
      url: hostname + 'Pre/pre_list',
      data: { openid: wx.getStorageSync('openId'), business_id: app.globalData.business_id, page: 1 },
      header: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;' },
      method: 'POST',
      dataType: 'JSON',
      success: (res) => {
        console.log(JSON.parse(res.data), 123132)
        if (res.data.status == 1) {
          let data = JSON.parse(res.data).data.sort(sortJ)
        }
        let data = JSON.parse(res.data).data.sort(sortJ);
        let total = that.data.totalPrice
        let cards = []

        for (let i in data) {
          if (Number(total) >= Number(data[i].full_money)) {
            cards.push({ 'name': '满' + data[i].full_money + '减' + data[i].pre_money, 'pre_money': data[i].pre_money, 'id': data[i].id })
            that.setData({ cards })
          }
        }
        console.log(cards, "cards")
      },
      fail: (res) => { },
      complete: (res) => { },
    })
  },
  // 选择优惠券
  bindPickerChange(e) {
    let idx;
    if (e) {
      idx = e.detail.value
    }

    console.log(this.data.cards[idx])
    let chooseCards = this.data.cards[idx]
    let endPrice;
    if (this.data.orderType == 1) {
      endPrice = Number(this.data.finalPrice) - Number(chooseCards.pre_money)
    } else {
      endPrice = Number(this.data.dPrice) - Number(chooseCards.pre_money)
    }

    console.log(endPrice)
    this.setData({ chooseCards, endPrice })
    // console.log()
  },
  // 获取商店信息
  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;
    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++
        }
        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))
                console.log(totalPrice, that.data.finalPrice)
                if (totalPrice !== that.data.finalPrice) {
                  totalPrice = Number(that.data.finalPrice);
                }
              }
            })
          })
          that.setData({ sendAble: !(totalPrice < Number(that.data.storeInfo.up_to_send)) })
          totalPrice = totalPrice.toFixed(2)
          that.setData({ goodsList, totalPrice })
          that.getPrelist()
        } 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;
    let endPrice;
    console.log(that.data.chooseCards)

    if (orderType == 1 && that.data.chooseCards) {
      endPrice = Number(that.data.finalPrice) - Number(that.data.chooseCards.pre_money)
      console.log(endPrice)
    }
    if (orderType == 2 && that.data.chooseCards) {
      endPrice = Number(that.data.dPrice) - Number(that.data.chooseCards.pre_money)
      console.log(endPrice)
    }
    if (orderType == 2) {
      setTimeout(() => {

        let { totalPrice, storeInfo } = this.data

        totalPrice = Calc.add(Calc.add(totalPrice, storeInfo.delivery), storeInfo.boxes)
        totalPrice = totalPrice.toFixed(2)
        console.log(totalPrice)
        that.setData({ scrollTop: 999999, dPrice: totalPrice })
      }, 100)
    }
    console.log(endPrice)
    this.setData({ orderType, endPrice })


  },
  // 记录收货信息
  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 })
  },


  // 价格满减
  // orderReduction(that) {
  //   wx.request({
  //     url: hostname + 'Order/reduction',
  //     header: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' },
  //     method: 'POST',
  //     data: { business_id: app.globalData.business_id },
  //     success: function (res) {
  //       let allself = res.data.data,
  //         fs = that.data,

  //         newallself = [];

  //       对数组进行排序
  //       function compare(property) {
  //         return function (a, b) {
  //           var value1 = a[property];
  //           var value2 = b[property];
  //           return value1 - value2;
  //         }
  //       }
  //       allself = allself.sort(compare('full_money')).reverse();
  //       allself.forEach((v) => {
  //         if (Number(goods_price) > Number(v.full_money)) {
  //           goods_price = goods_price - v.reduction_money
  //           that.setData({
  //             selfprice: goods_price
  //           })
  //           return
  //         }

  //       })
  //     }
  //   })
  // },

  // 获得储蓄卡余额
  getCardsMoney() {
    let that = this
    wx.request({
      url: hostname + 'Cards/balance',
      data: {
        openid: wx.getStorageSync("openId"),
        business_id: app.globalData.business_id/*  */
      },
      header: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' },
      method: 'POST',
      success: function (res) {
        console.log(res, "充值余额")
        if (res.data.status == 1) {
          that.setData({
            balanceInfo: res.data.data
          })
        }
      }
    })
  },




  // 提交订单并请求支付
  submitOrder(e) {

    let that = this

    wx.showLoading({
      title: '提交中...',
    })
    if (that.data.pay1 && Number(that.data.balanceInfo.balance) < Number(that.data.finalPrice)) {
      wx.showToast({
        title: '余额不足！',
        duration: 1000,
        image: '../../images/tan.png',
        success: function () {
          // console.log('余额不足')
          setTimeout(function () {
            that.setData({
              pay1: false,
              pay2: true,
              hui: true,
              pay_type: 1
            })
          }, 500)
        }
      })
    }
    let { orderType, goodsList, mark = '', targetTime, seatIndex, meals_num, seatList, floorIndex, floorList, pay_type } = this.data,   // 1为点餐  2为外卖

      car_content = [],
      users_id = wx.getStorageSync('users_id'),
      seat = null;
    console.log(pay_type)
    // 拼接座位信息
    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;
      let user_pre_id = that.data.chooseCards ? that.data.chooseCards.id : ''

      wx.request({
        url: hostname + 'Order/create_order',
        data: {
          business_id,
          users_id,
          car_content,
          mark,
          order_type: 2,
          seat,
          meals_num,
          user_pre_id: user_pre_id,
          pay_type,
        },
        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) {
                        console.log(res)
                        if (res.statusCode == 200 && res.data.code !== 200) {
                          // wx.request({
                          //   url: hostname + 'api/paychange',
                          //   data: {
                          //     trade_no: order_sn,
                          //     transaction_id: Date.parse(new Date())
                          //   },
                          //   success: (res) => {
                          //     wx.showToast({
                          //       title: '支付成功',
                          //       duration: 1500,
                          //       success: function (res) {
                          //         setTimeout(() => {
                          //           wx.switchTab({
                          //             url: '../order/order',
                          //           })
                          //         }, 1500)
                          //       }
                          //     })
                          //   }
                          // })
                          wx.requestPayment({
                            timeStamp: res.data.timeStamp,
                            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: () => { }
                          })
                        }

                        //  双状态为200成功时
                        if (res.statusCode == 200 && res.data.code == 200) {

                          let { order_sn } = result.data




                          wx.showToast({
                            title: '余额支付成功',
                            duration: 1500,
                            success: function (res) {
                              setTimeout(() => {
                                wx.switchTab({
                                  url: '../order/order',
                                })
                              }, 1500)
                            }
                          })
                        }
                      },
                      fail: function (res) { },
                      complete: function (res) { },
                    })
                  },
                })
              }
            })
          } else {
            wx.showToast({
              title: '余额不足！',
              duration: 1000,
              image: '../../images/tan.png',
            })
          }
        },
        fail: (res) => { },
        complete: (res) => { wx.hideLoading() },
      })
    } else if (orderType == 2) {
      console.log(this.data)
      let { name, phone, address_info, address_area, targetTime, pay_type } = this.data
      if (name && phone && meals_num && address_info) {
        var business_id = app.globalData.business_id;
        let user_pre_id = that.data.chooseCards ? that.data.chooseCards.id : ''
        // that.data.chooseCards.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,
            user_pre_id: user_pre_id,
            pay_type,
          },
          header: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;' },
          method: 'POST',
          dataType: 'JSON',
          success: (res) => {
            console.log(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: () => {
                              }
                            })
                          }
                        },
                        fail: function (res) { },
                        complete: function (res) { },
                      })
                    },
                  })
                }
              })
            } else {
              wx.showToast({
                title: '余额不足！',
                duration: 1000,
                image: '../../images/tan.png',
              })
            }
          },
          fail: (res) => { },
          complete: (res) => { wx.hideLoading() },
        })
      } else {
        wx.hideLoading()
        wx.showModal({
          title: '提示',
          content: '请完善收货信息',
          showCancel: false,
          confirmColor: '##d31944'
        })
      }
    }
  }
})
function sortJ(a, b) {
  return b.full_money - a.full_money
}