let Parse = getApp().Parse;
const company = getApp().globalData.company
const rechText = require('../../../../../../utils/rech-text');
const login = require('../../../../../../utils/login')
const dateF = require('../../../../../../utils/date')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: "",
    goods: {},
    shopstore: {},
    number: 1,
    prices: null,
    gid: null,
    show: false,
    sid: null,
    oid: null

  },
  onChange(event) {
    let number = event.detail
    console.log(number);
    let prices = (this.data.goods.price * number)
    console.log(prices);
    this.setData({
      number: number,
      prices: prices
    })
  },
  async getorder() {
    let oid = this.data.oid
    let shopOrder
    let ShopOrder = new Parse.Query("ShopOrder")
    shopOrder = await ShopOrder.get(oid)
    shopOrder.set("status", 200)
    shopOrder.save().then(res => {
      console.log(res)
    })
  },
  submit() {
    let userLogin = wx.getStorageSync("userLogin");
    if (userLogin == "") {
      login.loginNow();
      return;
    }
    this.setData({
      show: true
    })
    let _this = this
    //生成订单号
    let now = new Date()
    let tradeNo = "C" +
      String(now.getFullYear()) +
      (now.getMonth() + 1) +
      now.getDate() +
      now.getHours() +
      now.getMinutes() +
      now.getSeconds() +
      Math.random().toString().slice(-6); //生成六位随机数
    this.setData({
      tradeNo: tradeNo
    })
    console.log(this.data.prices, this.data.shopstore.storeName, tradeNo, this.data.goods.name, this.data.gid, this.data.sid)
    let ShopOrder = Parse.Object.extend("ShopOrder")
    let shopOrder = new ShopOrder()
    shopOrder.set("orderNum", tradeNo)
    shopOrder.set("price", this.data.prices)
    shopOrder.set("type", 'meal')
    shopOrder.set("image", this.data.goods.image)
    shopOrder.set("status", 100)
    shopOrder.set("count", this.data.number)
    shopOrder.set("name", this.data.goods.name)
    shopOrder.set("goods", {
      __type: 'Pointer',
      className: 'ShopGoods',
      objectId: this.data.gid
    })
    shopOrder.set("shopStore", {
      __type: 'Pointer',
      className: 'ShopStore',
      objectId: this.data.sid
    })
    shopOrder.set("company", {
      __type: 'Pointer',
      className: 'Company',
      objectId: company
    })
    shopOrder.set("user", {
      __type: 'Pointer',
      className: '_User',
      objectId: Parse.User.current().id
    })

    shopOrder.save().then(res => {
      console.log(res)
      _this.setData({
        oid: res.id
      })
    })
  },
  async acceptResult(e) {
    let {
      activeOrder,
      tradeNo,
      oid
    } = this.data
    let that = this
    let {
      params,
      no
    } = e.detail;
    that.setData({
      show: false
    })
    try {
      if (params == "ok") {
        // activeOrder.set("status", 200)
        // activeOrder.set("isPay", true)
        await that.getorder()
        // await activeOrder.save()
        this.print_order(oid, tradeNo)
        wx.showToast({
          title: '购买成功',
          icon: 'none',
          image: '',
          duration: 1500,
          mask: false,
        });
        wx.navigateBack({
          delta: 2,
        })
      } else {
        wx.showToast({
          title: '支付失败，取消订单',
          icon: 'none',
          image: '',
          duration: 1500,
          mask: false,
        });
      }
    } catch (error) {
      console.log(error)
      wx.showToast({
        title: "支付失败",
        icon: "error",
        duration: 1500,
      });
      wx.hideLoading()
    }
  },
  //用户下单成功，打印订单
  async print_order(orderid, orderNumber) {
    let {
      prices,
      goods,
      sid
    } = this.data
    let orders = [{
      name: goods.name,
      num: 1,
      price: goods.price.toFixed(2)
    }]
    let servece = 0
    let mobile = '18866666666'
    let address = '堂食到店'
    let dev_code = await this.getPrint()
    let user = Parse.User.current()
    if(user.get('mobile')){
      mobile = user.get('mobile')
    }
    let data = {
      dev_code: dev_code,
      cid: company,
      order_id: orderid,
      orderNumber: orderNumber,
      price: prices,
      orders: orders,
      name: user.get('nickname'),
      mobile: mobile,
      address: address,
      servece: servece,
      desc: '用户下单',
      storeid:sid,
    }
    console.log(data);
    wx.request({
      url: 'https://test.fmode.cn/api/print-dev/dev',
      data: data,
      header: {
        'content-type': 'application/json'
      },
      method: 'POST',
      dataType: 'json',
      responseType: 'text',
      success: (result) => {
        console.log(result);
      },
      fail: () => {},
      complete: () => {}
    });
  },
  //获取打印机设备
  async getPrint() {
    let query = new Parse.Query("PrintDevice")
    query.equalTo("company", company)
    let res = await query.first()
    if (res && res.id) {
      return res.get("code")
    }
  },
  async getShopgoods() {
    let id = this.data.id
    let query = new Parse.Query('ShopGoods')
    query.include('shopStore')
    let shopGoods = await query.get(id)
    let goods = shopGoods.toJSON()
    if (goods.details) {
      goods.details = rechText.formatRichText(goods.details)
    }
    let gid = shopGoods.id //套餐id
    let prices = goods.price * this.data.number
    this.setData({
      goods,
      prices,
      gid
    })
    this.getShopStore()
  },
  async getShopStore() {
    let storeId = this.data.goods.shopStore.objectId
    let ShopStore = new Parse.Query('ShopStore')
    let shopstore = await ShopStore.get(storeId)
    this.setData({
      shopstore: shopstore.toJSON(),
      sid: storeId
    })
  },
  taxi() {
    let latitude = this.data.shopstore.location.latitude;
    let longitude = this.data.shopstore.location.longitude;
    console.log(latitude, longitude);
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success() {
        wx.openLocation({
          latitude,
          longitude,
          scale: 18
        })
      }
    })
  },
  phone() {
    let phone = this.data.shopstore.mobile
    console.log(phone);
    wx.makePhoneCall({
      phoneNumber: phone
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      activeColor:getApp().globalData.activeColor || '#229293'
  })
    let id = options.id
    let events = {
      detail: 0
    }
    this.setData({
      id: id,
      events: events
    })
    this.getShopgoods()
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})