// pages/member/refund/refund.js
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    language: "",

    order_id: "",
    refund_id: "",

    //处理方式
    refundTypes: [],
    //退款原因

    money: 0.0,

    typeData: 1,

    fileList1: [],//凭证图片
    isValue:'',


    order_status:0, //订单状态

    //退款商品
    returnAllGoodsList:[],
    returnGoolsList:[],

    //售后类型
    returnTypeItem:{},

    //收货状态
    receivingStatus:"not_received",

    //退货方式
    returnMethods:0,
    send_back_way:[],

    //退款原因
    returnReasons:"",

    //退款说明
    returnExplain:"",

    //京东上门取件相关信息
    jdTakeParts:null,
    jd_weight:'', 
    jd_length:'',
    jd_width:'',
    jd_height:'',

    start_time:'',
    end_time:'',

    jd_address:{
      pick_up_name : '',
      pick_up_tel : '',
      pick_up_province : 0,
      pick_up_city : 0,
      pick_up_district : 0,
      pick_up_street : 0,
      pick_up_address : '',
      addressName:""
    },
    refundable_freight: 0, //可退运费
    refundable_other: 0, //其他费用
    freight_price: "", //可退运费
    other_price: "", //其他费用
    showInstructions: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.order_id) {
      this.setData({
        refund_id: options.order_id,
        order_id: options.order_id,
      });
    }
    if(options.value){
      this.setData({
        isValue:options.value
      });
    }
    if (options.type) {
      this.setData({
        typeData: options.type,
      });
    }
    if(options.refundType){
      this.setData({
        refundType: options.refundType,
      });
    }
    if (options.type == 2) {
      //修改申请
      wx.setNavigationBarTitle({
        title: "修改申请",
      });
      this.getAlterInfo();
    } else {
      wx.setNavigationBarTitle({
        title: "售后申请",
      });
      this.getRefundInfo();
    }
    // this.openComponentsPop('pickUpTime');
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync("langIndex");
    this.setData({ language: language.en });
  },

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

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

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

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

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

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  getAlterInfo() {
    let urlStr = app.getNetAddresss("refund.edit");
    urlStr += "&refund_id=" + this.data.order_id;
    app._getNetWork({
      url: urlStr,
      success: (resdata)=> {
        var res = resdata.data;
        if (res.result == 1) {
          var mydata = res.data;
          let changeData = {};
          changeData.refundable_freight = Number(mydata.refundable_freight) || 0; //可退运费
          changeData.refundable_other = Number(mydata.refundable_other) || 0; //其他费用
          changeData.freight_price = Number(mydata.refundApply.freight_price) || ""; //可退运费
          changeData.other_price = Number(mydata.refundApply.other_price) || ""; //其他费用
          changeData.money= Number(mydata.refundApply.apply_price).toFixed(2);
          changeData.refundTypes = mydata.refundTypes;
          changeData.send_back_way = mydata.send_back_way;
          if(mydata.refundApply.receive_status==1){
            changeData.receivingStatus = "received";
          }else {
            changeData.receivingStatus = "not_received";
          }
          this.selectComponent(`.receivingStatus`).setRadio(mydata.refundApply.receive_status);
          changeData.returnTypeItem = changeData.refundTypes[mydata.refundApply.refund_type];
          changeData.returnReasons = mydata.refundApply.reason;
          changeData.returnExplain =  mydata.refundApply.content;
          changeData.fileList1 = mydata.refundApply.images;
          changeData.returnMethods = mydata.refundApply.refund_way_type;
          this.selectComponent('.returnMethods').setRadio(changeData.returnMethods);
          changeData.returnGoolsList = mydata.refundApply.refund_order_goods;
          changeData.order_status = mydata.refundApply.order.status;
          
          if(changeData.returnMethods==1 && mydata.send_back_way_data){
            this.getJdTakeParts(mydata.send_back_way_data);
          }else if(changeData.returnMethods==1){
            this.getJdTakeParts();
          }
          this.setData(changeData);
          
        } else {
          app.tips(res.msg);
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  //获取退款信息
  getRefundInfo() {
    let urlStr = app.getNetAddresss("refund.apply");
    if(!app._isTextEmpty(this.data.refundType) && this.data.refundType=="installationSever"){
      urlStr= app.getNetAddresss("plugin.live-install.frontend.apply.index");  //安装服务
    }
    if(!app._isTextEmpty(this.data.isValue)){
      // 盲盒
      urlStr= app.getNetAddresss("plugin.blind-box.api.apply.index");
    }
    urlStr += "&order_id=" + this.data.order_id;
    app._getNetWork({
      url: urlStr,
      success: (resdata)=> {
        var res = resdata.data;
        if (res.result == 1) {
          var mydata = res.data;
          this.setData({
            refundable_freight : Number(mydata.refundable_freight) || 0, //可退运费
            refundable_other : Number(mydata.refundable_other) || 0, //其他费用
            money: mydata.order.price.toFixed(2),
            refundTypes: mydata.refundTypes,
            order_status:mydata.order.status,
            send_back_way:mydata.send_back_way,
            returnMethods:mydata.send_back_way[0] ? mydata.send_back_way[0].value : 0,
            returnAllGoodsList:mydata.order.order_goods.filter((item)=>{
              item.stepperValue = 1;
              return item.is_refund==0;
            })
          });
          if(this.data.order_status>=2 && mydata.support_batch){
            //support_batch 参数 true 支持单商品退款 false不支持， 先判断下订单是否支持选择商品退款
            // 不支持的就显示商品就行了，提交时也不用传 order_goods 参数
            this.openComponentsPop('returnGoods');
          }else {
            this.openComponentsPop('returnType');
          }

        } else {
          app.tips(res.msg);
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },

  //提交退款申请
  confirmRefund() {
    if (this.data.returnTypeItem.value!=2 && this.data.returnReasons=="") {
      return app.tips("请选择申请原因！");
    }
    if (this.data.refundable_freight > 0 && Number(this.data.freight_price) > this.data.refundable_freight) {
      return app.tips(`退款运费金额最大为${this.data.refundable_freight}`);
    }
    if (this.data.refundable_other > 0 && Number(this.data.other_price) > this.data.refundable_other) {
      return app.tips(`退款其他金额最大为${this.data.refundable_other}`);
    }

    let json = {
      order_id:this.data.order_id,
      refund_id:this.data.refund_id,
      refund_type:this.data.returnTypeItem.value,
      reason:this.data.returnReasons,
      content:this.data.returnExplain,
      receive_status:this.data.receivingStatus=="not_received" ? 0 : 1,
      refund_way_type:this.data.returnMethods,
      freight_price: this.data.freight_price || 0,
      other_price: this.data.other_price || 0
    };

    if(this.data.order_status>0){
      let arr=[];
      this.data.returnGoolsList.forEach(element => {
        let o = {};
        o.id = element.id;
        o.total = element.refund_total;
        arr.push(o);
      });
      if(arr.length > 0) json.order_goods = arr;
      json.part_refund = 1;
    }

    //上门取货
    if(this.data.returnMethods==1){
      if(!this.data.start_time || !this.data.end_time) return app.tips('请选择取件时间');
      Object.assign(json,this.data.jd_address);
      json.jd_weight = this.data.jd_weight;
      json.jd_length = this.data.jd_length;
      json.jd_width = this.data.jd_width;
      json.jd_height = this.data.jd_height;
      json.start_time = this.data.start_time;
      json.end_time = this.data.end_time;
    }
   

    let urlStr = "";
    if (this.data.typeData == 1) {
      urlStr = app.getNetAddresss("refund.apply.store");
    } else if (this.data.typeData == 3) {
      urlStr = app.getNetAddresss("plugin.snatch-regiment.api.order.refund");
    } else {
      urlStr = app.getNetAddresss("refund.edit.store");
    }
    if(!app._isTextEmpty(this.data.refundType) && this.data.refundType=="installationSever"){
      urlStr= app.getNetAddresss("plugin.live-install.frontend.apply.store");  //安装服务
    }
    if(!app._isTextEmpty(this.data.isValue)){
    // 盲盒
      urlStr= app.getNetAddresss("plugin.blind-box.api.apply.store");
    }
    if(this.data.fileList1.length > 0) {
      json.images = JSON.stringify(this.data.fileList1);
    }

    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1500,
            success: function () {
              setTimeout(function () {
                //要延时执行的代码
                wx.navigateBack({
                  delta: 1,
                });
              }, 1500); //延迟时间
            },
          });
        } else {
          app.tips(res.msg);
        }
      },
      fail: function (res) {},
    });
  },
  updateImages(e) {
    this.setData({
      fileList1: e.detail
    });
  },

  openComponentsPop(evt) {
    let name=evt.currentTarget ? evt.currentTarget.dataset.name : evt;
    this.selectComponent(`.${name}`).setPopShow();
  },

  confrimReturnType(evt){
    let item = evt.detail.item;
    if(this.data.returnTypeItem.value == item.value) return;
    let changeData={};
    if(item.value !=0 ){
      changeData.receivingStatus="received";
    }
    changeData.returnTypeItem = item;
    changeData.returnReasons="";
    this.setData(changeData);
  },
  confirmReturnReason(evt){
    let text = evt.detail.text;
    this.setData({returnReasons:text});
  },
  confrimReturnGoods(evt){
    this.setData({
      returnGoolsList:evt.detail.modelsArr,
      money:evt.detail.total_price
    });
    this.openComponentsPop('returnType');
  },
  confirmReceivingStatus(evt){
    this.setData({
      receivingStatus:evt.detail.status
    });
  },
  confirmReturnMethods(evt){
    this.setData({
      returnMethods:evt.detail.status
    });
    if(this.data.returnMethods == 1 && this.data.jdTakeParts==null){
      this.getJdTakeParts();
    }
  },
  confirmPickUpTime(evt){
    this.setData({
      start_time:evt.detail.start_time,
      end_time:evt.detail.end_time
    });
  },

  confirmEditAddress(evt){
    this.setData({
      jd_address:evt.detail
    });
    let _json = {
      province_id: evt.detail.pick_up_province,
      city_id: evt.detail.pick_up_city,
      district_id: evt.detail.pick_up_district,
      street_id: evt.detail.pick_up_street,
      address: evt.detail.pick_up_address
    };
    this.getPickUpTime(_json);
  },

  //获取京东上门安装默认数据
  getJdTakeParts(defaultData = null){
    let urlStr = app.getNetAddresss("plugin.jd-take-parts.frontend.refund.get-default-data");
    app._postNetWork({
      url: urlStr,
      data: { order_id:this.data.order_id},
      success:  (resdata)=> {
        var res = resdata.data;
        if (res.result == 1) {
          // this.selectComponent(`.pickUpTime`).setListData(res.data.time_list);
          if(defaultData == null){
            this.setData({
              jdTakeParts:res.data,
              jd_height:res.data.default.default_height,
              jd_length:res.data.default.default_length,
              jd_weight:res.data.default.default_weight,
              jd_width:res.data.default.default_width,
            });
            this.selectComponent(`.editAddress`).setFormData(res.data.order_address);
            this.getPickUpTime(res.data.order_address);
          }else {
            this.setData({
              jdTakeParts:res.data,
              jd_height:defaultData.jd_height,
              jd_length:defaultData.jd_length,
              jd_weight:defaultData.jd_weight,
              jd_width:defaultData.jd_width,
              start_time:defaultData.start_time,
              end_time:defaultData.end_time,
            });
            let address={
              realname:defaultData.pick_up_name,
              mobile:defaultData.pick_up_tel,
              province:defaultData.pick_up_province_name,
              city:defaultData.pick_up_city_name,
              district:defaultData.pick_up_district_name,
              street:defaultData.pick_up_street_name,
              province_id:defaultData.pick_up_province,
              city_id:defaultData.pick_up_city,
              district_id:defaultData.pick_up_district,
              street_id:defaultData.pick_up_street,
              address:defaultData.pick_up_address
            };
            this.selectComponent(`.editAddress`).setFormData(address);
            this.getPickUpTime(address);
          }
          
        } else {
          app.tips(res.msg);
        }
      },
      fail: function (res) {},
    });
  },
  getPickUpTime(_data) {
    let _json = {
      pick_up_province: _data.province_id,
      pick_up_city: _data.city_id,
      pick_up_district: _data.district_id,
      pick_up_street: _data.street_id,
      pick_up_address: _data.address
    };

    let urlStr = app.getNetAddresss("plugin.jd-take-parts.frontend.refund.get-pickup-in-time");
    app._postNetWork({
      url: urlStr,
      data: _json,
      success:  (resdata)=> {
        var res = resdata.data;
        if (res.result == 1) {
          this.selectComponent(`.pickUpTime`).setListData(res.data.time_list);
        } else {
          app.tips(res.msg);
        }
      },
      fail: function (res) {},
    });
  },
  showInstructionsFn() {
    this.setData({
      showInstructions: true
    })
  },
  onCloseInstructions() {
    this.setData({
      showInstructions: false
    })
  },
  onChangeFreightPrice(event){
    this.setData({
      freight_price: event.detail
    })
  },
  onChangeOtherPrice(event){
    this.setData({
      other_price: event.detail
    })
  }
});
