/*******************************************************************************
 * Copyright(c) 2022 dongke All rights reserved. / Confidential
 * 类的信息：
 *		1.程序名称：  新建付款单
 * 编辑履历：
 *		作者				日期					版本				修改内容
 *		姜永辉      2024-03-22    1.00		   	    
 *******************************************************************************/
const mixins = require('@/mixins/index.js')
const Constants = require('@/utils/Constants.js');
const util = require('@/utils/util.js')
const app = getApp();
Page({
  mixins: [mixins],
  /**
   * 页面的初始数据
   */
  data: {
    cardList: [
      { name: 'main' },
      { name: 'bill', title: mixins.$t('payment'), chooseFlag: true, chooseTitle: mixins.$t('paymentSelect'), urlKey: 'selectBill' },
      { name: 'file' }],
    contentObj: {
      main: [
        {
          code: 'accDate',
          name: 'accDate',
          type: 'date',
          required: true,
        },
        {
          code: 'staffId',
          name: 'staffName',
          required: true,
          title: mixins.$t('payer'),
          type: 'choose',
          urlKey: 'chooseStaff'
        },
        {
          code: 'orgId',
          name: 'orgName',
          required: true,
          type: 'choose',
          urlKey: 'chooseOrg'
        },
        {
          code: 'sumAmtPay',
          type: 'number',
          title: mixins.$t('thisPaymentgo'),
          required: true
        },

      ],
      bill: [
        { code: 'cancelAmount', type: 'cancel', title: mixins.$t('sumAmtPayableHandle'), bill: 0, amount: 0 },
        { code: 'payableResidue', type: 'number', title: mixins.$t('tobeverifiedAmount'), readonly: true, },
        { code: 'currentPayableResidue', type: 'number', title: mixins.$t('curentVerifiedAmount'), required: true },
        { code: 'sumWaiveAmt', type: 'number', title: mixins.$t('sumWaiveAmt'), },
        { code: 'paymentResidue', type: 'number', title: mixins.$t('prepaidDeduction'), readonly: true, },

      ],
      file: [{
        code: 'remarks', type: 'textarea', title: mixins.$t('remarks')
      },
      { code: 'file', type: 'uploader', title: mixins.$t('uploader') }]
    },
    //应付金额 预付金额 
    amountArr: [
      { title: mixins.$t('payAmount'), code: 'payableResidue' },
      { title: mixins.$t('advancePrepaidAmount'), code: 'paymentResidue' }],
    // 三个汇总金额
    totalObj: {
      bill: [{ title: mixins.$t('paymentAmount'), code: 'paymentAmount' },
      { title: mixins.$t('totalWriteOffAmount'), code: 'totalWriteOffAmount' },
      { title: mixins.$t('toAdvancePrepaidAmount'), code: 'toAdvancePrepaidAmount' }]
    },
    // 弹出按钮
    buttonList: [{
      name: 'merge',
      title: mixins.$t('payment')
    }],
    contentList: [{
      code: 'need',
      title: mixins.$t('totalAmount'),
      type: 'str'
    }, {
      code: 'amount',
      content: 0,
      type: 'number'
    }],
    btnFormData: null,
    routeObjName: 'payment',
    accountService: app.globalData['accountService'],
    payableResidue: 0,
    paymentResidue: 0,
    bill: 0,
    objInfo: {},
    table: Constants.tables.recPay,
  },

  /**
    * @desc : 页面加载数据方法
    * @date : 2024/2/1 15:49
    * @author : 姜永辉
    */
  loadInit() {
    if (this.data.formMode == Constants.formMode.edit) {
      wx.setNavigationBarTitle({
        title: mixins.$t('paymentOrderEdit'),
      })

    } else {
      wx.setNavigationBarTitle({
        title: mixins.$t('paymentOrderAdd'),
      })
      // 新增
      if (this.data.formData != undefined) {
        this.setData({
          formData: JSON.stringify({ accDate: new Date().toDateStr() })
        })
      }
    }


  },

  /**
      * @desc   : 绑定数据-选择页面返回的逻辑处理
      * @author : 姜永辉
      * @date   : 2024年3月12日
      */
  chooseData(e) {
    console.log("chooseData", e, this.data.formData);
    let formData = JSON.parse(this.data.formData)
    let cardList_ = this.data.cardList
    let contentObj = this.data.contentObj
    let code = e.detail.code
    let data = e.detail.data.data
    if (code == "supId") { //供应商
      formData.supId = data.id
      formData.supName = data.name
    }
    if (code == "staffId") { //员工
      formData.staffId = data.id
      formData.staffName = data.name
    }
    if (code == "orgId") { //部门
      formData.orgId = data.id
      formData.orgName = data.name
    }
    if (code == "bill") { //选取应付的返回值     
      formData.payableList = data.payableList
      _this.setData({
        payableList: data.payableList,
        objInfo: data.objInfo,
        payableResidue: data.payableResidue,
        paymentResidue: data.paymentResidue,
        bill: data.payableList.length,
      })
      this.setForm(formData, contentObj, data.payableResidue, data.paymentResidue, data.payableList.length)
      return
    }
    this.setData({
      cardList: cardList_,
      formData: JSON.stringify(formData)
    })
  },

  /**
   * @desc : 选择供应商后的回调
   * @date : 2024/2/1 15:49
   * @author : 姜永辉
   */
  chooseObjTypeData(e) {
    let _this = this

    let formData = JSON.parse(this.data.formData)
    let contentObj = this.data.contentObj
    let objInfo = e.detail.data.objInfo
    let supId = e.detail.data.supId
    console.log("chooseObjTypeData", e, this.data.formData);
    let params = {
      objectId: supId,
    }
    this.excute(this.data.accountService, this.data.accountService.getPayableAccountItem, params).then(res => {
      if (res.data.data.length == 0) {
        formData.cancelAmount = false
      } else {
        formData.cancelAmount = true
      }
      formData.sumWaiveAmt = 0
      formData.sumAmtPay = 0.00
      formData.payableList = res.data.data
      _this.setForm(formData, contentObj, objInfo.payableResidue,
        objInfo.paymentResidue, res.data.data.length)
      _this.setData({
        payableList: res.data.data,
        objInfo,
        payableResidue: objInfo.payableResidue,
        paymentResidue: objInfo.paymentResidue,
        bill: res.data.data.length
      })

    })
  },

  /**
 * @desc : 设置表单的数据
 * @date : 2024/2/1 15:49
 * @author : 姜永辉
 */
  onCheckChange(e) {
    let cancelAmount = e.detail.data.cancelAmount
    let formData = JSON.parse(this.data.formData)
    let contentObj = this.data.contentObj
    // 应收为0
    if (this.data.payableList == undefined || this.data.payableList.length == 0) {
      formData.cancelAmount = false
      this.setData({
        formData: JSON.stringify(formData)
      })
      return
    }
    if (cancelAmount) {
      formData.payableList = this.data.payableList
      this.setForm(formData, contentObj, this.data.payableResidue, this.data.paymentResidue, this.data.bill)
    } else {
      formData.payableList = []
      this.setForm(formData, contentObj, 0, 0, 0)
    }
  },

  /**
 * @desc : 设置表单的数据
 * @date : 2024/2/1 15:49
 * @author : 姜永辉
 */
  changeNumber(e) {
    let formData = JSON.parse(this.data.formData)
    let code = e.detail.code
    let data = e.detail.data
    console.log("changeNumber",code,data,formData);
    // 本次付款金额
    if (code == "sumAmtPay") {
      formData.sumAmtPay = data
      formData.paymentAmount = data
      formData.sumAmount = data
      let contentList = this.data.contentList
      contentList.forEach(it => {
        if (it.type == 'number') {
          it.content = data
        }
      })
      this.setData({
        contentList,
      })
    }
    // 本次核销金额
    if (code == "currentPayableResidue") {
      formData.currentPayableResidue = data
      formData.totalWriteOffAmount = data
    }
    // 优惠金额
    if (code == "sumWaiveAmt") {
      formData.sumWaiveAmt = data
    }
    // 预付扣减 
     // 预付扣减 =   绝对值（本退款 +  优惠 ）- 绝对值（本次核销）和 预付金额 两者 的最小值
     let cAmount = Math.abs(Number(formData.sumAmtPay ? formData.sumAmtPay : 0))
     + Math.abs(Number(formData.sumWaiveAmt))
   if (Math.abs(cAmount - Number(formData.currentPayableResidue)) > Math.abs(Number(this.data.paymentResidue))) {
     formData.paymentResidue = cAmount - Math.abs(Number(formData.currentPayableResidue)) > 0 ? 0 : Math.abs(Number(this.data.paymentResidue))
   } else {

     formData.paymentResidue = cAmount - Math.abs(Number(formData.currentPayableResidue)) < 0 ? cAmount - Math.abs(Number(formData.currentPayableResidue))   : 0
   }
    // 本次付款 +  优惠 + 预付扣减 > 本次核销 == 转预付金额
    let toAdvancePrepaidAmount = Number(formData.sumAmtPay) + Number(formData.sumWaiveAmt) + Number(formData.paymentResidue) - Number(formData.currentPayableResidue)
    if (toAdvancePrepaidAmount > 0) {
      formData.toAdvancePrepaidAmount = toAdvancePrepaidAmount
    } else {
      formData.toAdvancePrepaidAmount = 0
    }
    this.setData({
      formData: JSON.stringify(formData)
    })
  },

  /**
   * @desc : 设置表单的数据
   * @date : 2024/2/1 15:49
   * @author : 姜永辉
   */
  setForm(formData, contentObj, payableResidue, paymentResidue, bill) {
    console.log("app.globalData.user", app.globalData.user);
    if (payableResidue == null) {
      payableResidue = 0
    }
    if (paymentResidue == null) {
      paymentResidue = 0
    }
    if (bill == null) {
      bill = 0
    }
    formData.payableResidue = payableResidue  // 待核销金额
    formData.currentPayableResidue = payableResidue  // 本次核销金额
    formData.totalWriteOffAmount = payableResidue  // 核销总额
 
    // 预存扣减金额 =   绝对值（本退款 +  优惠 ）- 绝对值（本次核销）和 预存金额 两者 的最小值
    let cAmount = Math.abs(Number(formData.sumAmtPay ? formData.sumAmtPay : 0))
      + Math.abs(Number(formData.sumWaiveAmt))
    if (Math.abs(cAmount - Number(formData.currentPayableResidue)) > Math.abs(Number(paymentResidue))) {
      formData.paymentResidue = cAmount - Math.abs(Number(formData.currentPayableResidue)) > 0 ? 0 : Math.abs(Number(paymentResidue))
    } else {

      formData.paymentResidue = cAmount - Math.abs(Number(formData.currentPayableResidue)) < 0 ? Math.abs(Number(formData.currentPayableResidue)) - cAmount : 0
    }
    // 本次收款 +  优惠 + 预收扣减 > 本次核销 == 转预收金额
    let toAdvancePrepaidAmount = Number(formData.sumAmtPay) + Number(formData.sumWaiveAmt) + Number(formData.paymentResidue) - Number(formData.currentPayableResidue)
    if (toAdvancePrepaidAmount > 0) {
      formData.toAdvancePrepaidAmount = toAdvancePrepaidAmount
    } else {
      formData.toAdvancePrepaidAmount = 0
    }
    if (formData.staffId == null) {
      formData.staffId = app.globalData.user.staffId
      formData.orgId = app.globalData.user.orgId
      formData.staffName = app.globalData.user.staffName
      formData.orgName = app.globalData.user.orgName
    }

    contentObj['bill'].forEach(itcard => {
      if (itcard.code === 'cancelAmount') {
        //单数和金额
        itcard.bill = bill
        itcard.amount = payableResidue //总应付
      } else if (itcard.code === 'sumWaiveAmt'
      || itcard.code === 'currentPayableResidue') {
      //优惠 本次核销是否只读
      itcard.readonly = Number(formData.currentPayableResidue) == 0 ? true : false
    }
    })
    this.setData({
      contentObj,
      formData: JSON.stringify(formData)
    })
  },

  /**
     * @desc : 保存数据服务--校验
     * @date : 2024/2/1 15:49
     * @author : 姜永辉
     */
  validData() {
    let msgError = null
    let formData = JSON.parse(this.data.formData)
    // 本次核销不能大于待核销金额
    if (Number(formData.currentPayableResidue)
      > Number(formData.payableResidue)) {
      msgError = '本次核销不能大于待核销金额'
    }
    let bill = 0
    let contentObj = this.data.contentObj
    contentObj['bill'].forEach(itcard => {
      if (itcard.code === 'cancelAmount') {
        //单数和金额
        bill  = itcard.bill  
      } 
    })
    if (Number(formData.currentPayableResidue) == 0
      && Number(formData.sumAmtPay) == 0
      && Number(bill) == 0
      ) {
      msgError = '本次核销金额和本次付款不能同时为0'
    }

    // 预存+本次收款 + 优惠》= 本次核销
    if (Number(formData.sumAmtPay)
      + Number(formData.paymentResidue)
      + Number(formData.sumWaiveAmt)
      < Number(formData.currentPayableResidue)) {
      msgError = '本次核销金额不能大于付款和预付金额之和'
    }

    if (msgError != null) {
      util.showToast(msgError);
      return false
    }

    return true
  },



  /**
   * @desc : 保存的參數設置
   * @date : 2024/2/1 15:49
   * @author : 姜永辉
   */
  setParams(params) {
    let formData = JSON.parse(this.data.formData)
    if (Number(formData.sumAmtPay) != 0) {
      return params
    }
    //收付款类型-收款的查询参数
    params.rpType = Constants.rpType.payment
    params.orgId = formData.orgId  //组织部门
    params.staffId = formData.staffId  // 员工
    //  // 供应商1 客户2 所有 传空
    params.objectId = this.data.objInfo.supId  // 经销商
    // 收款金额					
    params.sumAmtPay = formData.sumAmtPay
    // 合计应付冲抵金额								
    params.sumAmtPayableHandle = formData.currentPayableResidue
    // 合计优惠金额
    params.sumWaiveAmt = formData.sumWaiveAmt
    // 预存的使用
    params.paymentResidue = formData.paymentResidue
    params.annexPaths = formData.annexPaths || [] //附件 
    // params.biznisType = null
    // params.biznisId	 = null
    // params.biznisNo	= null	 
    params.accDate = formData.accDate  // 
    params.remarks = formData.remarks  // 备注
    params.makeStaff = app.globalData.user.staffId  // 制单人

    params.itemList = [] //明细 
    let rlsit = this.setReturnPayableList(formData.payableList || [], formData.sumWaiveAmt, formData.currentPayableResidue, formData.payableResidue)
    params.payableList = rlsit //应付款的明细 
    return params
  },

  /**
 * @desc : 将优惠和本次核销的金额分摊到应付单据的明细里
 * @date : 2024/2/1 15:49
 * @author : 姜永辉
 */
  setReturnPayableList(list, sumWaiveAmt, currentPayableResidue, totalAmount) {
    let retList = []
    if (sumWaiveAmt == null || sumWaiveAmt == undefined) {
      sumWaiveAmt = 0
    }
    if (currentPayableResidue == null || currentPayableResidue == null) {
      currentPayableResidue = 0
    }
    if (currentPayableResidue == 0 && sumWaiveAmt == 0 || list == null) {
      return retList
    }
    let finalAmout = currentPayableResidue
    let finalSumWaiveAmt = sumWaiveAmt
    for (let index = 0; index < list.length; index++) {
      const element = list[index];
      // 应付冲抵金额	== 明细的剩余金额	默认
      let amtReceivableHandle = (finalAmout < element.amtResidue ? finalAmout : element.amtResidue)
      let amtWaive = Number(parseFloat(element.amtResidue / totalAmount * sumWaiveAmt).toFixed(2))
      finalAmout -= amtReceivableHandle
      finalSumWaiveAmt -= amtWaive

      retList.push({
        accDate: list.accDate,
        accItemId: element.accItemId,
        // 应付冲抵金额	
        amtPayableHandle: amtReceivableHandle,
        // 优惠金额-分摊之后 最后一条的数据取剩余的值
        amtWaive: (index == list.length - 1 ? finalSumWaiveAmt : amtWaive),
      })
    }

    return retList

  },

    /**
  * @desc :处理保存后续
  * @date : 2024/2/1 15:49
  * @author : 姜永辉
  */
 handleData() {
  this.setData({
    formData: JSON.stringify({ accDate: new Date().toDateStr() })
  })
},

  /**
  * @desc : 保存数据服务
  * @date : 2024/2/1 15:49
  * @author : 姜永辉
  */
  saveData() {
    let formData = JSON.parse(this.data.formData)
    if (formData.sumAmtPay == 0) {
      return this.excute(this.data.service, this.data.service.insertPayableReceipt, this.data.params)
    } else {
      this.open()
    }

  },


  /**
  * @desc : 保存数据服务-跳转收款页面
  * @date : 2024/2/1 15:49
  * @author : 姜永辉
  */
  open(e) {
    let _this = this
    wx.navigateTo({
      url: '/package-base-select/pages/select-collection_confirm/select-collection_confirm',
      events: {
        // 回调后
        bindData: function (data) {
          // 保存成功后 回调
          wx.navigateBack({
            data: 1
          })
        }
      },
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据 
        res.eventChannel.emit('params', { item: _this.data.formData, formType: 2 })
      }
    })
  }

})