// pages/order/order.js
const app = getApp()
const wxService = require('../../utils/wxService')
const utils = require('../../utils/util')
const envInfo = require('../../config/index').envInfo

wxService.page({
  /**
   * 页面的初始数据
   */
  data: {
    showApplyRefundModal: false,
    // 订单状态(C:取消;N:新建,P:已支付;D:已发货;R:已收货)
    swiperItem: [
      {
        type: '1',
        status: '',
        name: '全部'
      },
      {
        type: '2',
        status: 'N',
        name: '待付款' // 新建
      },
      {
        type: '3',
        status: 'P',
        name: '待发货'
      },
      {
        type: '4',
        status: 'D',
        name: '待收货'
      },
      {
        type: '5',
        status: 'RF',
        name: '退款/售后'
      }
    ],
    currentIndex: 1,
    pageNo: 1,
    pageSize: 5,
    noMoreFlag: false,
    orderList: null,
    totalPages: 0,
    subImgs: [],
    status: '',  // 订单状态(C:取消;N:新建,P:已支付;D:已发货;R:已收货)
    no_data: true,
    currentTradeId: '',
    refundId : ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log('currentIndex', this.data.currentIndex)
    const { currentIndex } = this.data

    if (currentIndex == 5) {
      this.getRefundList(this.data.pageNo, this.data.pageSize)
    } else {
      this.setData({
        pageNo: 1,
        pageSize: 5
      }, () => {
        this.initOrderList(this.data.pageNo, this.data.pageSize, this.data.status)
      })
    }



  },
  // 确认收货
  handelConfirmReceipt(e) {
    const { id } = e.currentTarget.dataset
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wxService.post(`/sale/trade/buyer/confirm/${id}`).then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          wx.hideLoading()
          wx.showToast({
            title: `您已确认收货!`,
            icon: 'none'
          })
          setTimeout(() => {
            this.onShow()
          }, 200)
        } else {
          wx.showToast({
            title: `确认收货失败!`,
            icon: 'none'
          })
          setTimeout(() => {
            this.onShow()
          }, 200)
        }
      }
    })
  },
  // 删除订单
  handelDelOrder(e) {
    const { id } = e.currentTarget.dataset
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wxService.post(`/sale/trade/buyer/delete/${id}`).then(res => {
      if (res) {
        const { result } = res.data
        if (result == 0) {
          wx.hideLoading()
          wx.showToast({
            title: `删除成功!`,
            icon: 'none'
          })
          setTimeout(() => {
            this.onShow()
          }, 200)
        }

      } else {
        wx.showToast({
          title: `删除失败!`,
          icon: 'none'
        })

        setTimeout(() => {
          this.onShow()
        }, 200)
      }
    })
  },
  // 立即支付
  handelToPay(e) {
    const { id } = e.currentTarget.dataset
    console.log('0000', id)
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wxService.post(`/sale/trade/buyer/wxprepay/${id}`).then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          console.log('dddd', data.amount)
          let amount = data.amount || 0
          wx.hideLoading()
          wx.requestPayment(Object.assign({
            success(res) {
              wx.hideLoading()
              // 支付成功页面
              wxService.router(`/subPackage/page/pages/paymentStatus/paymentStatus?status=S&amount=${amount}`)
            },
            fail(res) {
              wx.hideLoading()
              wxService.router('/subPackage/page/pages/paymentStatus/paymentStatus?status=F')
            }
          }, data))

        }
      }
    })
  },
  // 查看物流
  checkLogistics(e) {
    const { detail } = e.currentTarget.dataset
    let params = JSON.stringify(detail)
    // 退款申请
    wxService.router(`/pages/logistics/logistics`).search({ params })
  },
  // 查看详情
  handelCheckRfDetail(e) {
    const { id } = e.currentTarget.dataset
    wxService.router(`/pages/orderDetail/orderDetail?id=${id}`)
  },
  // 订单详情
  handelDetail(e) {
    // const {detail} = e.currentTarget.dataset
    const { id } = e.currentTarget.dataset
    wxService.router(`/pages/orderDetail/orderDetail?id=${id}`)
  },
  // 退单详情 
  handelDetailRf(e) {
    const { id } = e.currentTarget.dataset
    wxService.router(`/pages/refundDetail/refundDetail?id=${id}`)
  },
  // 取消退款
  handelCancelRefund(e) {
    const { id } = e.currentTarget.dataset
    console.log('取消退款', id)
    this.handelRevokeRefund(id)
  },
  handelRevokeRefund(id) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    const params = { id }
    wxService.post(`/sale/refund/buyer/cancel?id=${id}`).then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          wx.hideLoading()
          wx.showToast({
            title: '撤销退款成功',
            icon: 'none'
          });
          setTimeout(() => {
            wxService.router('/pages/order/order')
          }, 200)
        }
      }
    })
  },

  //点击切换tab
  switchTab(e) {
    const { type, status } = e.currentTarget.dataset
    const { currentIndex } = this.data
    if (currentIndex == type) return false
    this.setData({
      currentIndex: type,
      pageNo: 1,
      orderList: [],
      status: '',
      no_data: true
    }, () => {
      if (type == 5 && status == 'RF') {
        this.getRefundList(this.data.pageNo, this.data.pageSize)
      } else {
        this.setData({
          status: status
        }, () => {
          this.initOrderList(this.data.pageNo, this.data.pageSize, status)
        })

      }
    })
  },
  initOrderList(pageNo, pageSize, status) {
    console.log('-------------', status)
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    const params = { status: status }
    wxService.post(`/sale/trade/buyer/history?pageNum=${pageNo}&pageSize=${pageSize}`, params).then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          wx.hideLoading()
          this.setData({
            orderList: this.data.pageNo == 1 ? [...data] : [...this.data.orderList, ...data],
            noMoreFlag: data.length < pageSize ? true : false,
          }, () => {
            this.setData({
              no_data: this.data.orderList.length ? true : false
            })
            wx.setStorageSync('orderList', this.data.orderList)
          })
        }
      }
    })
  },
  // 退款列表 /refund/buyer/history  订单状态(C:取消;N:新建,A:已审核;R:退货已发R货;D:退货已收货)
  getRefundList(pageNo, pageSize) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    const params = {}
    wxService.post(`/sale/refund/buyer/history?pageNum=${pageNo}&pageSize=${pageSize}`, params).then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          wx.hideLoading()
          this.setData({
            orderList: this.data.pageNo == 1 ? [...data] : [...this.data.orderList, ...data],
            noMoreFlag: data.length < pageSize ? true : false
          }, () => {
            // this.data.orderList.forEach(item =>{
            //   console.log('item', item)
            //   // 退单列表
            //   if(item.tradeId){
            //     console.log('item.tradeId', item.tradeId)
            //     let currentTradeId = item.tradeId
            //     this.setData({
            //       currentTradeId
            //     },()=>{
            //       this.refundDetail()
            //     })
            //   }
            // })
            this.setData({
              no_data: this.data.orderList.length ? true : false
            })

          })
        }
      }
    })
  },
  // 退单详情
  // refundDetail(){
  //   console.log('tradeId', this.data.currentTradeId)
  //   wx.showLoading({
  //     title: '加载中',
  //     mask: true
  //   })
  //   wxService.get(`/sale/trade/buyer/${this.data.currentTradeId}`).then(res => {
  //     if (res) {
  //       const { result, data } = res.data
  //       if (result == 0) {
  //         wx.hideLoading()
  //         console.log('daya', data, [...this.data.orderList, ...data])
  //         console.log('this.data.orderList', this.data.orderList)
  //         this.data.orderList.forEach(item =>{
  //           console.log('item.tradeId == data.id', item.tradeId,data.id)
  //           if(item.tradeId == data.id){
  //             console.log('...item, ...data',item, data)

  //             this.setData({
  //               orderList: [...item, ...data]
  //             },()=>{
  //               console.log('orderList', this.data.orderList)
  //             })
  //           }
  //         })

  //       }
  //     }
  //   })


  // },
  //发货之后回调
  onDeliveryOk(){
    this.getRefundList(1,5);
  },
  //填写物流信息
  tapWriteLogis(e) {
    let refundId = e.currentTarget.dataset.id;
    this.setData({
      showApplyRefundModal: true,
      refundId: refundId
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.setData({
      pageNo: this.data.pageNo + 1,
    }, () => {
      this.initOrderList(this.data.pageNo, this.data.pageSize, this.data.status)
    })
  },

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

  }
})