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

wxService.page({

  /**
   * 页面的初始数据
   */
  data: {
    detail: null,
    id: '',
    localNowTime: 0,
    hour: '00',
    min: '00',
    sec: '00',
    ms:  '0',
    mergedAmount: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu()
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const { id } = this.options
    let detailOrderList = wx.getStorageSync('orderList')
    let currentDetail = detailOrderList.filter(item => item.id == id)
    // /trade/buyer/{id}  订单详情
    console.log('id', id)
    if(id) {
      this.setData({
        id
      },()=>{
        this.getOrderDetail(id)
      })
    }
    // this.setData({
    //   detail: currentDetail[0]
    // })
  },
  getOrderDetail(id){
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wxService.get(`/sale/trade/buyer/${id}`).then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          wx.hideLoading()
          const { localNowTime} = this.data
          data.localNowTime = localNowTime ? localNowTime : new Date().getTime();
          data.createOrderTime = new Date(data.createTime.replace(/-/g,'/')).getTime() || [];
          data.countDownOrderTime = 7200000; // 2时(h)=7200000毫秒(ms)
          // 订单倒计时  超多两小时 刷新当前页
          // 本地时间 - 创建时间  >  2小时  刷新当前页
          this.setData({
            detail: data,
            mergedAmount: data.mergedAmount || 0
          }, ()=>{
            this.initCountDown(data.countDownOrderTime, data.createOrderTime, data.localNowTime)
          })
        }
      }
    })
  },
  initCountDown(countDownOrderTime,startTime,localTime) {
    // 毫秒差 本地时间 - 创建时间
    let countTimeSpan = localTime - startTime
  
    let countDownTimer = setInterval(() => {
      countDownOrderTime -= 1000
      let result = this.getCountDown(countTimeSpan, countDownOrderTime);
      if (result.isOver) {
        clearInterval(countDownTimer);
      } else {
        this.setData({
          hour: result.hour,
          min: result.min,
          sec: result.sec,
          ms: result.ms,
        })
      }
    }, 1000);
  },
  getCountDown(time, countDownOrderTime) {
     // 判断是否为时间戳
     let distancetime = time < countDownOrderTime ? countDownOrderTime - time : 0;
 
    // 毫秒差 本地时间 - 创建时间   7200000毫秒(ms)
     let result = {
       hour: '00',
       min: '00',
       sec: '00',
       ms: '00',
       isOver: true,
     };
     if (distancetime) {
      // 如果大于7200000.说明尚未到达截止时间
       result.ms = Math.floor((distancetime % 1000) / 100);
       result.sec = Math.floor((distancetime / 1000) % 60);
       result.min = Math.floor((distancetime / 1000 / 60) % 60);
       result.hour = Math.floor((distancetime / 1000 / 60 / 60) % 24);
       result.isOver = false;
 
       if (result.ms < 10) result.ms = result.ms;
       if (result.sec < 10) result.sec = '0' + result.sec;
       if (result.min < 10) result.min = '0' + result.min;
       if (result.hour < 10) result.hour = '0' + result.hour;
     } else {
       const {detail, id} = this.data
      console.log('status', detail.status)
        if (!this.getDetailLimitCount) {
          this.getDetailLimitCount = 1
        } else {
          this.getDetailLimitCount++
        }
        console.log('detail-request', this.getDetailLimitCount)
        if (this.getDetailLimitCount <= 1 && detail.status == 'N') {
          this.getOrderDetail(id)
        } 
     }

     return result;
  },
  // 删除订单
  handelDelOrder(e) {
    const { id } = e.currentTarget.dataset
    console.log('删除订单',id)
    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(() => {
            wxService.router('/pages/order/order')
          },200)
        } else {
          wx.showToast({
            title: `删除失败!`,
            icon: 'none'
          })
          setTimeout(() => {
            wxService.router('/pages/order/order')
          },200)
        }
      }
    })
  },
  // 立即支付
  handelToPay(e) { 
    const { id } = e.currentTarget.dataset
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    
    const { mergedAmount } = this.data
    let url = mergedAmount ? `/sale/payment/merged/buyer/wxprepay/${id}` : `/sale/trade/buyer/wxprepay/${id}`
    wxService.post(`${url}`).then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          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))

        }
      }
    })
  },
  // 取消订单
  handelCancelOrder(e) { 
    console.log('取消订单')
    const { id } = e.currentTarget.dataset
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    
    wxService.post(`/sale/trade/buyer/cancel/${id}`).then(res => {
      if (res) {
        const { result } = res.data
        if (result == 0) {
          wx.hideLoading()
          wx.showToast({
            title: `取消成功!`,
            icon: 'none'
          })
          setTimeout(() => {
            wxService.router('/pages/order/order')
          },200)
        } else {
          wx.showToast({
            title: `取消失败!`,
            icon: 'none'
          })
          setTimeout(() => {
            wxService.router('/pages/order/order')
          },200)
        }
      }
    })
    
  },
  // 查看物流
  checkLogistics(e) {
    console.log('----', e)
    const { detail } = e.currentTarget.dataset
    let params = JSON.stringify(detail)
    console.log("params", params)
    // 退款申请
    wxService.router(`/pages/logistics/logistics`).search({params})
  },
  // 申请退款
  handelRequestRefund(e) {
    console.log('----', e)
    const { id } = e.currentTarget.dataset
    const { detail } = e.currentTarget.dataset
    detail.id = this.data.id
    let params = JSON.stringify(detail)
    // 退款申请
    wxService.router(`/pages/refund/refund`).search({params})
   },
  // 确认收货
  handelConfirmReceipt(e) { 
    console.log('----', 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.initOrderList(this.data.pageNo, this.data.pageSize, this.data.trade)
          }, 200)
        } else {
          wx.showToast({
            title: `确认收货失败!`,
            icon: 'none'
          })
        }
      }
    })
  },
  copy(e) {
    wx.setClipboardData({
      //准备复制的数据
      data: e.currentTarget.dataset.content,
      success: function (res) {
        wx.showToast({
          title: '复制成功',
          icon: 'none'
        });
      }
    });
  },

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

  },

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

  },

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

  },

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

  },

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

  }
})