/*******************************************************************************
 * Copyright(c) 2021 dongke All rights reserved. / Confidential
 * 类的信息：
 *		1.程序名称：
 *		2.功能描述：客户收款确认
 * 编辑履历：
 *		作者				日期					版本				修改内容
 *		jyh		     2022-5-25		        1.00		   	    新建
 *******************************************************************************/
const app = getApp()
const Constants = require('@/utils/Constants');
const mixins = require('@/mixins/index.js')
const utils = require('@/utils/util')

mixins: [mixins],
  Page({
    mixins: [mixins],
    /**
     * 页面的初始数据
     */
    data: {
      annexPaths: [],
      dealFalg: "true",
      disabledSave: true,
      fileList: [],

      guId: "474fd125-7b97-4c30-88f2-5dd731fd111b",
      page: "orderBillingAdd",
      pageIndex: "undefined",
      routeObjName: 'receiptPayment',
      moneyAccountService: app.globalData['moneyAccountService'],
      otherReceivableService: app.globalData['otherReceivableService'],
      orderService: app.globalData['orderService'],
      otherPayableService: app.globalData['otherPayableService'],
    },

    /**
    * @desc : 设置查询参数
    * @date : 2024年3月8日
    * @author : 姜永辉
    */
    setSearchParams(params) {
      return params;
    },

    /** 
     * @desc : 查询 入库单
     * @date : 2024年3月8日
     * @author : 姜永辉
     */
    getData(params) {
      return this.excute(this.data.moneyAccountService, this.data.moneyAccountService.selectByCond, params);
    },

    /**
     * @desc :   处理接口返回数据
     * @date : 2024年3月8日
     * @author : 姜永辉
     */
    handleSearchData(tableData) {
      let formData = JSON.parse(this.data.item)
      //  根据formtype不同值 
      // formType ：1 收款单 ，2 付款单，3 客户收款保存参数,4 客户退款 5 退收款单 6 退付款单  7 订单开单收款
      if (this.data.formType == 1 || this.data.formType == 2
        || this.data.formType == 5 || this.data.formType == 6) {
        formData.sumAmount = formData.sumAmtRec
      }
      this.setData({
        formData: this.data.item,
        form: formData,
      })
      if ((this.data.formType == 3 || this.data.formType == 4) && formData.editFlag) { //客户收款/退款编辑
        this.setData({
          tableData: formData.dataItem,
          settlementTypeListLength: formData.dataItem.length
        })
        this.calculationScale(formData.dataItem)
      }

    },


    /**
     * @desc : 保存数据服务--校验
     * @date : 2024/2/1 15:49
     * @author : 姜永辉
     */
    validData() {
      let msgError = null
      let form = this.data.form
      // 请选择支付方式
      if (this.data.settlementTypeListLength == null || this.data.settlementTypeListLength == 0) {
        msgError = '请选择支付方式'
      }
      let sumAmount = Number(0)
      this.data.tableData.forEach(item => {
        if (item.checked) {
          sumAmount += Number(item.sumAmount)
        }
      })

      if (msgError != null) {
        utils.showToast(msgError);
        return false
      }
      if (sumAmount != form.sumAmount) {
        utils.showToast('输入收款金额不正确');
        return false
      }

      return true
    },

    /**
  * @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 : 姜永辉
 */
    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 : 姜永辉
     */
    setParams(params) {
      let form = this.data.form
      let itemList = []
      //收付款类型-收款的查询参数
      params.rpType = params.rpType ? params.rpType : Constants.rpType.receipt
      params.orgId = form.orgId  //组织部门
      params.staffId = form.staffId  // 员工
      // 合计优惠金额
      params.sumWaiveAmt = 0
      params.annexPaths = form.annexPaths ? form.annexPaths : []
      params.accDate = form.accDate  // 
      params.remarks = form.remarks  // 备注
      params.makeStaff = app.globalData.user.staffId  // 制单人 
      let tableData = this.data.tableData.filter(res => { return res.checked })
      //  根据formtype不同值 
      // formType ：1 收款单 ，2 付款单，3 客户收款保存参数,4 客户退款 5 退收款单 6 退付款单  7 订单开单收款
      if (this.data.formType == 1) {
        // 1 收款单
        params.objectId = this.data.form.objInfo.cusId  // 客户
        // 收款金额					
        params.sumAmtRec = Number(form.sumAmount)
        // 合计应收冲抵金额								
        params.sumAmtReceivableHandle = form.currentReceivableResidue
        // 预存的使用
        params.receiptResidue = form.receiptResidue
        // 合计优惠金额
        params.sumWaiveAmt = form.sumWaiveAmt
        let rlsit = this.setReturnReceivableList(form.receivableList || [], form.sumWaiveAmt, form.currentReceivableResidue, form.receivableResidue)
        params.receivableList = rlsit //应收收款的明细 
        tableData.forEach(item => {
          itemList.push(
            {
              amtRec: item.sumAmount,
              balance: item.balance,
              macCode: item.macCode,
              macId: item.macId,
              macName: item.macName,
            }
          )
        })

      } else if (this.data.formType == 2) {
        // 2 付款单，
        params.objectId = this.data.form.objInfo.supId  // 供应商
        // 收款金额					
        params.sumAmtPay = Number(form.sumAmount)
        // 合计应付冲抵金额								
        params.sumAmtPayableHandle = form.currentPayableResidue
        // 合计优惠金额
        params.sumWaiveAmt = form.sumWaiveAmt
        let rlsit = this.setReturnPayableList(form.payableList || [], form.sumWaiveAmt, form.currentPayableResidue, form.payableResidue)
        params.payableList = rlsit //应付款的明细 

        tableData.forEach(item => {
          itemList.push(
            {
              amtRec: item.sumAmount,
              balance: item.balance,
              macCode: item.macCode,
              macId: item.macId,
              macName: item.macName,
            }
          )
        })

      } else if (this.data.formType == 3) {
        //客户收款保存参数
        params.sumAmtRec = Number(params.sumAmtRec)
        if (form.editFlag) {
          tableData.forEach(res => {
            res.amtRec = res.sumAmount
          })
          itemList = tableData
        } else{
          tableData.forEach(item => {
            itemList.push(
              {
                amtRec: item.sumAmount,
                balance: item.balance,
                macCode: item.macCode,
                macId: item.macId,
                macName: item.macName,
              }
            )
          })
        }
       
        params.accDate = params.accDate ? params.accDate : utils.formatDayTime(new Date())
      } else if (this.data.formType == 4) {
        //客户退款保存参数
        params.sumAmtRec = Number(params.sumAmtRec)
        //编辑退款
        if (form.editFlag) {
          tableData.forEach(res => {
            res.amtRec = res.sumAmount
          })
          itemList = tableData
        } else {
          tableData.forEach(item => {
            itemList.push(
              {
                amtRec: item.sumAmount,
                balance: item.balance,
                macCode: item.macCode,
                macId: item.macId,
                macName: item.macName,
              }
            )
          })
        }
        params.accDate = params.accDate ? params.accDate : utils.formatDayTime(new Date())
      } else if (this.data.formType == 5) {
        // 5 退收款单
        params.objectId = this.data.form.objInfo.cusId  // 客户
        // 收款金额					
        params.sumAmtRec = Number(form.sumAmount)
        // 合计应收冲抵金额								
        params.sumAmtReceivableHandle = form.currentReceivableResidue
        // 预存的使用
        params.receiptResidue = form.receiptResidue
        // 合计优惠金额
        params.sumWaiveAmt = form.sumWaiveAmt
        let rlsit = this.setReturnReceivableList(form.receivableList || [], form.sumWaiveAmt, form.currentReceivableResidue, form.receivableResidue)
        params.receivableList = rlsit //应收收款的明细 
        tableData.forEach(item => {
          itemList.push(
            {
              amtRec: item.sumAmount,
              balance: item.balance,
              macCode: item.macCode,
              macId: item.macId,
              macName: item.macName,
            }
          )
        })

      } else if (this.data.formType == 6) {
        // 6 退付款单，
        params.objectId = this.data.form.objInfo.supId  // 供应商
        // 收款金额					
        params.sumAmtPay = Number(form.sumAmount)
        // 合计应付冲抵金额								
        params.sumAmtPayableHandle = form.currentPayableResidue
        // 合计优惠金额
        params.sumWaiveAmt = form.sumWaiveAmt
        let rlsit = this.setReturnPayableList(form.payableList || [], form.sumWaiveAmt, form.currentPayableResidue, form.payableResidue)
        params.payableList = rlsit //应付款的明细 

        tableData.forEach(item => {
          itemList.push(
            {
              amtRec: item.sumAmount,
              balance: item.balance,
              macCode: item.macCode,
              macId: item.macId,
              macName: item.macName,
            }
          )
        })
      } else if (this.data.formType == 7) { //其他收入单
        let formData = JSON.parse(this.data.formData)
        //收付款类型-收款的查询参数
        params.objectType = '对象类型-客户'
        params.objectId = formData.objInfo.cusId
        params.orgId = formData.orgId  //组织部门
        params.staffId = formData.staffId  // 员工
        params.accDate = formData.accDate
        params.annexPaths = formData.annexPaths || [] //附件 
        params.remarks = formData.remarks  // 备注
        params.makeStaff = app.globalData.user.staffId  // 制单人  
        let itemNumber = 0
        formData.itemList.forEach(element => {
          if (!isNaN(element.amtReceivable)) { //是数字才能加减
            itemNumber = Number(itemNumber) + Number(element.amtReceivable)
          }
          let item = {}
          item.receivableType = element.dataId //收入类别
          item.amtReceivable = element.receiptResidue //收入金额  
          itemList.push(item)
        });
        params.sumAmtReceivable = itemNumber
      } else if (this.data.formType == 8) { //订单开单收款

        params.sumAmtRec = Number(params.sumAmtRec)

        tableData.forEach(item => {
          itemList.push(
            {
              amtRec: item.sumAmount,
              balance: item.balance,
              macCode: item.macCode,
              macId: item.macId,
              macName: item.macName,
            }
          )
        })
        params.accDate = params.accDate ? params.accDate : utils.formatDayTime(new Date())
        params.receiptList = itemList
        console.log('params', params)
      } else if (this.data.formType == 9) { //其他支出
        let formData = JSON.parse(this.data.formData)
        //收付款类型-收款的查询参数
        params.objectType = '对象类型-供应商'
        params.objectId = formData.objInfo.supId
        params.orgId = formData.orgId //组织部门
        params.staffId = formData.staffId // 员工
        params.accDate = formData.accDate
        params.annexPaths = formData.annexPaths || [] //附件 
        params.remarks = formData.remarks // 备注
        params.makeStaff = app.globalData.user.staffId // 制单人  
        let itemNumber = 0
        formData.itemList.forEach(element => {
          if (!isNaN(element.amtPayable)) { //是数字才能加减
            itemNumber = Number(itemNumber) + Number(element.amtPayable)
          }
          let item = {}
          item.payableType = element.dataId //收入类别
          item.amtPayable = element.amtPayable //收入金额  
          itemList.push(item)
        });
        params.sumAmtPayable = itemNumber
      }

      if (this.data.formType !== 8) {
        params.itemList = itemList
      }


      return params
    },

    /**
    * @desc : 收款保存
    * @date : 2024/2/1 15:49
    * @author : 姜永辉
    */
    saveData() {
      //  根据formtype不同值  
      // formType ：1 收款单 ，2 付款单， 3 客户收款  4 客户退款  5 退收款单 6 退付款单  7 其他收入单 8 订单开单收款  9 其他支出
      if (this.data.formType == 1) {
        return this.excute(this.data.service, this.data.service.insertReceivableReceipt, this.data.params)
      } else if (this.data.formType == 2) {
        return this.excute(this.data.service, this.data.service.insertPayableReceipt, this.data.params)
      } else if (this.data.formType == 3) { //客户收款
        if (this.data.form.editFlag) {
          return this.excute(this.data.service, this.data.service.update, this.data.params)
        } else {
          return this.excute(this.data.service, this.data.service.insertReceipt, this.data.params)
        }
      } else if (this.data.formType == 4) { //客户退款
        if (this.data.form.editFlag) {
          return this.excute(this.data.service, this.data.service.update, this.data.params)
        } else {
          return this.excute(this.data.service, this.data.service.insertRefund, this.data.params)
        }

      } else if (this.data.formType == 5) {
        return this.excute(this.data.service, this.data.service.insertReceivableReceipt, this.data.params)
      } else if (this.data.formType == 6) {
        return this.excute(this.data.service, this.data.service.insertPayableReceipt, this.data.params)
      } else if (this.data.formType == 7) {
        return this.excute(this.data.otherReceivableService, this.data.otherReceivableService.insert, this.data.params)
      } else if (this.data.formType == 8) {
        return this.excute(this.data.orderService, this.data.orderService.insert, this.data.params);
      } else if (this.data.formType == 9) {
        return this.excute(this.data.otherPayableService, this.data.otherPayableService.insert, this.data.params);
      }




    },
    /**
      * @desc :   处理保存返回数据
      * @date : 2024年3月8日
      * @author : 姜永辉
      */
    handleData() {
      if (this.data.formType == 3 || this.data.formType == 4) { //客户收款/退款
        console.log('处理保存返回数据')
        let pages = getCurrentPages();
        let prevPage = pages[pages.length - 3]; //上二页
        prevPage.setData({
          refreshByAdd: true
        })
        wx.navigateBack({
          delta: 1
        })
      }
    },
    /**
     * 显示放大图片
     * @param {*} e 
     */
    previewImg: function (e) {
      let imgs = [e.currentTarget.dataset.imgurl]
      wx.previewImage({
        urls: imgs,
        current: e.currentTarget.dataset.imgurl, //当前图片地址
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    },


    /**
     * @desc : checkbox点击事件 
     * @date : 2022/5/23 15:16
     */
    catchtapCheck(e) {
      let tableData = this.data.tableData
      let form = this.data.form
      if (form.editFlag) {
        return
      }
      let index = e.target.dataset.index
      tableData[index].checked = e.detail
      if (tableData && tableData.length > 0) {
        // formType ：1 收款单 ，2 付款单，
        //客户收款结算方式多选
        if (tableData[index].checked) {
          tableData[index].sumAmount = Number(0)
        }
        //已选数量
        let settlementTypeListLength = tableData.filter(item => {
          return item.checked
        })
        //如果只选择一个 默认总的收款金额
        if (settlementTypeListLength.length == 1) {
          tableData.forEach(res => {
            if (res.checked) {
              res.sumAmount = form.sumAmount
            }
          })
        }
        if (settlementTypeListLength.length > 1) {
          this.calculationScale(tableData)
        }
        this.setData({
          tableData: tableData,
          settlementTypeListLength: settlementTypeListLength.length //已选数量
        })

      }
    },

    /**
      * @desc : 计算多选金额
      * @date : 2024/3/20 15:49
      * @author : 于继渤
      */
    calculationScale(tableData) {
      let form = this.data.form
      tableData = tableData.filter((item) => {
        return item.checked == true
      })
      let totalSumAmount = form.sumAmount
      let sumAmountIndexItem = Number(totalSumAmount / tableData.length).toFixed(2)
      let allocationRatioTotal = Number(0)
      //数据取余2为0
      if ((totalSumAmount % tableData.length) == 0) {
        //循环将计算好的百分比放入数据中
        for (let i in tableData) {
          tableData[i]['sumAmount'] = Number(sumAmountIndexItem).toFixed(2)
        }
      } else { //数据取余2不为0
        //获取最后选中checkbox数组中最后一个元素
        let endList = tableData.splice(-1)
        console.log('endList', endList)
        for (let i = 0; i < tableData.length; i++) {
          allocationRatioTotal = Number(allocationRatioTotal + Number(sumAmountIndexItem))
          tableData[i]['sumAmount'] = Number(sumAmountIndexItem).toFixed(2)
        }
        if (endList[0]) {
          endList[0]['sumAmount'] = Number(totalSumAmount - allocationRatioTotal).toFixed(2)
        }
      }
      this.setData({
        tableData: tableData
      })
    },
    /**
     * 结算方式金额输入事件
     * @param {*} e 
     */
    sumAmountBindValue(e) {
      let tableData = this.data.tableData
      let value = e.detail.value ? Number(e.detail.value) : 0
      let index = e.currentTarget.dataset.index
      tableData[index].sumAmount = value
      this.setData({
        tableData: tableData
      })
    },

    // sumAmountBlurValue(e){
    //   let tableData = this.data.tableData
    //   let form = this.data.form
    //   let index_ = e.currentTarget.dataset.index
    //   let value = e.currentTarget.dataset.value
    //   form.sumAmount - value
    //   let  tempList =[]

    //   for(let i =0 ;i < tableData.length;i++){
    //       if(i!=index_ && tableData[i].checked == true){
    //         tempList.push(tableData[i])
    //       }
    //   }

    //   console.log('tempList',tempList)

    //   tableData[index_].sumAmount = value
    //   this.setData({
    //       tableData: tableData
    //   })
    // },

    /**
     * @desc : 销售价格编辑
     * @author : 姜永辉
     * @date : 2022/5/31 14:45
     */
    changeSalesPriceField(e) {
      let form = this.data.form
      form.sumAmount = e.detail.value;
      let tableData = this.data.tableData
      if (tableData && tableData.length > 0) {
        tableData.forEach(res => {
          if (res.checked) {
            res.sumAmount = Number(e.detail.value ? e.detail.value : 0);
          }
        })
      }
      this.setData({
        tableData: tableData,
        form
      })
    },


  })