// pages/applyRefund/applyRefund.js
var http = require('../../utils/http.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {

    applyType: 1, //退款方式(1:仅退款 2退款退货)
    refundItem: {}, //订单项数据
    show:false,
    isAll:false,
    photoFiles: [], //凭证图片列表
    buyerDesc: '', //备注说明
    loading:false,
    goodList:[],
    reasonList:[
      {name:'暂不需要商品(买错/多买/漏买)'},
      {name:'冰品融化'},
      {name:'订单中有商品发错'},
      {name:'商品斤两不足'},
      {name:'商品临期到期'},
      {name:'商品破损/包装破损'},
      {name:'商品质量问题'},
      {name:'实物与图文描述不符'},
      {name:'商家通知我卖完了'},
      {name:'所有商品未收到'},
      {name:'整个订单送错'},
      {name:'订单少选且商家未通知我'},
      {name:'未在约定时间送达'},
    ],
    buyerReason: '', //退款原因
    total:0,
    refundId:0,//再次申请售后id
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let refundId = options.refundId || 0
    var refundItem
    if(refundId){//再次申请
      this.loadOrderDetail(options.orderNumber,refundId)
    }else{
      refundItem = wx.getStorageSync("refundItem");
      console.log('拿到缓存里的订单项数据refundItem:',refundItem)
      let orderItemDtos = []
      refundItem.orderItemDtos.forEach((item1,index)=>{
        let item = item1
        if(item.prodCount-item.refundCount){//剩余商品数量大于0
          item.num = item.prodCount-item.refundCount
          item.checked = true
          orderItemDtos.push(item)
        }
      })
      refundItem.orderItemDtos = orderItemDtos
      this.setData({
        refundId,
        refundItem: refundItem,
        orderNumber: refundItem.orderNumber,
        goodsNum: refundItem.prodCount,
        actualTotal: refundItem.actualTotal,  //总额
        isLastProd: refundItem.isLastProd,  //是否最后一样商品
        addTransfee: refundItem.addTransfee, //只有一件商品可以退运费
        orderScore: refundItem.useScore // 单个退积分
      })
      this.totalPrice()
      this.checkAll()
    }
  },
    /**
   * 评价图片预览
   */
  picPreView(e){
    var index = e.currentTarget.dataset.index
    var urls = []
    this.data.photoFiles.forEach(el => {
      urls.push(el.url)
    })
    wx.previewImage({
      current: urls[index],
      urls: urls
    })
  },
  // 实时监听输入
  onInput: function(e) {
    // e.detail.value 即为当前输入的内容
    this.setData({
      buyerDesc: e.detail.value
    });
  },
  /**
   * 加载订单数据
   */
  loadOrderDetail: function(orderNumber,refundId) {
    var ths = this;
    wx.showLoading();
    //加载订单详情
    var params = {
      url: "/p/myOrder/orderDetail",
      method: "GET",
      data: {
        orderNumber
      },
      callBack: function(res) {
        let orderItemDtos = []
        res.orderItemDtos.forEach((item1,index)=>{
          let item = item1
          if(item.prodCount-item.refundCount){//剩余商品数量大于0
            item.num = item.prodCount-item.refundCount
            item.checked = true
            orderItemDtos.push(item)
          }
      })
  
      res.orderItemDtos = orderItemDtos
      wx.hideLoading();
      ths.setData({
        refundId,
        refundItem: res,
        orderNumber,
        goodsNum: res.prodCount,
        actualTotal: res.actualTotal,  //总额
        isLastProd: res.isLastProd,  //是否最后一样商品
        addTransfee: res.addTransfee, //只有一件商品可以退运费
        orderScore: res.useScore // 单个退积分
      })
      ths.totalPrice()
      ths.checkAll()
      }
    };
    http.request(params);

  },
   /**
   * 提交退款
   */
  apply(){
    console.log(this.data.refundItem.orderItemDtos,this.data.refundItem.orderItemDtos.some(i=>i.checked));
    let that = this
     // 检查数据完整性
     if (this.data.buyerReason === '') {
        return wx.showToast({
          icon: 'none',
          title: '请选择退款原因',
        })
      }else if(!this.data.refundItem.orderItemDtos.some(i=>i.checked)){
        return wx.showToast({
          icon: 'none',
          title: '请选择退款商品',
        })
      }else if(this.loading){
        return
      }
      
    this.loading = true
    wx.showLoading();
    var pics = '';
    this.data.photoFiles.forEach(function (item) {
      pics += item.path + ',';
    });
    if (pics != '') {
      pics = pics.substring(0, pics.length - 1)
    }
    let goodsNum = 0
    let refundAmount = this.data.total 
    let orderRefundSkuList = []
    this.data.refundItem.orderItemDtos.forEach(item=>{
      if(item.checked){
        orderRefundSkuList.push({
          "productCount": item.num,
          "skuId": item.skuId,
          "skuPrice": item.price,
          "orderItemId": item.orderItemId,
        })
        goodsNum+=item.num
      }
    })
    if(this.data.refundItem.actualTotal == 0){//积分支付 不用管退款金额
      refundAmount = 0
    }else if(refundAmount>=this.data.refundItem.actualTotal){//支付了钱的订单 并且退款钱超过实际支付钱 传实际支付金额
      refundAmount = this.data.refundItem.actualTotal
    }

    let data = {
      orderNumber: this.data.orderNumber, //订单编号
      applyType: this.data.applyType, //退款方式(1:仅退款 2退款退货)
      isReceiver: this.data.applyType == 1?0:1, //货物状态(1:已收到货 0:未收到货)
      buyerReason: this.data.reasonList[this.data.buyerReason].name, //退款原因
      goodsNum, //退款数量（0或不传值则为全部数量）
      refundAmount: refundAmount, //退款金额
      freightAmount:this.data.refundItem.transfee,
      buyerMobile: this.data.refundItem.userAddrDto.mobile, //手机号码（默认当前订单手机号码）
      buyerDesc: this.data.buyerDesc, //备注说明
      photoFiles: pics, //凭证图片列表
      refundType: goodsNum == this.data.refundItem.totalNum ?1:2, //退款单类型（1:整单退款,2:单个物品退款）
      orderRefundSkuList: orderRefundSkuList
    }
    if(this.data.refundId){//再次申请
      data.refundId = this.data.refundId
       console.log('再次申请');
    }else{
       console.log('申请');

    }
    var params = {
      url:this.data.refundId?"/p/orderRefund/applyAgain": "/p/orderRefund/apply",
      method: "POST",
      data,
      callBack: (res) => {
        that.loading = false
        wx.hideLoading();
        if(res.code == 500){
          return wx.showToast({
            title: res.msg,
            icon:'none'
          })
        }
        // 去到我的退款订单页面
        wx.redirectTo({
          url: '/pages/afterSales/afterSales',
        })
      }
    };
    http.request(params);
  },

  /**
   * 打开选择原因弹窗
   */
  choose(){
    this.setData({
      show:true
    })
  },

  close(){
    this.setData({
      show:false
    })
  },
 /**
   * 选择原因
   */
  chooseReason(e){
   console.log(e);
    this.setData({
      buyerReason:Number(e.detail.value)
    })
  },
  /**
   * 确认原因
   */
  submitReason(){
   this.setData({
     show:false
   })
  },
  
  /** */
  delImg(e){
    let index = e.currentTarget.dataset.index
    let photoFiles = this.data.photoFiles
    photoFiles.splice(index,1)
    this.setData({
      photoFiles: photoFiles
    })
  },

   /**
   * 上传图片
   */
  getUploadImg: function(e) {
    console.log('上传图片开始');
    if(this.data.photoFiles.length == 5){
      return wx.showToast({
        title: '最多可上传5张图片',
      })
    }
    var ths = this;
    wx.chooseMedia({
      count: 1, // 默认9
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      success: function(res) {
        console.log('选择图片完成：',res);
        // 图片的本地临时文件路径列表
        var tempFilePaths = res.tempFiles[0].tempFilePath;
        wx.showLoading({
          mask: true
        })
        var params = {
          url: "/p/file/upload",
          filePath: tempFilePaths,
          name: 'file',
          callBack: function(res2) {
            console.log('上传接口：',res2);
            wx.hideLoading();
            var img = {};
            img.path = JSON.parse(res2).filePath;
            img.url = JSON.parse(res2).resourcesUrl + JSON.parse(res2).filePath;
            var photoFiles = ths.data.photoFiles;
            photoFiles.push(img);
            ths.setData({
              photoFiles: photoFiles
            })
          }
        };
        http.upload(params);
      }
    })
  },

  /**
   * 选择类型
   */
  radioChange(e){
    console.log(e);
    this.setData({
      applyType:e.detail.value
    })
  },

  /**
   * 全选
   */
  onSelectedAll(e){
    console.log(e,this.data);

    let isAll = !this.data.isAll
    let refundItem =  this.data.refundItem
    refundItem.orderItemDtos.forEach(item=>{
      item.checked = isAll
    })
    this.setData({
      isAll,
      refundItem
    })
    this.totalPrice()

  },
/**
 * 单选
 */
  onSelectedItem(e){
    let index = e.currentTarget.dataset.index
    let refundItem =  this.data.refundItem
    refundItem.orderItemDtos[index].checked = !refundItem.orderItemDtos[index].checked
    this.setData({
      refundItem
    })
    this.checkAll()
    this.totalPrice()
  },

  /**
   * 检查全选状态
   */

   checkAll(){
    let isAll = this.data.refundItem.orderItemDtos.every(i=>i.checked)
    this.setData({
      isAll
    })
   },

  /**
   * 计算总价
   */

   totalPrice(){
     let total = 0
     let num = 0
      this.data.refundItem.orderItemDtos.forEach(item=>{
        if(item.checked){
          total += Math.round(item.price*100)*item.num
          num+=item.num
        }
      })
      if(num == this.data.refundItem.totalNum){//全部商品退款 +运费
        total += Math.round(this.data.refundItem.transfee* 100)  
      }

      this.setData({
        total:total/100
      })
   },

  /**
   * 操作数量
   */
  changeNum(e){
    let index = e.currentTarget.dataset.index
    let num = e.currentTarget.dataset.num
    let refundItem =  this.data.refundItem
    if(num == -1&&refundItem.orderItemDtos[index].num == 1){
     return wx.showToast({
        title: '数量不能小于1',
        duration: 1200,
        icon: 'none',
      })
    }else if(num == 1&&refundItem.orderItemDtos[index].num == (refundItem.orderItemDtos[index].prodCount-refundItem.orderItemDtos[index].refundCount)){
      return wx.showToast({
        title: '不能超过购买数量',
        duration: 1200,
        icon: 'none',
      })
    }
    refundItem.orderItemDtos[index].num +=num
    this.setData({
      refundItem
    })
    this.totalPrice()
  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})