let util = require('../../../utils/util.js');
var that
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isPinkage: false,
    freight: 0,
    salesPrice: 0,
    addressname: '',
    customerid: 0,
    customeronlyid: '',
    addressid: 0,
    addressonlyid: '',
    isReceivables: false,
    isPayment: false,
    payWayarray: [],
    payWayindex: 0,

    deliveryTypeArray: [{
      key: 1,
      name: '快递'
    }, {
      key: 2,
      name: '上门'
    }, {
      key: 3,
      name: '自取'
    }],
    deliveryTypeIndex: 0,
    deliveryType: 1,
    realReceive: 0
  },
  deliveryTypeChange(e) {
    this.setData({
      deliveryTypeIndex: e.detail.value,
      deliveryType: this.data.deliveryTypeArray[e.detail.value].key
    })
  },
  freshdebt() {
    if (this.data.isReceivables) {
      this.setData({
        debt: parseFloat(parseFloat(this.data.salesPrice ? this.data.salesPrice : 0) - parseFloat(this.data.realReceive ? this.data.realReceive : 0)).toFixed(2)
      })
    }
  },
  freshsalesPrice() {
    var salesPrice = 0
    this.data.goods.forEach(function(e) {
      salesPrice += parseFloat((e.sale ? e.sale : 0) * (e.num ? e.num : 0))
    })
    this.setData({
      salesPrice: salesPrice.toFixed(2)
    })
    this.freshdebt()
  },
  payWayChange(e) {
    this.setData({
      payWayindex: e.detail.value,
      payWay: this.data.payWayarray[e.detail.value].key,
      payWayname: this.data.payWayarray[e.detail.value].name
    })
  },
  setrealReceive(e) {
    this.setData({
      realReceive: util.PointNum(e.detail.value)
    })
    this.freshdebt()
  },
  save() {
    // if (!this.data.customerid) {
    //   util.showToast('请选择收货人')
    //   return
    // }
    var goods = []
    this.data.goods.forEach(function(e) {
      goods.push({
        goods: {
          id: e.goodid,
          onlyID: e.goodonlyid
        },
        goodsBatch: {
          id: e.goodsBatchid,
          onlyID: e.goodsBatchonlyid
        },
        number: e.num,
        salesVolume: e.sale,
        id: e.ordergoodid
      })
    })
    var data = {

      orderGoodsList: goods,
      isPinkage: this.data.isPinkage ? 1 : 0,
      salesPrice: this.data.salesPrice,
      submitDate: this.data.submitDate + ' 00:00:00',
      salenote: this.data.salenote,
      isReceivables: this.data.isReceivables ? 1 : 0,
      isPayment: this.data.isPayment ? 1 : 0,
      isSend: this.data.isSend ? 1 : 0,
      freight: this.data.freight ? this.data.freight : 0
    }
    if (this.data.customerid) {
      data.customer = {
        id: this.data.customerid,
        onlyID: this.data.customeronlyid
      }
      data.customerAddress = {
        id: this.data.addressid,
        onlyID: this.data.addressonlyid
      }
    }
    if (this.data.isReceivables) {
      data.realReceive = this.data.realReceive
      data.debt = this.data.debt
      data.payWay = this.data.payWayarray[this.data.payWayindex].key

    }
    if (this.data.isSend) {
      data.deliveryType = this.data.deliveryTypeArray[this.data.deliveryTypeIndex].key
      data.courierCompany = this.data.courierCompany
      data.courierNumber = this.data.courierNumber
    }

    var url = ''
    if (this.data.orderid) {
      url = 'order/wxapi/update'
      data = Object.assign(this.data.olddata, data)
    } else {
      url = 'order/wxapi/create'
    }

    util.query(url, data, function(res) {
      if (res.code === 10000) {
        util.showToast('保存成功')
        setTimeout(function() {
          wx.switchTab({
            url: '/pages/order/order/order',
          })


        }, 2000)
      } else {
        util.showToast('保存失败')
      }
    }, 'POST')
  },
  delgood(e) {
    var goods = this.data.goods
    goods.splice(e.currentTarget.dataset.index, 1)
    this.setData({
      goods: goods
    })
    this.freshsalesPrice()
  },
  setcourierNumber(e) {
    this.setData({
      courierNumber: e.detail.value
    })
  },
  setcourierCompany(e) {
    this.setData({
      courierCompany: e.detail.value
    })
  },
  setnum(e) {
    var goods = this.data.goods
    goods[e.currentTarget.dataset.index].num = util.PointNum(e.detail.value)
    this.setData({
      goods: goods
    })
    this.freshsalesPrice()
  },
  setsale(e) {
    var goods = this.data.goods
    goods[e.currentTarget.dataset.index].sale = util.PointNum(e.detail.value)
    this.setData({
      goods: goods
    })
    this.freshsalesPrice()
  },
  setsalenote(e) {
    this.setData({
      salenote: e.detail.value
    })
  },
  setsalesPrice(e) {
    this.setData({
      salesPrice: e.detail.value
    })
  },
  setfreight(e) {
    this.setData({
      freight: util.PointNum(e.detail.value)
    })
  },
  setisPinkage(e) {
    this.setData({
      isPinkage: e.detail.value
    })
  },
  setisSend(e) {
    if (e.detail.value && this.data.customerid === 0) {
      util.showToast('请选择收货人')
      this.setData({
        isSend: false
      })
      return
    }

    this.setData({
      isSend: e.detail.value
    })
  },
  setisPayment(e) {
    this.setData({
      isPayment: e.detail.value
    })
  },
  setisReceivables(e) {
    this.setData({
      isReceivables: e.detail.value
    })
    this.freshdebt()

  },
  bindtime(e) {
    this.setData({
      submitDate: e.detail.value
    })
  },
  tochoiseAddress() {
    wx.navigateTo({
      url: '/pages/order/choiseAddress/choiseAddress',
    })
  },
  getDetail() {
    util.query('order/wxapi/findbyid', {
      id: this.data.orderid
    }, function(res) {
      if (res.code === 10000) {
        var pws = that.data.payWayarray
        var payWayindex = 0
        for (var i = 0; i < pws.length; i++) {
          if (pws[i].key === res.data.payWay) {
            payWayindex = i
            break
          }
        }
        var dts = that.data.deliveryTypeArray,
          deliveryTypeIndex
        for (var i = 0; i < dts.length; i++) {
          if (dts[i].key + '' === res.data.deliveryType) {
            deliveryTypeIndex = i
          }
        }
        var goods = []
        res.data.orderGoodsList.forEach(function(e) {
          goods.push({

            goodid: e.goods.id,
            goodname: e.goods.name,
            price: e.goodsBatch.purchasePrice,
            goodonlyid: e.goods.onlyID,
            goodsBatchid: e.goodsBatch.id,
            goodsBatchonlyid: e.goodsBatch.onlyID,
            num: e.number,
            sale: e.salesVolume,
            ordergoodid: e.id
          })
        })
        that.setData({
          isPinkage: res.data.isPinkage === '1' ? true : false,
          freight: res.data.freight,
          salesPrice: res.data.salesPrice,
          addressname: res.data.customerAddress ? res.data.customerAddress.name : '',
          customerid: res.data.customer ? res.data.customer.id : 0,
          customeronlyid: res.data.customer ? res.data.customer.onlyID : '',
          addressid: res.data.customerAddress ? res.data.customerAddress.id : 0,
          addressonlyid: res.data.customerAddress ? res.data.customerAddress.onlyID : '',
          isReceivables: res.data.isReceivables === 1 ? true : false,
          isPayment: res.data.isPayment === 1 ? true : false,
          payWayindex: payWayindex,
          deliveryTypeIndex: deliveryTypeIndex,
          realReceive: res.data.realReceive,
          submitDate: res.data.submitDate ? res.data.submitDate.split(' ')[0] : '',
          salenote: res.data.salenote,
          isSend: res.data.isSend === 1 ? true : false,
          debt: res.data.debt,
          courierCompany: res.data.courierCompany,
          courierNumber: res.data.courierNumber,
          goods: goods,
          olddata: res.data
        })
      } else {
        util.showToast('获取详情失败')
      }
    })
  },
  del() {
    wx.showModal({
      title: '确认',
      content: '是否确定删除订单',
      success(res) {
        if (res.confirm) {

          util.query("order/wxapi/delete", {
            id: that.data.olddata.id
          }, function(res) {
            if (res.code == 10000) {
              util.showToast('删除成功')
              setTimeout(function() {
                wx.navigateBack({
                  delta: 1
                })
              }, 2000)
            } else {
              util.showToast(res.message)
            }
          }, "POST")
        } else if (res.cancel) {

        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // options.goods = JSON.stringify([{
    //   goodid: 234776,
    //   goodname: '红米手机',
    //   price: 10,
    //   goodonlyid: '928502452021897932341492096432414',
    //   goodsBatchid: 308787,
    //   goodsBatchonlyid: '902801730046553607347570690271441'

    // }, {
    //   goodid: 234775,
    //   goodname: '红米手机',
    //   price: 20,
    //   goodonlyid: '873890605297730500447478226706003',
    //   goodsBatchid: 308785,
    //   goodsBatchonlyid: '811124563377812956890532518415719'
    // }])
    that = this
    util.checklogin(function() {

      util.getPayWay(function(e) {
        that.setData({
          payWayarray: e
        })
        if (options.id) {
          that.setData({
            orderid: options.id
          })
          that.getDetail()

        } else if (options.goods) {
          var goods = JSON.parse(options.goods)
          for (var i = 0; i < goods.length; i++) {

            //goods[i].sale = goods[i].price
            goods[i].num = 1 
            goods[i].lastprice = 0
            // that.getLastPrice(goods[i].goodid, i)
          }
          // goods.forEach(function(res) {
          //   res.sale = res.price
          //   res.num = 1
          // })
          that.setData({
            goods: goods
          })
          that.freshsalesPrice()
        }
        that.setData({
          submitDate: util.formatTime(new Date()).split(' ')[0]
        })
      })




    })

  },
  updatelast(customerId) {
    for (var i = 0; i < this.data.goods.length; i++) {
      this.getLastPrice(this.data.goods[i].goodid, customerId, i)
    }
  },
  getLastPrice(id, customerId, num) {

    util.query('order/wxapi/getLastPrice', {
      productId: id,
      customerId: customerId
    }, function(res) {
      if (res.code === 10000) {
        var goods = that.data.goods
        goods[num].lastprice = res.data
        that.setData({
          goods: goods
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})