// 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退款退货
    dvyType: 1, //配送类型 1:快递 2:自提 3：及时配送
    isReturnLogistics: false, //配送类型 1:快递 2:自提 3：及时配送
    goodsNum: '', //退货数量
    handelTime: '', //卖家处理时间
    orderAmount: '', //订单总金额
    orderItems: {}, //订单项 
    refundAmount: '', //退款金额
    goodsTotal:0,
    records:[],//退款流程
    offsetPoints:0,//退还积分
    refundExpiredScore:0,//过期积分
    freightAmount:0,
    refundStatusObj:{
      1:'申请原因',
      2:'商家待审核',
      3:'申请已通过',
      4:'用户撤回申请',
      5:'用户待发货',
      // 6:'待填写配送信息',
      7:'商家待收货',
      10:'审核通过',
      20:'驳回',
      25:'已收货',
      30:'退款成功',
    },
    refundDelivery: [], //收货地址对象
    refundId: '', //记录ID
    refundTime: '', //退款时间
    returnMoneySts: 1, //处理退款状态:(1.买家申请 2.卖家接受 3.买家发货 4.卖家收货 5.退款成功 6.买家撤回申请 7.商家拒绝 -1.退款关闭)
    updateTime: '', //更新时间
    refundSn: '', //退款编号
    rejectMessage: '', //拒绝理由
    buyerReason: '', //退款原因
    shopName: '', //店铺名称
    refundScore: 0, // 退款积分
    photoFiles:[],
    refundPhotoFiles:[],//退货物流图片
    addCarshow: false,
    selectTimeshow: false,
    flowShow: false,
    userAddrDto: {},
    payer: '',
    sendPay:'',
    sts: 0,
    nomDay: '',
    tomorrowDay: '',
    timeIntervals: [],
    columns: [],
    selectTimeshow: false,
    time: '',//取件时间
    userAddr: '',//取件地址
    shopInfo:null,
    sendInfo: {},
    currentSelectedIndex: -1, // 初始没有选中项，索引设为 -1
    cancelPay: false,
    remainingTime: '',
    timeFormat: '',
    orderNumSend:'',
    countdown_hours:'',
    countdown_minutes:'',
    statusObj:{
      10:{
        title:'待审核',
        desc:'等待商家处理申请'
      },
      20:{
        title:'处理中',
        desc:'申请通过后，将退回至原账户'
      },
      30:{
        title:'驳回退款',
        desc:'您的申请已被商家拒绝'
      },
      40:{
        title:'撤销退款',
        desc:'您已主动取消退款申请，如有需要可再次申请。'
      },
      60:{
        title:'待退货',
        desc:''
      },
      65:{
        title:'待商家收货',
        desc:'待商家收到商品，并确认不影响二次销售后，将为您退款'
      },
      70:{
        title:'退款完成',
        desc:'申请已通过，已退回至原账户'
      },
    }
  },

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

  },
  // 配送退货提交
  submit(e){
    console.log(e);
    if(!this.data.time){
      return wx.showToast({
        title:'请选择时间',
        icon:'none'
      })
    }else if(!e.currentTarget.dataset.info){
      return wx.showToast({
        title:'请选择收件地址',
        icon:'none'
      })
    }
    let that = this
    var params = {
      url: "/p/appointment",
      method: "POST",
      data: {
        appointmentTime:that.data.time,
        deliveryAddress:e.currentTarget.dataset.info.address+e.currentTarget.dataset.info.addressName,
        customerName:e.currentTarget.dataset.info.receiver,
        refundNumber:that.data.refundSn,
        phoneNumber:e.currentTarget.dataset.info.mobile,
        refundMethod:1,
      },
      callBack: (res)=> {
         //获取退款申请详情
         that.getRefundDetail()
      }
    }
    http.request(params);
  },
  // 获取配送退货填写内容
  getRefundWriteInfo(){
    let that = this
    var params = {
      url: "/p/appointment/"+this.data.refundSn,
      method: "GET",
      data: {
      },
      callBack: (res)=> {
        let userAddr = {}
        userAddr.addrDetail = ''
        userAddr.addressName = res.data.deliveryAddress
        userAddr.receiver =  res.data.customerName
        userAddr.mobile =  res.data.phoneNumber
        that.setData({
          time:res.data.appointmentTime,
          userAddr
        })
        console.log(that.data.time);
      }
    }
    http.request(params);
  },
   /**
   * 获取退款申请详情
   */
  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]
        })
        let photoFiles = []
        let refundPhotoFiles = []
        if(res.photoFiles){
          photoFiles = res.photoFiles.split(',')
        }
        if(res.refundDelivery.imgs){
          refundPhotoFiles = res.refundDelivery.imgs.split(',')
        }
        if(res.returnMoneySts == 60&&res.applyType == 2&&res.dvyType==1){//快递寄回
          ths.getShopAddress(res.refundDelivery.shopId)
        }else if((res.returnMoneySts == 65||res.returnMoneySts == 70)&&res.applyType == 2&&res.dvyType==3&&res.isReturnLogistics){
          ths.getRefundWriteInfo()
        }

        ths.setData({
          applyTime: res.applyTime, //申请时间
          applyType: res.applyType, //申请类型:1,仅退款,2退款退货
          dvyType: res.dvyType, //配送类型 1:快递 2:自提 3：及时配送
          isReturnLogistics: res.isReturnLogistics, //配送类型 1:快递 2:自提 3：及时配送
          goodsNum: res.goodsNum, //退货数量
          handelTime: res.handelTime, //卖家处理时间
          orderAmount: res.orderAmount, //订单总金额
          orderItems: res.orderItems, //订单项 
          orderNumber: res.orderNumber, //订单项 
          refundSn: res.refundSn, //退款编号
          refundAmount: res.refundAmount, //实际退款金额
          goodsTotal:res.goodsTotal,//总共退款价值
          records:res.records,//退款流程
          offsetPoints:res.offsetPoints,//退还积分
          refundExpiredScore:res.refundExpiredScore,//过期积分
          freightAmount:res.freightAmount,
          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, //退款原因
          photoFiles, //图片
          refundPhotoFiles,//退款图片
          shopName: res.shopName,
          refundScore: res.refundScore, // 退款积分
          payer: res.refundDelivery.payer,//运费承担方
          sendPay:res.refundDelivery.deyNu //物流编号，判断是否提交成功
        })
        wx.hideLoading();
        // ths.get_countDown()
      }
    };
    http.request(params);
  },

  // 获取退货地址
  getShopAddress(shopId){
    var ths = this;
    var params = {
      url: "/p/refundAddr/info/"+shopId,
      method: "GET",
      callBack: res => {
        if(res.code == 200){
          ths.setData({
            shopInfo:res.data
          })
        }
      }
    };
    http.request(params);
  },

  // 一键复制事件
  copyBtn: function(e) {
    let data = e.currentTarget.dataset.value
    wx.setClipboardData({
      //准备复制的数据
      data,
      success: function(res) {
        wx.showToast({
          title: '复制成功',
        });
      }
    })
  },
  /**
   * 选择时间和地址
   */
  choose(e){
    let type = e.currentTarget.dataset.type
    if(type == 'time'){
      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
      })
    }else{//选择地址
      wx.navigateTo({
        url: '/pages/delivery-address/delivery-address?order=write',
      })
    }
  },
  onCancel: function () {
    this.setData({
      selectTimeshow: false
    })
  },
  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
      console.log(combinedText);
      this.setData({
        time: combinedText,
        selectTimeshow: false
      });
    }
  },

  // 获取今明天并转换
  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]));
  },
  /**
   * 填写快递信息
   */
  writeInfo(e){
    var refundSn = e.currentTarget.dataset.refundsn;
    var type = e.currentTarget.dataset.type;
    wx.navigateTo({
      url: `/pages/writeReturnLogistics/writeReturnLogistics?refundSn=${refundSn}&shopId=${this.data.refundDelivery.shopId}&type=${type}`,
    })
  },

  

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})