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

  /**
   * 页面的初始数据
   */
  data: {
    showView: true, //隐藏是展示
    applyTime: '', //申请时间
    applyType: 1, //申请类型:1,仅退款,2退款退货
    goodsNum: '', //退货数量
    handelTime: '', //卖家处理时间
    orderAmount: '', //订单总金额
    orderItems: {}, //订单项 
    refundAmount: '', //退款金额
    refundDelivery: [], //收货地址对象
    refundId: '', //记录ID
    refundTime: '', //退款时间
    returnMoneySts: 1, //处理退款状态:(1.买家申请 2.卖家接受 3.买家发货 4.卖家收货 5.退款成功 6.买家撤回申请 7.商家拒绝 -1.退款关闭)
    updateTime: '', //更新时间
    refundSn: '', //退款编号
    rejectMessage: '', //拒绝理由
    buyerReason: '', //退款原因
    shopName: '', //店铺名称
    refundScore: 0, // 退款积分
    addCarshow: false,
    selectTimeshow: false,
    flowShow: false,
    userAddrDto: {},
    payer: '',
    sendPay:'',
    sts: 0,
    nomDay: '',
    tomorrowDay: '',
    timeIntervals: [],
    columns: [],
    combinedTextValue: '',
    sendInfo: {},
    currentSelectedIndex: -1, // 初始没有选中项，索引设为 -1
    steps: [{
        text: '步骤一',
        desc: '描述信息',
        inactiveIcon: 'location-o',
        activeIcon: 'success',
      },
      {
        text: '步骤二',
        desc: '描述信息',
        inactiveIcon: 'circle',
        activeIcon: 'plus',
      },
      {
        text: '步骤三',
        desc: '描述信息',
        inactiveIcon: 'circle',
        activeIcon: 'cross',
      },
      {
        text: '步骤四',
        desc: '描述信息',
        inactiveIcon: 'circle',
        activeIcon: 'fail',
      },
    ],
    cancelPay: false,
    remainingTime: '',
    timeFormat: '',
    orderNumSend:'',
    countdown_hours:'',
    countdown_minutes:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      orderNumSend:options.orderNumber
    })
    this.getTime()
    this.setData({
      refundSn: options.refundSn,
    });
    if(options.userAddrDto){
      this.setData({
        userAddrDto: JSON.parse(options.userAddrDto)
      })
    }
    //获取退款申请详情
    this.getRefundDetail()
  },

  /**
   * 更多说明&收起
   */
  onChangeShowState: function () {
    var that = this;
    that.setData({
      showView: (!that.data.showView)
    })
  },
  // 发起配送
  sendDistribution: function () {
    this.setData({
      addCarshow: true
    })
  },
  onClose: function () {
    this.setData({
      addCarshow: false
    })
  },
  timeOnClose: function () {
    this.setData({
      selectTimeshow: false
    })
  },
  submitBtn:function(){
    if (Object.keys(this.data.sendInfo).length === 0) {
      wx.showToast({
        title: '请先选择取件时间',
        icon: 'none'
      })
      return
    }
    this.submitExpress()
  },
  submitExpress:function(){
    var params = {
      url: `/p/orderRefund/submitExpress/${this.data.refundSn}`,
      method: "GET",
      callBack: res => {
        wx.showToast({
          title: '提交成功',
          icon: 'none',
        })
        this.setData({
          addCarshow:false
        })
        this.getRefundDetail()
      }
    };
    http.request(params);
  },
  // 辅助函数，将中文日期格式转换为YYYY-MM-DD格式
  formatDate: function (dateStr) {
    let parts = dateStr.match(/(\d+)月(\d+)日/);
    if (parts) {
      let month = parseInt(parts[1]);
      let day = parseInt(parts[2]);
      let year = new Date().getFullYear();
      return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
    }
    return dateStr;
  },
  selectUpTime: function () {
    this.getDayTime()
    this.getTime()
    let day = []
    day.push({
      id: 1,
      text: this.data.nomDay
    }, {
      id: 2,
      text: this.data.tomorrowDay
    })
    let data = []
    data.push({
      values: day,
      className: 'column1',
    }, {
      values: this.data.timeIntervals,
      defaultIndex: 2,
      className: 'column2',
    })
    this.setData({
      selectTimeshow: true,
      columns: data
    })
  },

  // 获取今明天并转换
  getDayTime: function () {
    const today = new Date();
    const month = (today.getMonth() + 1).toString().padStart(2, '0');
    const day = today.getDate().toString().padStart(2, '0');
    const todayFormat = `${month}月${day}日`;
    const tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000);
    const tomorrowMonth = (tomorrow.getMonth() + 1).toString().padStart(2, '0');
    const tomorrowDay = tomorrow.getDate().toString().padStart(2, '0');
    const tomorrowFormat = `${tomorrowMonth}月${tomorrowDay}日`;
    this.setData({
      nomDay: todayFormat,
      tomorrowDay: tomorrowFormat
    })
  },

  // 时间段转换
  getTime: function (selectedDate) {
    const timeIntervals = [];
    // 如果没有传入日期参数（首次加载等情况），则使用当前日期
    const now = selectedDate ? new Date(selectedDate) : new Date();
    if (isNaN(now.getTime())) {
      console.error('传入的日期格式不正确，无法解析为有效日期');
      return;
    }
    const currentTimeStamp = now.getTime();
    for (let hour = 0; hour < 23; hour++) {
      const start = hour.toString().padStart(2, '0') + ':00';
      const end = (hour + 1).toString().padStart(2, '0') + ':00';
      const interval = start + '~' + end;
      // 创建对应时间段开始时间的日期对象
      const startDate = new Date(now);
      startDate.setHours(hour, 0, 0, 0);
      const startTimestamp = startDate.getTime();
      // 通过比较时间戳来判断时间段是否已过去
      const hidden = startTimestamp < currentTimeStamp;
      timeIntervals.push({
        text: interval,
        disabled: hidden
      });
    }
    this.setData({
      timeIntervals
    });
  },

  // 日期转换方法
  convertDateToNumber: function (dateStr) {
    if (!dateStr) {
      throw new Error('日期字符串不能为空');
    }
    dateStr = dateStr.trim();
    let parts = dateStr.match(/(\d+)月(\d+)日/);
    if (!parts) {
      throw new Error('日期格式不正确，请按照XX月XX日的格式输入');
    }
    return new Date(2024, parseInt(parts[1]) - 1, parseInt(parts[2]));
  },

  // 选择器change事件
  onChange(event) {
    const {
      picker,
      value,
      index
    } = event.detail;
    value.map((item, index) => {
      if (index === 0) {
        var date1 = this.convertDateToNumber(item.text);
        var date2 = new Date();
        if (date1 > date2) {
          this.updateTimeIntervalsDisabled(item.id);
        } else {
          this.updateTimeIntervalsDisabled(item.id);
        }
      }
    })
  },
  onConfirm(event) {
    const {
      picker,
      value,
      index
    } = event.detail;
    var currentDate = new Date();
    var currentYear = currentDate.getFullYear();
    if (value.length >= 2) {
      const text1 = value[0].text; //text1为12月25日
      const text2 = value[1].text.slice(0, 5); //text2为15:00
      const month = ("0" + (parseInt(text1.split("月")[0]))).slice(-2); // 将中文月格式转换为数字（注意要减1，因为月份是从0开始计数），并补0
      const day = text1.split("月")[1].split("日")[0];
      const hour = text2.split(":")[0];
      const minute = text2.split(":")[1];
      const combinedText = `${currentYear}-${month}-${day} ${hour}:${minute}:00`;
      let dateObj = new Date(combinedText);
      let timestamp = Math.floor(dateObj.getTime() / 1000);
      // 获取配送费
      let that = this
      var params = {
        url: "/p/orderRefund/refundPrice",
        method: "GET",
        data: {
          refundSn: this.data.refundSn, //退款编号
          deliveryTime: timestamp
        },
        callBack: function (res) {
          that.setData({
            sendInfo: res
          })
        }
      };
      http.request(params);
      this.setData({
        combinedTextValue: combinedText,
        selectTimeshow: false
      });
    }
  },
  onCancel: function () {
    this.setData({
      selectTimeshow: false
    })
  },
  toPaySend: function () {
    if (Object.keys(this.data.sendInfo).length === 0) {
      wx.showToast({
        title: '请先选择取件时间',
        icon: 'none'
      })
      return
    } else {
      let that = this
      wx.showLoading({
        mask: true
      });
      var params = {
        url: "/p/order/refundPay",
        method: "POST",
        data: {
          payType: 1,
          orderType: 1,
          orderNumbers: this.data.refundSn
        },
        callBack: (res) => {
          wx.hideLoading();
          wx.requestPayment({
            timeStamp: res.timeStamp,
            nonceStr: res.nonceStr,
            package: res.packageValue,
            signType: res.signType,
            paySign: res.paySign,
            success: e => {
              wx.showModal({
                title: '支付成功',
                content: '',
                showCancel: false,
                success: () => {
                  this.setData({
                    addCarshow:false
                  })
                  this.submitExpress()
                }
              })
            },
            fail: err => {
              // this.countdownTime()
              // that.setData({
              //   cancelPay: true,
              //   addCarshow:false
              // })
            }
          })
        }
      };
      http.request(params);
    }
  },
  atoncePaySend: function () {
    wx.showLoading({
      mask: true
    });
    var params = {
      url: "/p/order/refundPay",
      method: "POST",
      data: {
        payType: 1,
        orderType: 1,
        orderNumbers: this.data.refundSn
      },
      callBack: (res) => {
        wx.hideLoading();
        wx.requestPayment({
          timeStamp: res.timeStamp,
          nonceStr: res.nonceStr,
          package: res.packageValue,
          signType: res.signType,
          paySign: res.paySign,
          success: e => {
            wx.showModal({
              title: '支付成功',
              content: '',
              showCancel: false,
              success: () => {
                // this.setData({
                //   cancelPay: false
                // })
                this.getRefundDetail()
              }
            })
          },
          fail: err => {}
        })
      }
    };
    http.request(params);
  },
  // 倒计时
  countdownTime: function () {
    // 十五分钟对应的毫秒数
    const fifteenMinutesInMs = 15 * 60 * 1000;
    const targetTimeStamp = this.data.sendInfo.touchTime;
    // 计算增加十五分钟后的时间戳
    const newTimeStamp = targetTimeStamp + fifteenMinutesInMs;
    const currentTimeStamp = newTimeStamp;
    const diff = currentTimeStamp - targetTimeStamp;
    if (diff > 0) {
      this.setData({
        remainingTime: diff,
      });
      this.countdown();
    } else {
    }
  },
  // 倒计时
  countdown: function () {
    const interval = setInterval(() => {
      if (this.data.remainingTime <= 0) {
        clearInterval(interval);
        this.setData({
          cancelPay: false
        })
        return;
      }
      this.setData({
        remainingTime: this.data.remainingTime - 1000,
      });
      // 将剩余时间（毫秒）转换为时分秒格式
      const hours = Math.floor(this.data.remainingTime / (1000 * 60 * 60));
      const minutes = Math.floor((this.data.remainingTime % (1000 * 60 * 60)) / (1000 * 60));
      const seconds = Math.floor((this.data.remainingTime % (1000 * 60)) / 1000);
      const timeFormat = `${this.padZero(hours)}:${this.padZero(minutes)}:${this.padZero(seconds)}`;
      this.setData({
        timeFormat: timeFormat
      });
    }, 1000);
  },
  // 辅助函数，用于将数字转换为两位数格式（不足两位前面补0）
  padZero(num) {
    return num < 10 ? '0' + num : num.toString();
  },
  // 根据id判断是否开启disabled
  updateTimeIntervalsDisabled(id) {
    let datatime = this.data.timeIntervals.map(subItem => {
      if (id === 2) {
        subItem.disabled = false;
      } else if (id === 1) {
        // 选中当天重新调用getTime方法判断当前时间
        this.getTime()
      }
      return subItem;
    });
    // copy上面的数据结构，待优化
    let day = []
    day.push({
      id: 1,
      text: this.data.nomDay
    }, {
      id: 2,
      text: this.data.tomorrowDay
    })
    let data = []
    data.push({
      values: day,
      className: 'column1',
    }, {
      values: this.data.timeIntervals,
      defaultIndex: 2,
      className: 'column2',
    })
    this.setData({
      timeIntervals: datatime,
      columns: data
    });
  },
  flowBution: function () {
    wx.navigateTo({
      url: '/pages/MaterialFlowInfo/MaterialFlowInfo?refundSn=' + this.data.refundSn
    })
    // this.setData({
    //   flowShow: true
    // })
    // wx.navigateTo({
    //   url: '/pages/MaterialFlow/MaterialFlow',
    // })
  },
  flowOnClose: function () {
    this.setData({
      flowShow: false
    })
  },
  /**
   * 获取退款申请详情
   */
  getRefundDetail: function (e) {
    var ths = this;
    // wx.showLoading({})
    var params = {
      url: "/p/orderRefund/info",
      method: "GET",
      data: {
        refundSn: this.data.refundSn //退款编号
      },
      callBack: function (res) {
        let img=''
        res.orderItems.map(item=>{
          img=item.pic.split(',')
          item.pic=img[0]
        })
        ths.setData({
          applyTime: res.applyTime, //申请时间
          applyType: res.applyType, //申请类型:1,仅退款,2退款退货
          goodsNum: res.goodsNum, //退货数量
          handelTime: res.handelTime, //卖家处理时间
          orderAmount: res.orderAmount, //订单总金额
          orderItems: res.orderItems, //订单项 
          refundSn: res.refundSn, //退款编号
          refundAmount: res.refundAmount, //退款金额
          refundDelivery: res.refundDelivery, //收货地址对象
          refundId: res.refundId, //记录ID
          refundTime: res.refundTime, //退款时间
          returnMoneySts: res.returnMoneySts, //处理退款状态:(1.买家申请 2.卖家接受 3.买家发货 4.卖家收货 5.退款成功 6.买家撤回申请 7.商家拒绝 -1.退款关闭)
          updateTime: res.updateTime, //更新时间
          rejectMessage: res.rejectMessage, //拒绝理由
          buyerReason: res.buyerReason, //退款原因
          shopName: res.shopName,
          refundScore: res.refundScore, // 退款积分
          payer: res.refundDelivery.payer,//运费承担方
          sendPay:res.refundDelivery.deyNu //物流编号，判断是否提交成功
        })
        wx.hideLoading();
        ths.get_countDown()
      }
    };
    http.request(params);
  },
/**
 * 同意后倒计时
 * @param {*} e 
 */
get_countDown:function(){
  const start = new Date(this.data.handelTime);
    const end = new Date(start.getTime() + 48 * 60 * 60 * 1000);
    const interval = setInterval(() => {
      const now = new Date();
      const diff = end - now;
      if (diff <= 0) {
        clearInterval(interval);
        this.setData({
          countdown_hours: '00天',
          countdown_minutes:'00分钟'
        });
      } else {
        const hours = Math.floor(diff / (1000 * 60 * 60));
        const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
        this.setData({
          countdown_hours:String(hours).padStart(2, '0'),
          countdown_minutes:String(minutes).padStart(2, '0')
          // countdown_time:`${String(hours).padStart(2, '0')}小时${String(minutes).padStart(2, '0')}分钟`
        });
      }
    }, 1000);
},
  /**
   * 撤销退货退款申请
   */
  cancelApplication: function (e) {
    console.log('撤销申请')
    wx.showModal({
      title: '撤销',
      content: '确定要撤销本次申请？',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({})
          var params = {
            url: "/p/orderRefund/cancel",
            method: "PUT",
            data: this.data.refundSn, //退款订单编号
            callBack: function (res) {
              wx.hideLoading();
              wx.navigateTo({
                url: '/pages/afterSales/afterSales',
              })
            }
          };
          http.request(params);
        } else {
          console.log('取消')
        }
      }
    })

  },


  /**
   * 跳转修改退款申请
   */
  // toAlterRefundApply: function (e) {
  //   var refundSn = e.currentTarget.dataset.refundsn;
  //   console.log(e.currentTarget.dataset.refundsn)
  //   wx.navigateTo({
  //     url: '/pages/applyRefund/applyRefund?refundSn=' + refundSn,
  //   })
  // },


  /**
   * 填写物流信息
   */
  toLogisticsPage: function (e) {
    var refundSn = e.currentTarget.dataset.refundsn;
    console.log(e.currentTarget.dataset.refundsn)
    wx.navigateTo({
      url: '/pages/writeReturnLogistics/writeReturnLogistics?refundSn=' + refundSn,
    })
  },


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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})