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

wxService.page({

  /**
   * 页面的初始数据
   */
  data: {
    imageDomain: '',
    refundCreateDto: {
      reason: "", // 原因
      skuList: [],
      tradeId: 0,
      proofImgUrls: [] //凭证
    },
    refundMark: '',
    cartList: [],
    curType: { // 当前选择原因
      value: 0,
      name: '请选择'
    },
    // 所有退货原因
    resonType: [],
    refundAmount: 0,
    checkedColor: 'rgb(203, 60, 60)',
    pics: [],
    id: '',
    returnOrder: 0
  },
  submitRefund() {
    var selectGoods = this.data.cartList.filter(item => item.checked)
    if (selectGoods.length == 0) {
      wx.showToast({
        title: '请选择退款商品',
        icon: 'none'
      })
      return false
    }
    if (this.data.curType.value == 0) {
      wx.showToast({
        title: '请选择退款原因',
        icon: 'none'
      })
      return false
    }

    let skulist = [];
    selectGoods.forEach(item=>{
      const {skuId,count} = item;
      skulist.push({
        skuId,
        count
      })
    });

    this.reFundPreview({
      tradeId: this.data.id,
      skuList:skulist
    })

    var refundCreateDto = this.data.refundCreateDto
    refundCreateDto.reason = this.data.curType.name // 退款原因
    refundCreateDto.remark = this.data.refundMark// 说明备注

    refundCreateDto.skuList = selectGoods.map(function (item) {
      return {
        amount: item.amount,
        count: item.count,
        skuId: item.skuId
      }
    })
   this.handelRequestRefund(refundCreateDto)
  },
  //创建退款
  handelRequestRefund(params) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wxService.post('/sale/refund/buyer/create', params).then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          wx.hideLoading()
          wx.showToast({
            title: '申请退款成功',
          });
          // 订单列表
          setTimeout(() => {
            // wxService.router(`/pages/order/order`).search({params})
            wx.navigateBack({
              delta : 1
            });
          }, 2000)
        }
      }
    })

  },
  //获取退款原因列表
  getReasonList() {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    const refundReason = {}
    wxService.post('/sale/refund/reason/buyer/sortAll', refundReason).then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          wx.hideLoading()

          let newReasonList = [];
          data.forEach((item,index)=>{
            const {reason} = item;
            newReasonList.push({
              name: reason,
              value: index + 1
            })
          });
          this.setData({
            resonType: newReasonList
          })
        }
      }
    })
  },
  // 上传图片
  _uploadImg(e) {
    if (e.detail) {
      this.data.refundCreateDto.proofImgUrls.push(e.detail)
      this.setData({
        'refundCreateDto.proofImgUrls': this.data.refundCreateDto.proofImgUrls
      })
    }
  },

  checkPro(e) {
    var index = e.currentTarget.dataset.index
    const { cartList } = this.data
    if (cartList[index].checked) {
      cartList[index].checked = false
    } else {
      cartList[index].checked = true
    }
    this.setData({
      cartList
    },()=>{
      this.getReturnPrice()
    })
  },
  changeRemark(event) { // 备注
    this.setData({
      refundMark: event.detail.value
    })
  },
  selectType: function (event) { // 选择退货类型
    this.setData({
      curType: this.data.resonType[event.detail.value]
    })
  },
  minusNum: function (e) { // 减少数量
    var cartList = this.data.cartList
    var index = e.currentTarget.dataset.index
    let proNum = cartList[index].count

    if (proNum > 1) {
      proNum--
    } else {
      wx.showToast({
        title: '数量不能为0',
        icon: 'none'
      })
      return false
    }
    cartList[index].count = proNum
    this.setData({
      cartList: cartList
    }, () => {
      this.getReturnPrice()
      this.editOk(cartList[index]) //调用完成
    })
  },
  //新增数量
  addNum: function (e) { // 增加数量
    var index = e.currentTarget.dataset.index
    var cartList = this.data.cartList
    var proNum = cartList[index].count;
    if (proNum < cartList[index].canRefundNum){
      proNum++
    }
    else{
      wx.showToast({
        title: '退单数量不能大于当前商品购买数量',
        icon : 'none'
      });
      return ;
    }

    cartList[index].count = proNum
    this.setData({
      cartList: cartList
    }, () => {
      this.getReturnPrice()
      this.editOk(cartList[index]) //调用完成
    })

  },
  blurNum: function (e) { // 输入数量
    var newNum = e.detail.value
    var cartList = this.data.cartList
    var index = e.currentTarget.dataset.index
    var refundNum = cartList[index].count

    if (newNum === '' || newNum === '0') {
      newNum = 1
    } else {
      newNum = parseInt(newNum)
      if (newNum > refundNum) {
        newNum = refundNum
      } else {
        newNum = newNum
      }
    }
    cartList[index].count = newNum

    this.setData({
      cartList: cartList
    }, () => {
      this.getReturnPrice()
      this.editOk(cartList[index]) //调用完成
    })
  },
  editOk(cartPro){
    let skulist = [];
    const {skuId,count} = cartPro;
    skulist.push({
      skuId,
      count
    })
    
    this.reFundPreview({
      tradeId: this.data.id,
      skuList:skulist}) // 退款预览
  },
  getReturnPrice() {
    var cartList = this.data.cartList
    var returnPrice = 0

    for (let i = 0; i < cartList.length; i++) {
      if (cartList[i].checked) {
        returnPrice += cartList[i].paySkuPrice * (cartList[i].count ? cartList[i].count : 1)
      }
    }

    let tempPrice = parseInt(returnPrice * 100);

    this.setData({
      returnOrder: parseFloat(tempPrice/100).toFixed(2)
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu();
    const { params } = options;
    let detail = JSON.parse(params)
    
    // item.checked
    detail.skuVOList.forEach(item => {
      item.checked = false;
      let paySkuPrice = parseInt(item.amount * 100 / item.totalCount);
      item.paySkuPrice = (paySkuPrice/100).toFixed(2);
    });

    this.setData({
      id: detail.id,
      cartList: detail.skuVOList,
      refundAmount: detail.payAmount,
      'refundCreateDto.tradeId': detail.id
    }, () => {
      // 退款原因列表 /refund/reason/buyer/sortAll
      this.getReasonList()
    })
  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },
  //退款prever
  reFundPreview(cartPro={}) {
    const params = {...cartPro}
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wxService.post(`/sale/refund/buyer/preview`,params).then(res => {
      if (res) {
        const { result, data } = res.data
        if (result == 0) {
          wx.hideLoading()
        }
      }
    })
  },
  
});