<!-- @desc:销售订单新建  @auth:付斌  @time:2024/02/20 15:15 -->
<template>

  <div class="main-div" style="position: relative;">
    <DkCollapse @on-change="changeCollapse" ref="collapse">
      <DkPanel prop="essentialInformation">
        <!--  单据信息  -->
        <DkForm slot="content" ref="formInline" v-model="formData" :label-max-words="5" style="width:100%">
          <!--供应商-->
          <DkFormItem prop="objectId" :label="$t('supName')" :required="true">
            <SelectMagnifier v-model="formData.objectId" :display-text="formData.supName"
                             :type="this.$config.MagnifierType.supplier"
                             :multiple="false"
                             @ok="supplierOk"/>
          </DkFormItem>
          <!--业务部门-->
          <DkFormItem prop="orgId" :label="$t('orgId')">
            <SelectMagnifier v-model="formData.orgId" :display-text="formData.orgName"
                             :type="this.$config.MagnifierType.org"
                             :multiple="false"/>
          </DkFormItem>
          <!--业务员-->
          <DkFormItem prop="staffId" :label="$t('staffId')">
            <SelectMagnifier v-model="formData.staffId" :display-text="formData.staffName"
                             :type="this.$config.MagnifierType.staff"
                             :multiple="false"/>
          </DkFormItem>
          <!--应付余额-->
          <DkFormItem prop="payableResidue">
            <InputNumberPop ref="payableResidue" v-model="formData.payableResidue" :disabled="true"/>
          </DkFormItem>
          <!--预收余额-->
          <DkFormItem prop="paymentResidue">
            <InputNumberPop ref="paymentResidue" v-model="formData.paymentResidue" :disabled="true"/>
          </DkFormItem>
          <!--付款时间-->
          <DkFormItem prop="accDate" :label="$t('paymentDate')" :data-type="$config.dataType.date">
            <DatePickerPop v-model="formData.accDate"
                           :short-cut-flag="true"/>
          </DkFormItem>
          <!--备注-->
          <DkFormItem prop="remarks" :span="12">
            <InputPop ref="remarks" v-model="formData.remarks"
                      maxlength=500 textareaFlag/>
          </DkFormItem>
        </DkForm>
      </DkPanel>
      <!--供应商付款-->
      <DkPanel prop="supplierPayment">
        <div id="search-cond-div-goods-info" ref="search-cond-div-goods-info" slot="content">
          <EditTable v-if="showEditTable" ref="paymentTable" :data="formData.itemList" showFooter
                     major-field="rpId"
                     :height="this.tableHeight/2"
                     :new-row-flag="true"
                     :columns="paymentColumns"
                     controlId="macId" @on-choose="getTotals" @changeValue="getTotals"/>
        </div>
      </DkPanel>
      <BaseIndexButtonGroup ref="BaseIndexButtonGroup" id="BaseIndexButtonGroup">
        <template #left>
          <BaseIndexButton ref="choosePayableInvoice" name="choosePayableInvoice"
                           @click="openPayableModal"></BaseIndexButton>
        </template>
      </BaseIndexButtonGroup>
      <DkForm ref="payableFootFormData" v-model="payableFootFormData" :labelMaxWords="6" name="dk-form"
              class="form-content-class">
        <!-- 待核销金额 -->
        <DkFormItem prop="sumShouldHandle">
          <InputNumberPop ref="sumShouldHandle" v-model="payableFootFormData.sumShouldHandle" :digits="2"
                          :disabled="true"/>
        </DkFormItem>
        <!-- 本次核销金额 -->
        <DkFormItem prop="sumAmtPayableHandle">
          <InputNumberPop ref="sumAmtPayableHandle" v-model="payableFootFormData.sumAmtPayableHandle"
                          :digits="2"
                          @on-change="sumAmtPayableHandleChange"/>
        </DkFormItem>
        <!-- 优惠金额 -->
        <DkFormItem prop="sumAmtWaiveHandle">
          <InputNumberPop ref="sumAmtWaiveHandle" v-model="payableFootFormData.sumAmtWaiveHandle" :digits="2"
                          @on-change="sumAmtWaiveHandleChange"/>
        </DkFormItem>
        <!-- 预收抵扣 -->
        <DkFormItem prop="sumUsePaymentResidue">
          <InputNumberPop ref="sumUsePaymentResidue" v-model="payableFootFormData.sumUsePaymentResidue" :digits="2"
                          :disabled="true"/>
        </DkFormItem>
      </DkForm>
      <!--应付款单-->
      <DkPanel prop="payableInvoice">
        <div id="search-cond-div-payable-info" ref="search-cond-div-goods-info" slot="content">
          <EditTable ref="payableTable" :data="formData.payableList" showFooter major-field="itemId"
                     :new-row-flag="false" :add-flag="false"
                     :columns="payableColumns" controlId="itemId" @on-choose="getPayableTotals"
                     @changeValue="getPayableTotals" @delRow="delPayableTable"
                     :height="this.tableHeight/2"/>
        </div>
      </DkPanel>
      <DkForm ref="payableFootFormData2" v-model="payableFootFormData2" :labelMaxWords="6" name="dk-form"
              class="form-content-class">
        <!-- 付款金额 -->
        <DkFormItem prop="sumAmtPay">
          <InputNumberPop ref="sumAmtPay" v-model="payableFootFormData2.sumAmtPay" :digits="2" :disabled="true"
                          :min="-9999999999"/>
        </DkFormItem>
        <!-- 应付核销总额 -->
        <DkFormItem prop="sumAmtPayableHandle2">
          <InputNumberPop ref="sumAmtPayableHandle2" v-model="payableFootFormData2.sumAmtPayableHandle2"
                          :digits="2" :disabled="true"/>
        </DkFormItem>
        <!-- 转预收金额 -->
        <DkFormItem prop="sumToPaymentResidue">
          <InputNumberPop ref="sumToPaymentResidue" v-model="payableFootFormData2.sumToPaymentResidue" :digits="2"
                          :disabled="true"/>
        </DkFormItem>
      </DkForm>
      <!--附件-->
      <DkPanel prop="files">
        <div id="search-cond-div-files-info" ref="search-cond-div-files-info" slot="content">
          <DkPicWall v-model="formData.annexPaths"
                     :table="$config.tables.recPay" :accept="$config.uploadFileConfig.acceptPicType"
                     :format="['jpg','jpeg','png']"></DkPicWall>
        </div>
      </DkPanel>
    </DkCollapse>
    <!--      下部分按钮区域-->
    <DkSaveButton ref="saveButton" :loading="loading" @save="save(true)" @close="close"/>

    <!-- DkModal应付款单 -->
    <DkModal :loading="loading" v-model="payableModal" ref="modal_payable"
             @modalOk="payableOk" :title='this.$t("应付款单")' :height="900" :width="1500">
      <BaseIndexButtonGroup ref="BaseIndexButtonGroup2" id="BaseIndexButtonGroup2">
        <template #left>
          <BaseIndexButton ref="search" name="search" @click="getPayableInvoice"></BaseIndexButton>
          <BaseIndexButton ref="clear" name="clear"></BaseIndexButton>
        </template>
      </BaseIndexButtonGroup>
      <DkTable :id="'table-'+$options.name" ref="detail-select" :pageFlag="false"
               :data="tableData_payable" :height="this.tableHeight" primaryKey="itemId" name="table">
        <DkTableColumn field="accDate" :title="$t('biznisDate')"/>
        <DkTableColumn field="biznisTypeName"/>
        <DkTableColumn field="biznisNo"/>
        <DkTableColumn field="supName"/>
        <DkTableColumn field="orgName"/>
        <DkTableColumn field="staffName"/>
        <DkTableColumn field="recStatusName"/>
        <DkTableColumn field="amtShould" :title="$t('amtShouldPayable')"/>
        <DkTableColumn field="amtHandle"/>
        <DkTableColumn field="amtWaive"/>
        <DkTableColumn field="amtResidue"/>
      </DkTable>
    </DkModal>
  </div>
</template>

<script>
import {formMixin} from '@/mixins/form'

export default {
  components: {},
  mixins: [formMixin],
  data() {
    let self = this
    return {
      loading: false,
      payableModal: false,
      tableData_payable: null,
      negativeFlag: false,
      showEditTable: true,
      // 画面表单数据
      formData: {
        accDate: new Date(),
        rpType: null,
        objectId: null,//客户Id
        supName: null,
        staffId: null,
        staffName: null,
        staffCode: null,
        orgId: null,
        orgName: null,
        orgCode: null,
        sumAmtPay: 0,    // 合计付款金额
        payableResidue: 0,
        paymentResidue: 0,
        remarks: null,
        annexPaths: null,
        makeStaff: self.$store.state.user.id,
        cpId: self.$store.state.user.cpId,
        itemList: [],
        payableList: [],
      },
      // 应付合计信息
      payableFootFormData: {
        sumShouldHandle: 0,
        sumAmtPayableHandle: 0,
        sumAmtWaiveHandle: 0,
        sumUsePaymentResidue: 0,
      },
      // 应付合计信息
      payableFootFormData2: {
        sumAmtPay: 0,
        sumAmtPayableHandle2: 0,
        sumToPaymentResidue: 0,
      },
      paymentColumns: [
        {
          field: 'macName',
          controlId: 'macId',
          type: 'tableSelect',
          width: 200,
          dataType: self.$config.tableSelectType.moneyAccount,
          fieldUpdate: self.$updateColumns.paymentChooseMac,
          searchDetailFlag: true
        },
        //付款金额
        {
          field: 'amtPay',
          type: 'number',
          digits: 2,
          negative: () => self.negativeFlag,
          sum: true,
        },
        {
          field: 'remarks', type: 'text', equal: true,
        },
      ],
      payableColumns: [
        {field: 'biznisTypeName', type: 'disabled'},
        {field: 'biznisNo', type: 'disabled'},
        {field: 'accDate', type: 'disabled'},
        {field: 'amtShould', title: self.$t('amtShouldPayable'), type: 'disabled'},
        {field: 'amtHandle', type: 'disabled'},
        {field: 'amtNotHandle', type: 'disabled'},
        // 本次核销金额
        {
          field: 'amtPayableHandle',
          type: 'number',
          digits: 2,
          number: true,
          sum: true,
          formula: {
            amtResidue: ['amtShould-amtHandle-amtPayableHandle', 'amtShould', 'amtHandle', 'amtPayableHandle'],
          },
        },
        // 本次优惠金额
        {
          field: 'amtWaiveHandle',
          type: 'number',
          digits: 2,
          number: true,
          sum: true,
        },
        {field: 'amtResidue', type: 'disabled'},
      ],
    }
  },
  methods: {
    /**
     * @desc   : 加载数据
     * @author : 付斌
     * @date   : 2024-02-20 15:53
     */
    initData() {
      this.formData.staffId = this.$store.state.user.id
      this.formData.staffName = this.$store.state.user.staffName
      this.formData.orgId = this.$store.state.user.orgId
      this.formData.orgName = this.$store.state.user.orgName
    },
    /**
     *   @desc   : 获取客户资料并且监听每一次的客户修改
     *   @date   : 2022/5/24 15:04
     *   @author : 付斌
     */
    supplierOk(val) {
      if (val && val.length > 0) {
        this.formData.objectId = val[0].supplierId
        this.formData.supName = val[0].supplierName

        // 查询客户可用余额
        let params = {
          'objectId': this.formData.objectId
        }
        this.excute(this.$service.accountService, this.$service.accountService.selectByCond, params).then(res => {
          if (res.code === this.$config.SUCCESS_CODE && res.data.list.length > 0) {
            this.formData.payableResidue = res.data.list[0].payableResidue
            this.formData.paymentResidue = res.data.list[0].paymentResidue
            // 设置预收抵扣
            this.setPaymentResidue();
          }
        })
      }
    },
    /**
     *   @desc   : 付款计算合计
     *   @date   : 2022/5/30 15:31
     *   @author : 付斌
     */
    getTotals() {
      let table = this.$refs['paymentTable'].tableData
      if (table && table.length > 0) {
        this.formData.sumAmtPay = table.sum('amtPay');
        this.payableFootFormData2.sumAmtPay = this.formData.sumAmtPay;
        // 设置预收抵扣
        this.setPaymentResidue();
      }
    },
    /**
     * @desc   :删除行事件
     * @author : 付斌
     * @date   : 2024-03-30 10:52
     */
    delPayableTable() {
      this.getPayableTotals();
      this.payableFootFormData.sumShouldHandle = this.$refs['payableTable'].tableData?.sum('amtNotHandle')
    },
    /**
     * @desc   : 应付计算合计
     * @author : 付斌
     * @date   : 2024-03-23 13:21
     */
    getPayableTotals() {
      let payableTable = this.$refs['payableTable'].tableData
      if (payableTable && payableTable.length > 0) {
        this.payableFootFormData.sumAmtPayableHandle = payableTable.sum('amtPayableHandle')
        this.payableFootFormData.sumAmtWaiveHandle = payableTable.sum('amtWaiveHandle')
        this.payableFootFormData2.sumAmtPayableHandle2 = this.payableFootFormData.sumAmtPayableHandle
      } else {
        this.payableFootFormData.sumAmtPayableHandle = 0
        this.payableFootFormData.sumAmtWaiveHandle = 0
        this.payableFootFormData2.sumAmtPayableHandle2 = 0
      }
      // 设置预收抵扣
      this.setPaymentResidue();
    },
    /**
     * @desc   : 打开选择应付单据的Modal
     * @author : 付斌
     * @date   : 2024-03-23 11:10
     */
    openPayableModal() {
      if (!this.formData.objectId) {
        this.$Message.warning('请先选择供应商')
        return false;
      }
      this.payableModal = true
    },
    /**
     * @desc   : 获取应付单据
     * @author : 付斌
     * @date   : 2024-03-22 16:42
     */
    getPayableInvoice() {
      // 查询客户可用余额
      let params = {
        'objectId': this.formData.objectId,
        'formType': this.type
      }
      this.excute(this.$service.accountService, this.$service.accountService.getPayableAccountItem, params).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          this.tableData_payable = res.data
        }
      })
    },
    /**
     * @desc   : 选择应付单据
     * @author : 付斌
     * @date   : 2024-03-23 11:10
     */
    payableOk() {
      this.formData.payableList = this.$refs['detail-select'].batchRows
      // 剩余金额清0
      this.formData.payableList.forEach(row => {
        this.$set(row, 'amtResidue', 0);
      })
      let sumAmtPayableHandle = this.formData.payableList.sum('amtPayableHandle');
      this.payableFootFormData.sumAmtPayableHandle = sumAmtPayableHandle
      this.payableFootFormData.sumShouldHandle = sumAmtPayableHandle
      this.payableFootFormData2.sumAmtPayableHandle2 = sumAmtPayableHandle
      this.payableModal = false
      // 设置预收抵扣
      this.setPaymentResidue();
    },
    /**
     * @desc   : 核销金额改变事件
     * @author : 付斌
     * @date   : 2024-03-23 13:10
     */
    sumAmtPayableHandleChange(val) {
      this.$refs['payableTable'].tableData.forEach(row => {
        // 先把本次核销金额清0
        this.$set(row, 'amtPayableHandle', 0);
        // 如果本次优惠没有数值，则置为0
        if (!row['amtWaiveHandle'] || row['amtWaiveHandle'] === '') {
          this.$set(row, 'amtWaiveHandle', 0);
        }
        // 设置剩余应付 = 应付-已核销
        this.$set(row, 'amtResidue', parseFloat(row['amtShould']) - parseFloat(row['amtHandle']));

        // 剩余应付
        let amtResidue = parseFloat(row['amtResidue']);
        if (amtResidue > 0) {
          // 如果剩余应付比输入的值大，则把输入的值赋给本次应付，然后剩余应付减输入的值
          if (amtResidue > val) {
            this.$set(row, 'amtPayableHandle', val);
            this.$set(row, 'amtResidue', amtResidue - val);
            val = 0;
          }
          // 否则把剩余应付赋给本次应付，然后剩余应付为0
          else {
            this.$set(row, 'amtPayableHandle', amtResidue);
            this.$set(row, 'amtResidue', 0);
            val = val - amtResidue;
          }
        }
      })
      this.payableFootFormData2.sumAmtPayableHandle2 = this.payableFootFormData.sumAmtPayableHandle
      // 设置预收抵扣
      this.setPaymentResidue();
    },
    /**
     * @desc   : 优惠金额改变事件
     * @author : 付斌
     * @date   : 2024-03-23 13:10
     */
    sumAmtWaiveHandleChange(val) {
      let payableTable = this.$refs['payableTable'].tableData
      let sumAmtShould = payableTable.sum('amtShould')  // 合计核销数量
      // 基本颗粒
      let particle = val / sumAmtShould;
      let amtWaiveHandle = 0;     // 本行计算出的优惠金额
      let sumAmtWaiveHandle = 0;  // 合计优惠金额
      payableTable.forEach((row, index) => {
        amtWaiveHandle = (particle * parseFloat(row['amtShould'])).toFixed(2)
        // 当是最后一行的时候，用减法算出最后一行的优惠金额
        if (index === payableTable.length - 1) {
          this.$set(row, 'amtWaiveHandle', val - sumAmtWaiveHandle);
        } else {
          this.$set(row, 'amtWaiveHandle', amtWaiveHandle);
          sumAmtWaiveHandle += parseFloat(amtWaiveHandle);
        }
      })
      // 设置预收抵扣
      this.setPaymentResidue();
    },
    /**
     * @desc   : 校验数据
     * @author : 付斌
     * @date   : 2024-03-11 14:37
     */
    validData() {
      // 校验付款表
      let itemTable = this.$refs['paymentTable'].getTableDataFilter();
      if (itemTable && itemTable.length > 0) {
        for (let it of itemTable) {
          if (!it.amtPay || it.amtPay === '') {
            this.$Message.warning(this.$t('W_042', {'param': '付款金额不能'}))
            return false;
          }
        }
      }

      // 校验应付核销表
      let payableTable = this.$refs['payableTable'].getTableDataFilter();
      let payableHandleIsZero = false;
      payableTable.forEach(row => {
        // 如果本次核销没有数值，则置为0
        if (!row['amtPayableHandle'] || row['amtPayableHandle'] === '') {
          this.$set(row, 'amtPayableHandle', 0);
          payableHandleIsZero = true;
        }
        // 如果本次优惠没有数值，则置为0
        if (!row['amtWaiveHandle'] || row['amtWaiveHandle'] === '') {
          this.$set(row, 'amtWaiveHandle', 0);
        }
        // 将优惠金额设置成保存时需要的列名
        this.$set(row, 'amtWaive', row['amtWaiveHandle']);
      })
      if (payableHandleIsZero) {
        this.$Message.warning('请将本次核销金额为0的行去掉')
        return false;
      }
      let sumAmtPayableHandle = payableTable.sum('amtPayableHandle') // 本次核销金额
      let sumAmtWaiveHandle = payableTable.sum('amtWaiveHandle')           // 本次优惠金额
      if (this.payableFootFormData.sumAmtPayableHandle != sumAmtPayableHandle) {
        this.$Message.warning('本次核销金额合计与本次总核销金额不一致')
        return false;
      }
      if (this.payableFootFormData.sumAmtWaiveHandle != sumAmtWaiveHandle) {
        this.$Message.warning('本次优惠金额合计与本次总优惠金额不一致')
        return false;
      }
      if (Math.abs(sumAmtWaiveHandle) > Math.abs(sumAmtPayableHandle)) {
        this.$Message.warning('优惠金额不能超出本次核销总额')
        return false;
      }
      // 超出金额 = 核销总额 - 优惠总额 - 付款总额 - 客户预收
      let excessAmt = parseFloat(this.payableFootFormData.sumAmtPayableHandle) - parseFloat(this.payableFootFormData.sumAmtWaiveHandle)
        - parseFloat(this.payableFootFormData2.sumAmtPay) - parseFloat(this.formData.paymentResidue)
      if (excessAmt > 0) {
        this.$Message.warning('（本次总核销金额 - 优惠金额）不能大于（付款金额 + 预收金额）')
        return false;
      }
      // for (let it of payableTable) {
      //   if (!it.amtResidue < 0) {
      //     this.$Message.warning('剩余应付不能小于0')
      //     return false;
      //   }
      // }
      return true;
    },
    /**
     * @desc   : 给参数赋值
     * @author : 付斌
     * @date   : 2023/6/25 14:31
     */
    setParams(arg) {
      if (this.type === this.$config.formMode.add) {
        this.formData.rpType = this.$config.rpType.fuKuan
      } else if (this.type === this.$config.formMode.refund) {
        this.formData.rpType = this.$config.rpType.tuifuKuan
      }
      this.formData.accDate = new Date(this.formData.accDate).toDateStr();
      // 修改新增的表数据
      let itemTable = this.$refs['paymentTable'].getTableDataFilter();
      let payableTable = this.$refs['payableTable'].getTableDataFilter();

      this.formData.itemList = itemTable
      this.formData.payableList = payableTable
      Object.assign(this.params, this.formData, this.payableFootFormData)
    },
    /**
     * @desc   : 保存数据
     * @author : 付斌
     * @date   : 2023/6/25 14:31
     */
    saveData() {
      if (this.type === this.$config.formMode.add) {
        return this.excute(this.$service.paymentService, this.$service.paymentService.insertPayablePayment, this.params);
      }
    },
    /**
     * @desc   :新建完毕后清空窗体
     * @author : 付斌
     * @date   : 2024-02-27 10:33
     */
    clear() {
      let self = this
      this.formData = {
        accDate: new Date(),
        rpType: null,
        objectId: null,//客户Id
        cusName: null,
        cusPhone: null,
        addressFull: null,              // 详细地址
        staffId: null,
        staffName: null,
        staffCode: null,
        orgId: null,
        orgName: null,
        orgCode: null,
        sumAmtPay: 0,    // 合计付款金额
        payableResidue: null,
        paymentResidue: null,
        remarks: null,
        annexPaths: null,
        makeStaff: self.$store.state.user.id,
        cpId: self.$store.state.user.cpId,
        itemList: [],
        payableList: [],
      }
    },
    /**
     * @desc   :设置预收抵扣和转预收金额
     * @author : 付斌
     * @date   : 2024-03-30 9:52
     */
    setPaymentResidue() {
      if (this.formData.paymentResidue != null) {
        // 本次要用到的预存 = 核销总额-优惠总额-付款总额
        let usePaymentResidue = parseFloat(this.payableFootFormData.sumAmtPayableHandle)
          - parseFloat(this.payableFootFormData2.sumAmtPay) - parseFloat(this.payableFootFormData.sumAmtWaiveHandle);
        if (usePaymentResidue >= 0) {
          this.payableFootFormData2.sumToPaymentResidue = 0;
          if (this.formData.paymentResidue >= usePaymentResidue) {
            this.payableFootFormData.sumUsePaymentResidue = usePaymentResidue
          } else {
            this.payableFootFormData.sumUsePaymentResidue = this.formData.paymentResidue
          }
        } else {
          this.payableFootFormData.sumUsePaymentResidue = 0
          this.payableFootFormData2.sumToPaymentResidue = -usePaymentResidue;
        }
      }
    },
  },
  /**
   * @desc   : 在实例创建完成后被立即同步调用
   * @author : 付斌
   * @date   : 2022/3/3 10:32
   */
  created() {
    this.focusItem = 'rpId';    // 给第一个组件赋值，可以在混入中自动去聚焦
    this.primaryKey = 'rpId'  // 设置主键Id

    // 如果是退款，editTable要输入负数
    if (this.type === this.$config.formMode.refund) {
      this.showEditTable = false
      this.negativeFlag = true;
      setTimeout(() => {
        this.showEditTable = true;
      }, 50)
    }
  }
}
</script>
