// nova-tourism/pages/my/merchant/merchant-home/gift-order/index.js
const Parse = getApp().Parse;
const company = getApp().globalData.company
const dateF = require('../../../../../../utils/date')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderList: [], //订单列表
    storeId: '', //本店id
    statusMap_shop: {
      '100': '待支付',
      '200': '已支付',
      '300': '已发货',
      '400': '已收货',
      '500': '申请退款',
      '601': '退款申请通过',
      '602': '退款被驳回',
      '700': '退款成功',
      '800': '订单完成',
    },
    isShipments: false, //发货弹框
    shipments_order: null, //发货订单
    shipments_index: 0, //发货订单下标
    trackingNumber: null, //快递单号

    isShowExpress: false, //快递公司弹框
    expVal: '', //快递公司搜索关键字
    timeout: null, //搜索框计时器
    expComList: [], //快递公司列表
    checkExp: null, //选中的公司
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let storeId = options.storeId;
    this.setData({
      storeId: storeId
    })
    this.refersh()
  },
  async refersh() {
    this.getOrder()
  },
  /**获取订单 */
  async getOrder() {
    let {
      storeId,
      orderList
    } = this.data
    let query = new Parse.Query('Order')
    query.include('targetObject', 'store', 'expressCompany')
    query.equalTo('company', company)
    query.equalTo('store', storeId)
    query.notEqualTo('isDeleted', true)
    query.containedIn('status', ['200', '300', '400', '500', '601', '602', '700', '800'])
    query.limit(10)
    query.skip(orderList?.length || 0)
    query.descending('createdAt')
    let r = await query.find()
    if (r?.length <= 0) wx.showToast({
      title: '到底了~',
      icon: 'none',
      duration: 500
    })
    let list = r?.map(item => {
      let obj = item?.toJSON()
      obj.createdAt = dateF.formatTime("YYYY-mm-dd HH:MM", obj.createdAt)
      if (obj.payTime) obj.payTime = dateF.formatTime("YYYY-mm-dd HH:MM", obj.payTime.iso)
      return obj
    }) || []
    this.setData({
      orderList: [...(orderList || []), ...(list || [])]
    })
    // console.log(this.data.orderList)
  },
  /**
   * 更新订单状态
   * @param {*} index 订单下标
   */
  async refershOrder(index) {
    let {
      orderList
    } = this.data
    let item = orderList[index]
    let query = new Parse.Query('Order')
    query.include('targetObject', 'store', 'expressCompany')
    query.notEqualTo('isDeleted', true)
    query.containedIn('status', ['200', '300', '400', '500', '601', '602', '700', '800'])
    query.equalTo('objectId', item.objectId)
    let r = await query.first()
    if (!r.id) {
      orderList.splice(index, 1)
      this.setData({
        orderList
      })
      return
    }
    let obj = r?.toJSON()
    obj.createdAt = dateF.formatTime("YYYY-mm-dd HH:MM", obj.createdAt)
    if (obj.payTime) obj.payTime = dateF.formatTime("YYYY-mm-dd HH:MM", obj.payTime.iso)
    orderList[index] = obj
    this.setData({
      orderList
    })
  },


  /**快递订单-确认发货 */
  async confirmShipment() {
    let {
      shipments_order,
      trackingNumber,
      checkExp,shipments_index
    } = this.data
    if ((!trackingNumber) || (!checkExp?.objectId)) {
      wx.showToast({
        title: '存在未填项',
        icon: 'none'
      })
      return
    }
    let query = new Parse.Query('Order')
    let o = await query.get(shipments_order?.objectId)
    o.set('trackingNumber', trackingNumber)
    o.set('expressCompany', {
      __type: 'Pointer',
      className: 'ExpressCompany',
      objectId: checkExp?.objectId
    })
    o.set('status','300')
    await o.save()
    await this.refershOrder(shipments_index)
    this.closeShipments()
    wx.showToast({
      title: '保存成功',
      icon:'success'
    })
  },
  /**发货弹框-开 */
  openShipments(e) {
    let {
      index
    } = e.currentTarget.dataset
    let {
      orderList,statusMap_shop
    } = this.data
    let shipments_order = orderList[index]
    if (shipments_order.distributeType != 'delivery') return
    if(shipments_order.status != '200'){
      wx.showToast({
        title: `当前订单 ${statusMap_shop[shipments_order.status]} ，无需发货。`,
        icon:'none'
      })
      return
    }
    // console.log(shipments_order)
    this.setData({
      isShipments: true,
      shipments_order,
      shipments_index: index,
      checkExp: shipments_order.expressCompany || null,
      expVal: '',
      trackingNumber:shipments_order.trackingNumber||'',
    })
  },
  /**发货弹框-关 */
  closeShipments() {
    this.setData({
      isShipments: false
    })
  },
  /**确认退款 */
  confirm_refund(e) {
    let {
      index
    } = e.currentTarget.dataset
    let {
      orderList
    } = this.data

    let _this = this
    wx.showModal({
      title: '',
      content: '已确认顾客退款到账吗？',
      showCancel: true,
      cancelText: '取消',
      cancelColor: '#000000',
      confirmText: '确定',
      confirmColor: '#3CC51F',
      success: async (result) => {
        if (result.confirm) {
          wx.showLoading({
            title: '加载中',
          })
          let ShopOrder = new Parse.Query('Order')
          let order = await ShopOrder.get(orderList[index]?.objectId)
          if (order && order?.id) {
            order.set('status', '700')
            await order.save()
            this.refershOrder(index)
          } else {
            wx.hideLoading()
            wx.showToast({
              title: '出错了',
              icon: 'error',
              image: '',
              duration: 1500,
            });
            return
          }
          orderList.splice(index, 1)
          _this.setData({
            orderList
          })
          wx.hideLoading()
          wx.showToast({
            title: '已取消',
            icon: 'none',
            image: '',
            duration: 1500,
          });
        }
      },
      fail: () => {},
      complete: () => {}
    });
  },
  /**驳回退款 */
  overrule_refund(e) {
    let {
      index
    } = e.currentTarget.dataset
    let {
      orderList
    } = this.data

    let _this = this
    wx.showModal({
      title: '',
      content: '驳回当前退款申请吗？',
      showCancel: true,
      cancelText: '取消',
      cancelColor: '#000000',
      confirmText: '确定',
      confirmColor: '#3CC51F',
      success: async (result) => {
        if (result.confirm) {
          wx.showLoading({
            title: '加载中',
          })
          let ShopOrder = new Parse.Query('Order')
          let order = await ShopOrder.get(orderList[index]?.objectId)
          if (order && order?.id) {
            order.set('status', '602')
            await order.save()
            this.refershOrder(index)
          } else {
            wx.hideLoading()
            wx.showToast({
              title: '出错了',
              icon: 'error',
              image: '',
              duration: 1500,
            });
            return
          }
          orderList.splice(index, 1)
          _this.setData({
            orderList
          })
          wx.hideLoading()
          wx.showToast({
            title: '已取消',
            icon: 'none',
            image: '',
            duration: 1500,
          });
        }
      },
      fail: () => {},
      complete: () => {}
    });
  },
  /**同意退款 */
  agree_refund(e) {
    let {
      index
    } = e.currentTarget.dataset
    let {
      orderList
    } = this.data

    let _this = this
    wx.showModal({
      title: '',
      content: '确认当前退款申请吗？',
      showCancel: true,
      cancelText: '取消',
      cancelColor: '#000000',
      confirmText: '确定',
      confirmColor: '#3CC51F',
      success: async (result) => {
        if (result.confirm) {
          wx.showLoading({
            title: '加载中',
          })
          let ShopOrder = new Parse.Query('Order')
          let order = await ShopOrder.get(orderList[index]?.objectId)
          if (order && order?.id) {
            order.set('status', '601')
            await order.save()
            this.refershOrder(index)
          } else {
            wx.hideLoading()
            wx.showToast({
              title: '出错了',
              icon: 'error',
              image: '',
              duration: 1500,
            });
            return
          }
          orderList.splice(index, 1)
          _this.setData({
            orderList
          })
          wx.hideLoading()
          wx.showToast({
            title: '已取消',
            icon: 'none',
            image: '',
            duration: 1500,
          });
        }
      },
      fail: () => {},
      complete: () => {}
    });
  },
  /**确认收货 */
  confirm_receipt(e) {
    let {
      index
    } = e.currentTarget.dataset
    let {
      orderList
    } = this.data

    let _this = this
    wx.showModal({
      title: '',
      content: '确认当前自提订单已取货吗',
      showCancel: true,
      cancelText: '取消',
      cancelColor: '#000000',
      confirmText: '确定',
      confirmColor: '#3CC51F',
      success: async (result) => {
        if (result.confirm) {
          wx.showLoading({
            title: '加载中',
          })
          let ShopOrder = new Parse.Query('Order')
          let order = await ShopOrder.get(orderList[index]?.objectId)
          if (order && order?.id) {
            order.set('status', '800')
            await order.save()
            this.refershOrder(index)
          } else {
            wx.hideLoading()
            wx.showToast({
              title: '出错了',
              icon: 'error',
              image: '',
              duration: 1500,
            });
            return
          }
          orderList.splice(index, 1)
          _this.setData({
            orderList
          })
          wx.hideLoading()
          wx.showToast({
            title: '已取消',
            icon: 'none',
            image: '',
            duration: 1500,
          });
        }
      },
      fail: () => {},
      complete: () => {}
    });
  },





  closeExpress() {
    this.setData({
      isShowExpress: false
    });
  },
  openExpress() {
    this.getPointerItem()
    this.setData({
      isShowExpress: true
    });
  },
  /**指针搜索框变化 */
  async valChange(e) {
    await this.setData({
      expVal: e.detail || ''
    })
    let {
      timeout
    } = this.data
    clearTimeout(timeout)
    timeout = setTimeout(async () => {
      await this.setData({
        expComList: [],
      })
      this.getPointerItem()
    }, 1000);
    this.setData({
      timeout
    })
  },
  /**选中快递公司 */
  checkPointer(e) {
    let {
      index
    } = e.currentTarget.dataset
    let {
      expComList
    } = this.data
    this.setData({
      checkExp: expComList[index]
    })
    // console.log(expComList[index])
    this.closeExpress()
  },
  /** 查询快递公司*/
  async getPointerItem() {
    let {
      expVal,
      expComList
    } = this.data
    let query = new Parse.Query('ExpressCompany')
    query.contains('name', expVal || '')
    query.limit(30)
    query.skip(expComList?.length || 0)
    let d = await query.find()
    let list = d?.map(item => item.toJSON())
    this.setData({
      expComList: [...(expComList || []), ...(list || [])]
    })
  },






  /**预览图片 */
  previewImg: function (e) {
    let {
      list
    } = e.currentTarget.dataset
    var photo = list || []
    wx.previewImage({
      current: photo[0],
      urls: photo
    });
  },
  /**复制文本 */
  onCopy(e) {
    let {
      text
    } = e.currentTarget.dataset
    wx.setClipboardData({
      data: text,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '复制成功',
            })
          }
        })
      }
    })
  },

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

  },

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

  },

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

  },

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

  },

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

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.getOrder()
  },

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

  }
})