// pages/order-detail/order-detail.js

var http = require('../../utils/http.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderItemDtos: [],
    remarks: "",
    actualTotal: 0,
    userAddrDto: null,
    orderNumber: "",
    createTime: "",
    status: 0,
    productTotalAmount: '',
    transfee: '',
    reduceAmount: '',
    prodid: '',
    orderType: 0,
    shopName: '', //店铺名称
    canRefund: false, // 能否退款
    canAllRefund: false, // 能否整单退款
    isLastProd: false,  //最后一款商品
    irrevocable: false,  //不可撤销
    sum: [],  //本单已申请单个退款的商品数组
    orderScore: 0, // 整单使用积分
    orderNumSend:''
  },

  //跳转商品详情页
  toProdPage: function(e) {
    var prodid = e.currentTarget.dataset.prodid;
    if(this.data.orderType==3){
      console.log('积分商品')
      wx.navigateTo({
        url: '/pages/convertProdDet/convertProdDet?prodid=' + prodid,
      })
    }else{
      wx.navigateTo({
        url: '/pages/prod/prod?prodid=' + prodid,
      })
    }
  },

  /**
   * 是否最后一个商品在执行单个商品退款事件
   */
  applyLastProdRefund: function() {
    if(this.data.status==2) { //待发货状态下
      // 遍历商品list
      if(this.data.orderItemDtos.length > 1) {  //如果商品列表长度大于1
        let sum = []
        this.data.orderItemDtos.forEach((el,index) => {
          if (el.refundSn) { //如果拥有退款单号
            sum.push(el)
            this.setData({
              sum
            })
          }
        })
        console.log(this.data.sum)
        if(this.data.sum.length == this.data.orderItemDtos.length-1) {
          // 如果拥有退款单号的item等于商品列表数据长度-1，那么点击的这件商品就是最后意见商品
          this.setData({
            isLastProd: true
          })
        }else if(this.data.sum.length == this.data.orderItemDtos.length) {
          // 如果拥有退款单号的item等于商品列表数据长度，那么不可撤销申请
          this.setData({
            irrevocable: true  //不可撤销
          })
        }
      }
      console.log('isLastProd：',this.data.isLastProd)
      console.log('irrevocable：',this.data.irrevocable)
    }
  },

  /**
   * 申请退款
   */
  applyRefund: function(e) {
    var refundType = e.currentTarget.dataset.refundtype // 退款类型 1整单  2单个物品
    var status = this.data.status
    this.loadOrderDetail(this.data.orderNumber)  //请求订单详情数据
    if (e.currentTarget.dataset.refundtype == 1) { //整单退款
      var item = {}
      item.orderNumber = this.data.orderNumber;
      item.actualTotal = this.data.actualTotal;
      item.transfee = this.data.transfee;
      item.status = this.data.status; //订单状态
      item.orderItemDtos = this.data.orderItemDtos;
      item.orderScore = this.data.orderScore,  // 整单积分
      //拿到存储在本地的订单项数据
      wx.setStorageSync("refundItem", item);
      // console.log('订单详情页获取到的整单退item：',item)
    } else if(e.currentTarget.dataset.refundtype == 2) { //单个商品退款
      this.applyLastProdRefund() //是否最后一个商品执行单个商品退款
      console.log('isLastProd：',this.data.isLastProd)
      // 将数据存储到本地
      var item = e.currentTarget.dataset.item;
      if(this.data.orderItemDtos.length == 1) {
        item.addTransfee = true
      }else {
        item.addTransfee = false
      }
      item.orderNumber = this.data.orderNumber;
      item.transfee = this.data.transfee;
      item.status = this.data.status; //订单状态
      item.isLastProd = this.data.isLastProd?this.data.isLastProd:undefined //是否最后一款商品
      //拿到存储在本地的订单项数据
      wx.setStorageSync("refundItem", item);
      console.log(item)
      console.log(item.actualTotal)
    }
    /**
     * 判断跳转页面（根据订单是否已发货）
     */
    var type = e.currentTarget.dataset.type;
    
    if (status == 2) {   //待发货，直接跳转到申请页，不需要选择退货方式
      wx.redirectTo({ //通过wx.redirectTo实现跳转（关闭当前页面，跳转到应用内某个页面）
        url: '/pages/applyRefund/applyRefund?type=' + type + '&refundType=' + refundType,
      })
    } else  {  //已发货，跳转到选择退货方式页
      wx.redirectTo({
        url: '/pages/chooseRefundWay/chooseRefundWay?refundType=' + refundType
      })
    }
  },


  /**
   * 查看退款
   */
  viewRefund: function(e) {
    var refundSn = e.currentTarget.dataset.refundsn;
    this.applyLastProdRefund() //是否最后一个商品执行单个商品退款
    console.log(this.data.irrevocable)
    wx.navigateTo({
      url: '/pages/DetailsOfRefund/DetailsOfRefund?refundSn=' + refundSn + '&irrevocable=' + this.data.irrevocable+'&userAddrDto='+JSON.stringify(this.data.userAddrDto) +'&orderNumber=' + this.data.orderNumSend
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      orderNumSend:options.orderNum
    })
    this.loadOrderDetail(options.orderNum);
  },

  /**
   * 加载订单数据
   */
  loadOrderDetail: function(orderNum) {
    var ths = this;
    wx.showLoading();
    //加载订单详情
    var params = {
      url: "/p/myOrder/orderDetail",
      method: "GET",
      data: {
        orderNumber: orderNum
      },
      callBack: function(res) {
        let img=''
        res.orderItemDtos.forEach(e=>{
          img=e.pic.split(',')
          e.pic=img[0]
        })
        ths.setData({
          orderNumber: orderNum,
          actualTotal: res.actualTotal, //实际支付总额（商品总额+运费)
          userAddrDto: res.userAddrDto,
          remarks: res.remarks,
          orderItemDtos: res.orderItemDtos,
          createTime: res.createTime,
          status: res.status,
          productTotalAmount: res.total, //所有商品总额
          transfee: res.transfee, //运费
          reduceAmount: res.reduceAmount,
          orderType: res.orderType,
          shopName: res.shopName,
          canRefund: res.canRefund,
          canAllRefund: res.canAllRefund,
          orderScore: res.orderScore, // 整单使用积分
        });
        wx.hideLoading();
      }
    };
    http.request(params);

  },


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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

  toGroupDetails: function(e) {
    wx.navigateTo({
      url: '/pages/spellGroupDetails/spellGroupDetails?orderNumber=' + e.currentTarget.dataset.ordernumber,
    })
  },


  // 一键复制事件
  copyBtn: function(e) {
    var ths = this;
    wx.setClipboardData({
      //准备复制的数据
      data: ths.data.orderNumber,
      success: function(res) {
        wx.showToast({
          title: '复制成功',
        });
      }
    })
  },

})