/*******************************************************************************
 * 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('receivable'), chooseFlag: true, chooseTitle: mixins.$t('receivableSelect'), urlKey: 'selectBill' },
      { name: 'file' }],
    contentObj: {
      main: [
        {
          code: 'accDate',
          name: 'accDate',
          type: 'date',
          required: true,
        },
        {
          code: 'staffId',
          name: 'staffName',
          required: true,
          title: mixins.$t('payee'),
          type: 'choose',
          urlKey: 'chooseStaff'
        },
        {
          code: 'orgId',
          name: 'orgName',
          required: true,
          type: 'choose',
          urlKey: 'chooseOrg'
        },
        {
          code: 'sumAmtRec',
          type: 'number',
          title: mixins.$t('thisPayment'),
          required: true
        },

      ],
      bill: [
        { code: 'cancelAmount', type: 'cancel', title: mixins.$t('sumAmtReceivableHandle'), bill: 0, amount: 0 },
        { code: 'receivableResidue', type: 'number', title: mixins.$t('tobeverifiedAmount'), readonly: true, },
        { code: 'currentReceivableResidue', type: 'number', title: mixins.$t('curentVerifiedAmount'), required: true, readonly: true, },
        { code: 'sumWaiveAmt', type: 'number', title: mixins.$t('sumWaiveAmt'), readonly: true, },
        { code: 'receiptResidue', type: 'number', title: mixins.$t('paymentDeduction'), readonly: true, },
      ],
      file: [{
        code: 'remarks', type: 'textarea', title: mixins.$t('remarks')
      },
      { code: 'file', type: 'uploader', title: mixins.$t('uploader') }]
    },
    // 预存金额 预收金额
    amountArr: [
      { title: mixins.$t('receivableAmount'), code: 'receivableResidue' },
      { title: mixins.$t('advancePaymentAmount'), code: 'receiptResidue' }],
    // 三个汇总金额
    totalObj: {
      bill: [{ title: mixins.$t('collectAmount'), code: 'collectAmount' },
      { title: mixins.$t('totalWriteOffAmount'), code: 'totalWriteOffAmount' },
      { title: mixins.$t('toAdvancePaymentAmount'), code: 'toAdvancePaymentAmount' }]
    },
    // 弹出按钮
    buttonList: [{
      name: 'merge',
      title: mixins.$t('collection')
    }],
    contentList: [{
      code: 'need',
      title: mixins.$t('totalAmount'),
      type: 'str'
    }, {
      code: 'amount',
      content: 0,
      type: 'number'
    }],
    btnFormData: null,
    routeObjName: 'receiptPayment',
    accountService: app.globalData['accountService'],
    receivableResidue: 0,
    receiptResidue: 0,
    bill: 0,
    objInfo: {},
    table: Constants.tables.recPay,
  },
  /**
    * @desc : 页面加载数据方法
    * @date : 2024/2/1 15:49
    * @author : 姜永辉
    */
  loadInit() {
    console.log(this.data.item, this.data.formMode);
    if (this.data.formMode == Constants.formMode.edit) {
      wx.setNavigationBarTitle({
        title: mixins.$t('receiptOrderEdit'),
      })

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


  },

  /**
      * @desc   : 绑定数据-选择页面返回的逻辑处理
      * @author : 姜永辉
      * @date   : 2024年3月12日
      */
  chooseData(e) {
    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.receivableList = data.receivableList
      this.setData({
        receivableList: data.receivableList,
        objInfo: data.objInfo,
        receivableResidue: data.receivableResidue,
        receiptResidue: data.receiptResidue,
        bill: data.receivableList.length,
      })
      this.setForm(formData, contentObj, data.receivableResidue, data.receiptResidue, data.receivableList.length)
      return
    }
    this.setData({
      cardList: cardList_,
      formData: JSON.stringify(formData)
    })
  },

  /**
   * @desc : 选择客户后的回调
   * @date : 2024/2/1 15:49
   * @author : 姜永辉
   */
  chooseObjTypeData(e) {
    let _this = this
    console.log("chooseObjTypeData", e, this.data.formData);
    let formData = JSON.parse(this.data.formData)
    let contentObj = this.data.contentObj
    let objInfo = e.detail.data.objInfo
    let cusId = e.detail.data.cusId
    let params = {
      objectId: cusId,
    }
    // // 正常收款
    // params.amtResidueFlg = true
    // // 退收款
    // params.formType = 'refund'

    this.excute(this.data.accountService, this.data.accountService.getReceivableAccountItem, params).then(res => {
      if (res.data.data.length == 0) {
        formData.cancelAmount = false
      } else {
        formData.cancelAmount = true
      }
      formData.sumWaiveAmt = 0
      formData.sumAmtRec = 0.00
      formData.receivableList = res.data.data
      _this.setForm(formData, contentObj, objInfo.receivableResidue,
        objInfo.receiptResidue, res.data.data.length)
      _this.setData({
        objInfo,
        receivableList: res.data.data,
        receivableResidue: objInfo.receivableResidue,
        receiptResidue: objInfo.receiptResidue,
        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.receivableList == undefined || this.data.receivableList.length == 0) {
      formData.cancelAmount = false
      this.setData({
        formData: JSON.stringify(formData)
      })
      return
    }

    if (cancelAmount) {
      formData.receivableList = this.data.receivableList
      this.setForm(formData, contentObj, this.data.receivableResidue, this.data.receiptResidue, this.data.bill)
    } else {
      formData.receivableList = []
      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

    // 本次收款金额
    if (code == "sumAmtRec") {
      formData.sumAmtRec = data
      formData.collectAmount = data
      formData.sumAmount = data
      let contentList = this.data.contentList
      contentList.forEach(it => {
        if (it.type == 'number') {
          it.content = data
        }
      })
      this.setData({
        contentList,
      })
    }
    // 本次核销金额
    if (code == "currentReceivableResidue") {
      formData.currentReceivableResidue = data
      formData.totalWriteOffAmount = data
    }
    // 优惠金额
    if (code == "sumWaiveAmt") {
      formData.sumWaiveAmt = data
    }
    // 预存扣减金额 =   绝对值（本退款 +  优惠 ）- 绝对值（本次核销）和 预存金额 两者 的最小值
    let cAmount = Math.abs(Number(formData.sumAmtRec ? formData.sumAmtRec : 0))
      + Math.abs(Number(formData.sumWaiveAmt))
    if (Math.abs(cAmount - Number(formData.currentReceivableResidue)) > Math.abs(Number(this.data.receiptResidue))) {
      formData.receiptResidue = cAmount - Math.abs(Number(formData.currentReceivableResidue)) > 0 ? 0 : Math.abs(Number(this.data.receiptResidue))
    } else {

      formData.receiptResidue = cAmount - Math.abs(Number(formData.currentReceivableResidue)) < 0 ? Math.abs(Number(formData.currentReceivableResidue)) - cAmount : 0
    }
    // 本次收款 +  优惠 + 预收扣减 > 本次核销 == 转预收金额
    let toAdvancePaymentAmount = Number(formData.sumAmtRec) + Number(formData.sumWaiveAmt) + Number(formData.receiptResidue) - Number(formData.currentReceivableResidue)
    if (toAdvancePaymentAmount > 0) {
      formData.toAdvancePaymentAmount = toAdvancePaymentAmount
    } else {
      formData.toAdvancePaymentAmount = 0
    }
    this.setData({
      formData: JSON.stringify(formData)
    })

  },

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

      formData.receiptResidue = cAmount - Math.abs(Number(formData.currentReceivableResidue)) < 0 ? Math.abs(Number(formData.currentReceivableResidue)) - cAmount : 0
    }
    // 本次收款 +  优惠 + 预收扣减 > 本次核销 == 转预收金额
    let toAdvancePaymentAmount = Number(formData.sumAmtRec) + Number(formData.sumWaiveAmt) + Number(formData.receiptResidue) - Number(formData.currentReceivableResidue)
    if (toAdvancePaymentAmount > 0) {
      formData.toAdvancePaymentAmount = toAdvancePaymentAmount
    } else {
      formData.toAdvancePaymentAmount = 0
    }
    // 收款总额
    formData.collectAmount = formData.sumAmtRec
    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 = receivableResidue //总应收
      } else if (itcard.code === 'sumWaiveAmt'
        || itcard.code === 'currentReceivableResidue') {
        //优惠 本次核销是否只读
        itcard.readonly = Number(formData.currentReceivableResidue) == 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.currentReceivableResidue)
      > Number(formData.receivableResidue)) {
      msgError = '本次核销不能大于待核销金额'
    }
    let bill = 0
    let contentObj = this.data.contentObj
    contentObj['bill'].forEach(itcard => {
      if (itcard.code === 'cancelAmount') {
        //单数和金额
        bill  = itcard.bill  
      } 
    })
    if (Number(formData.currentReceivableResidue) == 0
      && Number(formData.sumAmtRec) == 0
      && Number(bill) == 0
      ) {
      msgError = '本次核销金额和本次收款不能同时为0'
    }
    // 预存+本次收款 + 优惠》= 本次核销
    if (Number(formData.sumAmtRec)
      + Number(formData.receiptResidue)
      + Number(formData.sumWaiveAmt)
      < Number(formData.currentReceivableResidue)) {
      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.sumAmtRec) != 0) {
      return params
    }
    //收付款类型-收款的查询参数
    params.rpType = Constants.rpType.receipt
    params.orgId = formData.orgId  //组织部门
    params.staffId = formData.staffId  // 员工
    //  // 供应商1 客户2 所有 传空
    params.objectId = this.data.objInfo.objectId  // 客户
    // 收款金额	- 本次收款				
    params.sumAmtRec = formData.sumAmtRec
    // 合计应收冲抵金额								
    params.sumAmtReceivableHandle = formData.currentReceivableResidue
    // 合计优惠金额
    params.sumWaiveAmt = formData.sumWaiveAmt
    // 预存的使用
    params.receiptResidue = formData.receiptResidue
    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.setReturnReceivableList(formData.receivableList || [], formData.sumWaiveAmt, formData.currentReceivableResidue, formData.receivableResidue)
    params.receivableList = rlsit //应收收款的明细 

    return params
  },

  /**
  * @desc : 将优惠和本次核销的金额分摊到应收单据的明细里
  * @date : 2024/2/1 15:49
  * @author : 姜永辉
  */
  setReturnReceivableList(list, sumWaiveAmt, currentReceivableResidue, totalAmount) {
    let retList = []
    if (sumWaiveAmt == null || sumWaiveAmt == undefined) {
      sumWaiveAmt = 0
    }
    if (currentReceivableResidue == null || currentReceivableResidue == null) {
      currentReceivableResidue = 0
    }
    if (currentReceivableResidue == 0 && sumWaiveAmt == 0 || list == null) {
      return retList
    }
    let finalAmout = currentReceivableResidue
    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,
        // 应收冲抵金额	
        amtReceivableHandle: 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)
    // 本次收款金额大于0 进入收款页面否则 直接保存
    if (formData.sumAmtRec == 0) {
      return this.excute(this.data.service, this.data.service.insertReceivableReceipt, 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: 1 })
      }
    })
  }

})