/*******************************************************************************
 * Copyright(c) 2022 dongke All rights reserved. / Confidential
 * 类的信息：
 *		1.程序名称：
 *		2.功能描述：销售退货
 * 编辑履历：
 *		作者			  日期					版本				修改内容
 *		王英杰		     2022-5-25		        1.00		   	    新建
 *******************************************************************************/
const app = getApp();
const api = require('../../../../utils/api.js');
const Constants = require('../../../../utils/Constants.js');
const util = require('../../../../utils/util.js')
const common = require('../../../../utils/common.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeNames: [
      "1",
      "2"
    ],
    flgAutoIvt: true,
    
        form: {
          addressArea: {
            city: "沈阳市",
            district: "和平区",
            province: "辽宁省"
          },
          addressFull: "辽宁省沈阳市和平区汤玉麟公馆旧址11111",
          addressGcj02: {
            latitude: 41.79179,
            longitude: 123.421643
          },
          addressName: "汤玉麟公馆旧址",
          addressNo: "11111",
          ageComposition: null,
          ageCompositionName: null,
          apvResult: "审-通过",
          apvResultName: "通过",
          apvSubmitId: null,
          apvUserIds: [],
          ascpId: 29195,
          bankAccount: null,
          bankDeposit: null,
          canReturnAmount: 2997,
          categoryQuantity: 1,
          channelName: null,
          contactName: "",
          deliveryPhone: "",
          contractNo: "2312313333",
          cpId: 20760,
          crmOrderNo: null,
          customerCode: "45454454444-10030R",
          customerFrom: -1,
          customerFromName: null,
          customerId: 3915,
          customerName: "12.21.01",
          customerPhone: "45454454444",
          customerType: null,
          customerTypeName: null,
          decisionMaker: null,
          decisionMakerName: null,
          deliveryTime: "2024-01-16 08:00:00",
          deliveryTypeName: null,
          designRemarks: null,
          designStatus: "设计状态-无需",
          designStatusName: "不需要设计",
          designUser: null,
          designUserName: null,
          discountPromotion: -100,
          discountStandard: -11.24,
          displayStatus: "出库完成",
          docCode: "销售订单",
          earnestAmount: null,
          editTime: "2024-01-15 17:00:34",
          entryStatus: "入库状态-未入",
          entryTime: null,
          erpOrgCode: "",
          erpPushResult: null,
          erpPushStatus: 2,
          estateId: null,
          estateName: null,
          finalReceiptAmount: 0,
          fitupStyle: null,
          fitupStyleName: null,
          fitupType: null,
          fitupTypeName: null,
          flgValid: true,
          houseType: null,
          houseTypeName: null,
          kujialeDesignId: null,
          kujialeNo: null,
          kujialePricePaths: null,
          linkPsiSystem: "DK-IBOSS",
          mReasonForReturn: "",
          mRefundAccountNumber: "",
          makingTime: "2024-01-15 17:00:34",
          makingTimeConvert: "2024-01-15 17:00:34",
          makingUser: 1005,
          makingUserName: "无库无ERP00001",
          merOrderType: 0,
          merOrderTypeName: "非跟单",
          needReceivable: 0,
          orderId: 11767,
          orderItemVOList: null,
          orderNo: "SA-QZHJ-BFJ-202401150RYC",
          orderStatus: "订单状态-通过",
          orderStatusName: "成交",
          orderType: 2,
          orgCode: "GXBH1002",
          orgId: 32402,
          orgList: null,
          orgName: "北海富安居店",
          outStatus: "出库状态-完成",
          outStatusName: "出库完成",
          receiptStatus: "收款状态-未收",
          receiptStatusName: "未收款",
          receivable: 0,
          rejectStatusString: null,
          remarks: null,
          sale1Id: 20760,
          sale2Id: 29195,
          sale2OpeMode: "分销模式-代送",
          salesChannel: 1,
          salesChannelName: "零售",
          sorderId: null,
          sorderNo: null,
          staffCode: "12222222222@QZHJ",
          staffId: 1005,
          staffList: null,
          staffName: "无库无ERP00001",
          storeCode: "GXBH1002",
          storeId: 4421,
          storeName: "北海富安居店",
          storeType: null,
          storeTypeName: "直营门店",
          sumAmount: 2997,
          sumCollectedAmount: 0,
          sumEndAmount: 0,
          sumFeeAmount: 0,
          sumGoodsAmount: -2997,
          sumOutAmount: 2997,
          sumPromotion: -2997,
          sumQuantity: 3,
          sumReceiptAmount: 0,
          sumRejectAmount: -2997,
          sumRejectAmount_order: 0,
          sumRejectFeeAmount: 0,
          sumRejectGoodsAmount: -2997,
          sumRejectQuantity: -3,
          sumStandard: -26664,
          sumUsePrestore: 0,
          sumVolume: -0.15,
          sumWeight: 0,
          supplierCode: null,
          supplierId: null,
          supplierName: null,
          tdiscountPromotion: 100,
          tdiscountStandard: 11.24,
          toiletCount: null,
          toiletCountName: null,
          tsumAmount: 2997,
          tsumGoodsAmount: 2997,
          tsumPromotion: 2997,
          tsumQuantity: 3,
          tsumStandard: 26664
        }
      ,
    goodsList:[
        {
        activityId: 84,
        activityName: "零售活动方案",
        canReturnQuantity: 3,
        discountPromotion: 100,
        discountStandard: 11.24,
        erpOutItemId: 1435661,
        erpOutNo: "ZJSA72924011500006",
        flgDesign: false,
        flgGift: false,
        hasChild: 0,
        iconThumPath: "haip/2023-04-21/19ae78a2639547d9aa961b58d20dbdbd.png",
        id: "5d8d66b7-5e2c-4e63-b396-3786cef7d85d",
        itemId: 35537,
        itemIndex: 1,
        nonStandardArea: 1,
        nonStandardCode: "-",
        orderAmount: 2997,
        orderId: 11767,
        orderItemId: 35537,
        orderItemQuantity: 1,
        orderNo: "SA-QZHJ-BFJ-202401150RYC",
        orderPriceSale: 999,
        orderQuantity: 3,
        outId: 3382,
        outItemId: 6164,
        outNo: "WO-QZHJ-000-202401150RYD",
        outOutAmount: 2997,
        outOutQuantity: 3,
        outRejectAmount: 0,
        outRejectQuantity: 0,
        outStatus: 3,
        pathType: 2,
        pricePromotion: 999,
        priceSale: 999,
        priceStandard: 8888,
        promotionId: 211,
        promotionItemId: 22944,
        promotionName: "1",
        promotionPriceType: 77,
        promotionType: 1,
        promotionTypeName: "单品促销",
        radio: "1",
        refCostAmt: 9234,
        refCostPrice: 3078,
        rejectAmount: -2997,
        rejectPrice: 999,
        rejectQuantity: -3,
        rejectQuantityTemp: -3,
        skuCode: "EE920A00200B01",
        skuId: 9537580,
        skuModel: "EE920A00200B01",
        skuName: "【已淘汰】智能盖板HE920",
        skuType: 0,
        skuTypeName: "",
        skuVolume: 0.05,
        skuWeight: 0,
        spuCode: "HE920",
        spuId: 65410,
        standardId: 308,
        tItemAmount: 2997,
        tItemQuantity: 3,
        unitName: "PCS",
        whId: 552
        }
        ],
    item: {
      remarks: ""
    },
    remarks: "",
    saleLinkPsiSystem: true, 
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {  },
  /**
   * 退货原因输入事件监听
   *
   */
  onmReasonForReturnChange(event) {
    let form = this.data.form
    form.mReasonForReturn = event.detail
    this.setData({
      form
    })

  },

  /**
   * 退款账号
   * @param {*} event 
   */
  onmRefundAccountNumberChange(event) {

    let form = this.data.form
    form.mRefundAccountNumber = event.detail
    this.setData({
      form
    })
  },

  /**
   * @desc : 打开编辑商品备注事件
   * @author : 周兴
   * @date : 2022/6/30 12:16
   */
  openRemark(e) {
    this.setData({
      remarksIndex: e.currentTarget.dataset.index,
      remarkFlag: true
    })
  },


  /**
   * 每个商品 步进器监听事件
   */
  onChangeStepper(e) {
    let goodsList = this.data.goodsList
    let index = e.currentTarget.dataset.index

    goodsList[index].rejectQuantity = e.detail
    if (goodsList[index].nonStandardArea) {
      let num = util.accMul(goodsList[index].rejectPrice, e.detail)
      goodsList[index].rejectAmount = Number(num * goodsList[index].nonStandardArea)    //金额 = 本次退货价格*数量* 面积
    } else {
      goodsList[index].rejectAmount =
        util.accMul(goodsList[index].rejectPrice, e.detail) //金额 = 本次退货价格*数量
    }

    this.setData({
      goodsList
    })
    this.getTotalAmount();
  },

  /**
   * @desc : 金额计算
   * @author : 于继渤
   * @date : 2022/5/30 12:16
   */
  getTotalAmount() {
    let goodsList = this.data.goodsList
    let form = this.data.form
    let itemAmount = 0 // 货物总额
    let weight = 0 // 总重量
    let volumn = 0 // 总体积
    let sumStandard = 0 // 标价总额
    let sumPromotion = 0 // 标准价总额
    let sumRejectQuantity = 0 //退货数量
    let sumRejectAmount = 0 //退货金额
    let sumRejectGoodsAmount = 0 //退货金额
    goodsList.forEach(row => {
      if (row.rejectAmount) {
        // 金额
        itemAmount = util.AddNumber(row.rejectAmount, itemAmount);
      }
      // 重量
      if (row.skuWeight && row.rejectQuantity) {
        weight += util.accMul(row.rejectQuantity, row.skuWeight);
      }
      // 体积
      if (row.skuVolume && row.rejectQuantity) {
        volumn += util.accMul(row.rejectQuantity, row.skuVolume);
      }
      // 标价
      if (row.priceStandard && row.rejectQuantity) {
        sumStandard += util.accMul(row.rejectQuantity, row.priceStandard);
      }
      // 标准价
      if (row.pricePromotion && row.rejectQuantity) {
        sumPromotion += util.accMul(row.rejectQuantity, row.pricePromotion);
      }
      // 退货金额
      if (row.rejectAmount) {
        sumRejectGoodsAmount = util.AddNumber(row.rejectAmount, sumRejectGoodsAmount);
      }
      // 退货数量
      if (row.rejectQuantity) {
        sumRejectQuantity = util.AddNumber(row.rejectQuantity, sumRejectQuantity);
      }
    })

    form.sumWeight = Number(weight.toFixed(6));
    form.sumVolume = Number(volumn.toFixed(6));
    form.sumStandard = sumStandard
    form.sumPromotion = sumPromotion
    form.sumRejectAmount = itemAmount + Number(form.sumRejectFeeAmount)
    form.sumRejectQuantity = sumRejectQuantity
    form.sumRejectGoodsAmount = sumRejectGoodsAmount
    form.sumGoodsAmount = itemAmount
    // 计算合计金额
    // 退货后金额=退货前金额+费用金额
    //订单_t_sum_amount + 订单_sum_reject_amount+ 本单_sum_reject_amount
    let numEnd = util.AddNumber(Number(form.tsumAmount), Number(form.sumRejectAmount_order))
    form.sumEndAmount = util.AddNumber(Number(numEnd), Number(form.sumRejectAmount))
    // 剩余应收=退货后金额-实收金额  
    form.receivable = Number(util.SubNumber(Number(form.sumEndAmount), Number(form.sumCollectedAmount)))
    // 需收款金额 = 退货后金额- 实收金额
    form.needReceivable = Number(util.SubNumber(Number(form.sumEndAmount), Number(form.sumCollectedAmount)))

    // 标价折扣
    form.discountStandard = sumStandard === 0 ? 100 : Number((form.sumAmount * 100 / sumStandard).toFixed(2));
    // 标准价折扣
    form.discountPromotion = sumPromotion === 0 ? 100 : Number((form.sumAmount * 100 / sumPromotion).toFixed(2));

    this.setData({
      goodsList: goodsList,
      form: form
    })
  },




  /**
   * @desc : 手风琴展开事件
   * @author : 于继渤
   * @date : 2022/5/26 12:16
   */
  onChange(event) {
    this.setData({
      activeNames: event.detail,
    });
  },
  /**
   * 收款成交 点击事件
   */
  allClean() {
    let result = this.checkForm();
    if (!result.flag) {
      wx.showToast({
        title: result.msg,
        image: '/static/image/warning.png',
        duration: 1000
      })
      return
    }
    let form = this.deleteParam(this.data.form)
    form.rejectType = 1
    form.orderOutRejectItemVOList = this.data.goodsList
    form.editTimeTemp = form.editTime
    form.makingUserPur = app.globalData.user.sale2StaffId //报备人
    delete form['erpPushResult']
    delete form['erpPushStatus']
    // form.erpPushStatus = Constants.ERP_PUSH_STATUS.NO_PUSH_STATUS
  
    
    wx.navigateTo({
      url: '../customer-collection/customer-collection-confirm?type=3&item=' + JSON.stringify(form) + '&orgId=' + form.orgId,
    })
  },
  /**
   * @desc : 编辑商品关闭编辑备注事件
   * @author : 于继渤
   * @date : 2022/5/26 12:16
   */
  closeChoosedItemInfo_remark() {
    this.setData({
      remarkFlag: false
    })
  },
  /**
   * @desc : 备注弹窗编辑事件
   * @author : 于继渤
   * @date : 2022/6/01 12:16
   */
  changeRemarksField(e) {
    let item = this.data.item
    item.remarks = e.detail
    this.setData({
      item
    })
  },
  /**
   * @desc : 编辑商品关闭确定编辑备注事件
   * @author : 于继渤
   * @date : 2022/5/26 12:16
   */
  updateToChooseList_remark(e) {
    let goodsList = this.data.goodsList
    goodsList[this.data.remarksIndex].remarks = this.data.item.remarks
    this.setData({
      goodsList: goodsList,
      remarkFlag: false
    })
  },
  /* 表单校验 */
  checkForm() {

    if (!this.data.form.mReasonForReturn) {
      return {
        flag: false,
        msg: '请输入退货原因'
      };
    }

    return {
      flag: true,
      msg: '表单校验通过'
    }
  },
  deal(){
    wx.navigateTo({
        url: '../../order-billing/collection-confirm/collection-confirm' 
      })

  },
  /**
   * @desc : 未收款成交保存 
   * @author : 王英杰
   * @date : 2022/5/23 15:16
   */
  submit(e) {
    let result = this.checkForm();
    if (!result.flag) {
      wx.showToast({
        title: result.msg,
        image: '/static/image/warning.png',
        duration: 1000
      })
      return
    }

    this.setData({
      loading: true,
      loadingButtonFlag: true
    })
    let param = this.deleteParam(this.data.form)
    try {
      delete param['erpPushResult']
      param.rejectType = 1
      param.orderOutRejectItemVOList = this.data.goodsList
      param.cpId = app.globalData.user.cpId
      param.rejectReason = this.data.form.mReasonForReturn //退货原因
      param.refundAccount = this.data.form.mRefundAccountNumber //退款账号
      param.rejectReasonType = this.data.form.rejectReasonType ? this.data.form.rejectReasonType : null
      param.receiptVOList = []
      param.receiptStatus = '收款状态-未收'
      param.staffList = []
      param.orgList = []
      param.sumCollectedAmount = 0
      param.sumAmount = this.data.form.sumEndAmount //退货后总额
      param.sumReceiptAmount = 0 //退货后总额
      param.docCode = '销售退货'
      param.userId =app.globalData.user.userId
      param.userCode = app.globalData.user.userCode
      param.flgAutoIvt = this.data.flgAutoIvt  //自动出库办理标识
      if (this.data.flgAutoIvt) {
        param.outTime = util.formatDataTime(new Date())
      }else {
        param.outTime = null
      }
    //   param.erpPushStatus = Constants.ERP_PUSH_STATUS.NO_PUSH_STATUS
    delete param['erpPushStatus']
    param.makingUserPur = app.globalData.user.sale2StaffId //报备人
    } catch (e) {

    } 

    api.request(Constants.ORDER_OUT_REJECT_PC_API + 'insert', 'POST', param).then(res => {
      this.setData({
        loading: false
      })
      if (res.data.code === 200) {
        wx.showToast({
          title: '保存成功',
          image: '/static/image/success.png',
          duration: 1000
        })
        var pages = getCurrentPages();
        var prevPage = pages[pages.length - 3];

        prevPage.setData({
          orderAddFlag: true
        })
        setTimeout(function () {

          wx.navigateBack({
            delta: 2
          })

        }, 1500)
      }else{
        this.setData({
          loadingButtonFlag:false
        })
      }
    })
  },

  deleteParam(param) {
    delete param['tdiscountPromotion']
    delete param['tdiscountStandard']
    delete param['toiletCount']
    delete param['toiletCountName']
    delete param['tsumAmount']
    delete param['tsumGoodsAmount']
    delete param['tsumPromotion']
    delete param['tsumQuantity']
    delete param['tsumStandard']
    delete param['merOrderType']
    delete param['merOrderTypeName']
    delete param['sumOutAmount']

    delete param['apvSubmitId']
    delete param['apvUserIds']

    return param
  },















  sumFeeAmountBindinputBlur(e) {
 
    this.getTotalAmount();
  },
  /**
   * 服务价格 变化监听
   * @param {*} e 
   */
  sumFeeAmountBindinput(e) {

    let form = this.data.form
    form.sumRejectFeeAmount = e.detail.value;
    this.setData({
      form: form
    })
  },
  /**
   * 单个商品金额 变化监听
   * @param {*} e 
   */
  rejectAmountInput(e) {
  
    let index = e.currentTarget.dataset.index
    let goodsList = this.data.goodsList
    goodsList[index].rejectAmount = e.detail.value > 0 ? -1 * e.detail.value : e.detail.value;


    if (goodsList[index].nonStandardArea) {
      let num = util.except(goodsList[index].rejectAmount, goodsList[index].rejectQuantity)
      goodsList[index].rejectPrice = Number(num / goodsList[index].nonStandardArea)  //单价 = 金额/数量 / 面积
    }
    goodsList[index].rejectPrice =
      util.except(goodsList[index].rejectAmount, goodsList[index].rejectQuantity) //单价 = 金额/数量 
    this.setData({
      goodsList
    })
  },
  /**
 * 销售单价（本次退货价格）(单品)  变化监听
 * @param {*} e 
 */
  orderPriceSaleInput(e) {

    let index = e.currentTarget.dataset.index
    let goodsList = this.data.goodsList
    goodsList[index].rejectPrice = e.detail.value;

    if (goodsList[index].nonStandardArea) {
      let num = util.accMul(e.detail.value, goodsList[index].rejectQuantity)
      goodsList[index].rejectAmount = Number(num * goodsList[index].nonStandardArea)
    } else {
      goodsList[index].rejectAmount =
        util.accMul(e.detail.value, goodsList[index].rejectQuantity) //金额 = 单价*数量
    }

    this.setData({
      goodsList
    })
  },

  openRejectReasonType() {
    this.setData({
      rejectReasonTypeFlag: true
    })
  },

  mutiSearch(e) {
    let form = this.data.form
    form.rejectReasonType = e.detail.id
    form.rejectReasonTypeName = e.detail.name
    this.setData({
      form: form
    })
  },

      //自动出库办理
      onChangeAOP() {
        if (!this.data.saleLinkPsiSystem) {
            return
        }
        //有ERP 不让更改
        //有ERP 不让显示
        this.setData({
            flgAutoIvt: !this.data.flgAutoIvt
        })
    },
})