// 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: false,
    pay2: true,
    selcindex:0,
    orderType: 1,
    floorIndex: 0,
    seatIndex: 0,
    showLimit: 3,
    meals_num: 1,
    pay_type: 1,
    hui: false,
    gostore: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;
    // var totalPrice;
    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(); //获取优惠券
    that.getSelfDetail(); //获取用户个人信息
    // that.getGoodsInfo() // 获取商品信息qqqq
    // 获取当前时间
    this.setData({
      startTime,
      targetTime: startTime,
      qucanTime: startTime,
      floorIndex,
      seatIndex,
      finalPrice: options.finalPrice,
      // totalPrice: this.data.finalPrice
    })
    console.log(this.data.finalPrice, "finalPricefinalPricefinalPrice")
    // 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
    console.log(that.data.totalPrice)
    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(res.data)
        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 = []
        console.log(total, data,"datadatadata")
        for (let i in data) {
          if (Number(total) >= Number(data[i].full_money)) {
            console.log(total, data, "datadatadata")
            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()
  },

  //获取用户个人信息
  getSelfDetail() {
    let that = this;
    wx.request({
      url: hostname + 'Order/get_link',
      data: {
        user_id: wx.getStorageSync('users_id')
      },
      header: {
        'Content-type': 'application/x-www-form-urlencoded;charset=utf-8;'
      },
      method: 'POST',
      dataType: 'JSON',
      success: function(res) {
        // console.log(res.data,"获取个人信息")
        // let that = this,
        // selfDetail = res.data,
        // selfDetailData = res.data.data;
        // this.setData({
        //   selfDetail: selfDetail,
        //   selfDetailData: selfDetailData
        // })

        let data = JSON.parse(res.data),
          // let data = res.data,
          name_info = data.data.name,
          phone_info = data.data.phone;
        that.setData({
          name_info: name_info,
          phone_info: phone_info
        })
        // console.log(name_info, phone_info,"selfDetailselfDetailselfDetail")
      }
    })
  },
  // 获取商店信息
  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.hideLoading()
    that.setData({
      sendAble: !(that.data.finalPrice < Number(that.data.storeInfo.up_to_send))
    })
    // 请求商品价格
    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((value) => {
          //   goodsArr.push(value.id)
          // })

          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({
            goodsList,
            totalPrice,
            cart
          })
          console.log(goodsList, totalPrice, cart, "goodsList, totalPrice, cart")
          that.getPrelist();

        } else {}
        wx.hideLoading()
      },
    })
    // 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: 'gcj02',
      altitude:true,
      success: (res) => {
        let {
          latitude,
          longitude
        } = res
        console.log(res,"dsadasd")
        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}`,
              latlocation = data.result.location.lat,
              lnglocation = data.result.location.lng;
            that.setData({
              address_info,
              address_area,
              latlocation,
              lnglocation
            })
            // console.log(address_info, address_area, latlocation, lnglocation,"地址地址地址")
          },
          fail: (res) => {},
          complete: (res) => {},
        })
      },
      fail: (res) => {}
    })
  },

  // 选择下单方式
  selctChange: function (e) {
    let that = this,
      selcindex = that.data.selcindex,
      orderType = that.data.orderType,
      orderid = e.currentTarget.dataset.orderid,
      selcid = e.currentTarget.dataset.selcid;
      orderType = orderid;
    let endPrice;  
    that.setData({
      selcindex: selcid,
      orderType: orderid
    })

    console.log(orderType,"orderTypeorderTypeorderType")

    if (orderType == 1 && that.data.chooseCards) {
      endPrice = Number(that.data.finalPrice) - Number(that.data.chooseCards.pre_money)
      console.log(endPrice)
    }
    if (orderType == 3 && that.data.chooseCards) {
      endPrice = Number(that.data.finalPrice) - Number(that.data.chooseCards.pre_money)
      console.log(endPrice)
    }
    let storeInfo = that.data.storeInfo;
    let sendAble = that.data.sendAble;
    if (orderType == 2){
      if (storeInfo.is_on_waimai != 1) {
        wx.showModal({
          title: 'Tips',
          content: 'No takeaway service yet',
          showCancel:false
        })
        that.setData({
          orderType:1,
          selcindex:0
        })
      } else if (!sendAble){
        wx.showModal({
          title: 'Tips',
          content: 'No choice of delivery price',
          showCancel: false
        })
        that.setData({
          orderType: 1,
          selcindex: 0
        })
      } else{
        if (orderType == 2 && that.data.chooseCards) {
          endPrice = Number(that.data.dPrice) - Number(that.data.chooseCards.pre_money)
          console.log(endPrice)
        }
        if (orderType == 2) {
          // console.log(that.data.orderType,"dPricedPricedPrice")
          let {
          totalPrice,
        } = 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
          })
        }
      }
    }
    

    console.log(endPrice)
    this.setData({
      // orderType,
      endPrice
    })
    console.log(that.data.endPrice,that.data.dPrice,that.data.orderType,that.data.selcindex, selcid, "selcidselcidselcid")
  },

  // 切换订单类型
  switchOrderType(e) {
    let orderType = e.detail.value ? 2 : 1,
      that = this;
    let endPrice;
    console.log(that.data.chooseCards)
    console.log(orderType,"切换订单类型")
    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_info': value
        })
        break
      case 'phone':
        this.setData({
          'phone_info': 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
    })
  },
  // 选择到店用餐时间
  getMealTime(e) {
    this.setData({
      qucanTime: 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
          })
        }
      }
    })
  },


//   点击显示到店标识
  showGoStore:function(e){
    let that = this,
        orderType = that.data.orderType,
        gostore = that.data.gostore;
    console.log(that.data.orderType, that.data.gostore, "点击显示到店标识")
    if (gostore){
      console.log(1)
        that.setData({
          gostore: false,
          orderType:2
        })
        console.log(that.data.orderType, that.data.gostore,"orderType3")
      }else{
        console.log(2)
        that.setData({
          gostore: true,
          orderType:3
        })
        console.log(that.data.orderType, that.data.gostore,"orderType2")
      }
  },



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

    let that = this,
      formid = e.detail.formId;
      console.log(e,formid,"forforfor")

    // wx.showLoading({
    //   title: '提交中...',
    // })
    if (that.data.pay1 && Number(that.data.balanceInfo.balance) < Number(that.data.finalPrice)) {
      wx.showToast({
        title: 'Balance is not enough',
        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 cart = wx.getStorageSync('cart');
    let {
      orderType,
      goodsList,
      mark = '',
      targetTime,
      seatIndex,
      meals_num,
      seatList,
      floorIndex,
      floorList,
      pay_type,
      lnglocation,
      latlocation
    } = that.data, // 1为点餐  2为外卖
      car_content = [],
      users_id = wx.getStorageSync('users_id'),

      seat = null;

    console.log(lnglocation, latlocation)
    // 拼接座位信息
    seat = floorList[floorIndex] + ' ' + seatList[floorIndex][seatIndex]
    // 处理商品数据
    cart.forEach((value) => {
      car_content.push({
        'goods_id': Number(value.id),
        'goods_num': value.count,
        'sum_price': Calc.mul(value.count, value.price).toFixed(2),
        'attr_id': value.attr.join(',')
      })
    })
    car_content = JSON.stringify(car_content)
    console.log(car_content, "car_contentcar_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,
          lng: lnglocation,
          lat: latlocation
        },
        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: 'checkout success',
              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: 'Payment success',
                                duration: 1500,
                                success: function(res) {
                                  setTimeout(() => {
                                    wx.switchTab({
                                      url: '../order/order',
                                    })
                                  }, 1500)
                                }
                              })
                            },
                            fail: (res) => {
                              wx.showToast({
                                title: 'Failure to pay',
                                duration: 1500,
                                image: '/images/toast/tips_icon.png',
                                success: function(res) {
                                  setTimeout(() => {
                                    wx.navigateTo({
                                      url: '../order/order',
                                    })
                                  }, 1500)
                                }
                              })
                            },
                            complete: () => {}
                          })
                        }

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

                          let {
                            order_sn
                          } = result.data




                          wx.showToast({
                            title: 'Payment success',
                            duration: 1500,
                            success: function(res) {
                              setTimeout(() => {
                                wx.switchTab({
                                  url: '../order/order',
                                })
                              }, 1500)
                            }
                          })
                        }
                      },
                      fail: function(res) {},
                      complete: function(res) {},
                    })
                  },
                })
              }
            })
          } else {
            wx.showToast({
              title: 'Balance is not enough',
              duration: 1000,
              image: '../../images/tan.png',
            })
          }
        },
        fail: (res) => {},
        complete: (res) => {
          wx.hideLoading()
        },
      })
    } else if (orderType == 2) {
      console.log(this.data)

      let {
        name_info,
        phone_info,
        address_info,
        address_area,
        targetTime,
        pay_type
      } = this.data
      if (name_info && phone_info && 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_info,
            address_phone: phone_info,
            address_area,
            address_info,
            mark,
            order_type: 1,
            car_content,
            meals_num,
            user_pre_id: user_pre_id,
            pay_type,
            lng: lnglocation,
            lat: latlocation
          },
          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){
              console.log(result.status,"12331")
              wx.showModal({
                title: 'Tips',
                content: `Beyond the scope of delivery`,
                showCancel: false,
                confirmColor: '#067655'
              })
          }
            if (result.status == 1) {
              wx.showToast({
                title: 'checkout success',
                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: 'Payment success',
                                  duration: 1500,
                                  success: function(res) {
                                    setTimeout(() => {
                                      wx.switchTab({
                                        url: '../order/order',
                                      })
                                    }, 1500)
                                  }
                                })
                              },
                              fail: (res) => {
                                wx.showToast({
                                  title: 'Failure to pay',
                                  duration: 1500,
                                  image: '/images/toast/tips_icon.png',
                                  success: function(res) {
                                    setTimeout(() => {
                                      wx.navigateTo({
                                        url: '../order/order',
                                      })
                                    }, 1500)
                                  }
                                })
                              },
                              complete: () => {}
                            })
                          }
                        },
                        fail: function(res) {},
                        complete: function(res) {},
                      })
                    },
                  })
                }
              })
            }
            else {
              wx.showToast({
                title: 'Balance is not enough',
                duration: 1000,
                image: '../../images/tan.png',
              })
            }
          },
          fail: (res) => {},
          complete: (res) => {
            wx.hideLoading()
          },
        })
      } else {
        wx.hideLoading()
        wx.showModal({
          title: 'Tips',
          content: 'Please improve information',
          showCancel: false,
          confirmColor: '##d31944'
        })
      }
    } else if (orderType == 3){
      console.log("ordertype==314.21")
      let {
        name_info,
        phone_info,
        address_area,
        pay_type
      } = this.data
        let  qucan_time = that.data.qucanTime;
          console.log(qucan_time,"qucan")
          if (qucan_time && name_info && phone_info && meals_num) {
        var business_id = app.globalData.business_id;
        let user_pre_id = that.data.chooseCards ? that.data.chooseCards.id : ''
        // that.data.chooseCards.id || ''
        // 门店自提
        console.log(business_id, user_pre_id, qucan_time,"ordertype==314.21")
        wx.request({
          url: hostname + 'Order/create_order',

          data: {
            business_id,
            users_id,
            qucan_time: targetTime,
            mark,
            order_type: 3,
            car_content,
            meals_num,
            pay_type,
            address_name: name_info,
            address_phone: phone_info,

          },
          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: 'checkout success',
                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: 'Payment success',
                                  duration: 1500,
                                  success: function (res) {
                                    setTimeout(() => {
                                      wx.switchTab({
                                        url: '../order/order',
                                      })
                                    }, 1500)
                                  }
                                })
                              },
                              fail: (res) => {
                                wx.showToast({
                                  title: 'Failure to pay',
                                  duration: 1500,
                                  image: '/images/toast/tips_icon.png',
                                  success: function (res) {
                                    setTimeout(() => {
                                      wx.navigateTo({
                                        url: '../order/order',
                                      })
                                    }, 1500)
                                  }
                                })
                              },
                              complete: () => { }
                            })
                          }
                        },
                        fail: function (res) { },
                        complete: function (res) { },
                      })
                    },
                  })
                }
              })
            }
            else {
              wx.showToast({
                title: 'Balance is not enough',
                duration: 1000,
                image: '../../images/tan.png',
              })
            }
          },
          fail: (res) => { },
          complete: (res) => {
            wx.hideLoading()
          },
        })
      } else {
        wx.hideLoading()
        wx.showModal({
          title: 'Tips',
          content: 'Please improve information',
          showCancel: false,
          confirmColor: '##d31944'
        })
      }
    }
  }
})

function sortJ(a, b) {
  return b.full_money - a.full_money
}