<!-- @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" style="width:100%">
          <!--客户电话-->
          <DkFormItem prop="cusPhone" :required="true">
            <SelectMagnifier v-model="formData.cusPhone" ref="cusPhone" :telephone="true"
                             primary-key="objectId" :multiple="false"
                             :type="this.$config.MagnifierType.customer"
                             @on-input-blur="selectCustomer"
                             @ok="selectCustomer"/>
          </DkFormItem>
          <!--客户名称-->
          <DkFormItem prop="cusName">
            <InputPop ref="cusName" :disabled="true" v-model="formData.cusName"/>
          </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="receivableResidue">
            <InputNumberPop ref="receivableResidue" v-model="formData.receivableResidue" :disabled="true"/>
          </DkFormItem>
          <!--预收余额-->
          <DkFormItem prop="receiptResidue">
            <InputNumberPop ref="receiptResidue" v-model="formData.receiptResidue" :disabled="true"/>
          </DkFormItem>
          <!--收款时间-->
          <DkFormItem prop="accDate" :label="$t('receiptDate')" :data-type="$config.dataType.date">
            <DatePickerPop v-model="formData.accDate"
                           :short-cut-flag="true"/>
          </DkFormItem>
          <!--备注-->
          <DkFormItem prop="remarks">
            <InputPop ref="remarks" v-model="formData.remarks"
                      maxlength=500 textareaFlag/>
          </DkFormItem>
        </DkForm>
      </DkPanel>
      <!--客户收款-->
      <DkPanel prop="customerReceipt">
        <div id="search-cond-div-receipt-info" ref="search-cond-div-goods-info" slot="content">
          <EditTable v-if="showEditTable" ref="receiptTable" :data="formData.itemList" showFooter
                     major-field="rpId"
                     :height="this.tableHeight/2"
                     :new-row-flag="true"
                     :columns="receiptColumns"
                     controlId="macId" @on-choose="getTotals" @changeValue="getTotals"/>
        </div>
      </DkPanel>
      <!--选择应收款单 -->
      <BaseIndexButtonGroup ref="BaseIndexButtonGroup" id="BaseIndexButtonGroup">
        <template #left>
          <BaseIndexButton ref="chooseReceivableInvoice" name="chooseReceivableInvoice"
                           @click="openReceivableModal"></BaseIndexButton>
        </template>
      </BaseIndexButtonGroup>
      <DkForm ref="receivableFootFormData" v-model="receivableFootFormData" :labelMaxWords="6" name="dk-form"
              class="form-content-class">
        <!-- 待核销金额 -->
        <DkFormItem prop="sumShouldHandle">
          <InputNumberPop ref="sumShouldHandle" v-model="receivableFootFormData.sumShouldHandle" :digits="2"
                          :disabled="true"/>
        </DkFormItem>
        <!-- 本次核销金额 -->
        <DkFormItem prop="sumAmtReceivableHandle">
          <InputNumberPop ref="sumAmtReceivableHandle" v-model="receivableFootFormData.sumAmtReceivableHandle"
                          :digits="2"
                          @on-change="sumAmtReceivableHandleChange"/>
        </DkFormItem>
        <!-- 优惠金额 -->
        <DkFormItem prop="sumAmtWaiveHandle">
          <InputNumberPop ref="sumAmtWaiveHandle" v-model="receivableFootFormData.sumAmtWaiveHandle" :digits="2"
                          @on-change="sumAmtWaiveHandleChange"/>
        </DkFormItem>
        <!-- 预收抵扣 -->
        <DkFormItem prop="sumUseReceiptResidue">
          <InputNumberPop ref="sumUseReceiptResidue" v-model="receivableFootFormData.sumUseReceiptResidue" :digits="2"
                          :disabled="true"/>
        </DkFormItem>
      </DkForm>
      <!--应收款单-->
      <DkPanel prop="receivableInvoice">
        <div id="search-cond-div-receivable-info" ref="search-cond-div-goods-info" slot="content">
          <EditTable ref="receivableTable" :data="formData.receivableList" showFooter major-field="itemId"
                     :new-row-flag="false" :add-flag="false"
                     :columns="receivableColumns" controlId="itemId" @on-choose="getReceivableTotals"
                     @changeValue="getReceivableTotals" @delRow="delReceivableTable"
                     :height="this.tableHeight/2"/>
        </div>
      </DkPanel>
      <!--附件-->
      <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>
      <DkForm ref="receivableFootFormData2" v-model="receivableFootFormData2" :labelMaxWords="6" name="dk-form"
              class="form-content-class">
        <!-- 收款金额 -->
        <DkFormItem prop="sumAmtRec">
          <InputNumberPop ref="sumAmtRec" v-model="receivableFootFormData2.sumAmtRec" :digits="2" :disabled="true"
                          :min="-9999999999"/>
        </DkFormItem>
        <!-- 应收核销总额 -->
        <DkFormItem prop="sumAmtReceivableHandle2">
          <InputNumberPop ref="sumAmtReceivableHandle2" v-model="receivableFootFormData2.sumAmtReceivableHandle2"
                          :digits="2" :disabled="true"/>
        </DkFormItem>
        <!-- 转预收金额 -->
        <DkFormItem prop="sumToReceiptResidue">
          <InputNumberPop ref="sumToReceiptResidue" v-model="receivableFootFormData2.sumToReceiptResidue" :digits="2"
                          :disabled="true"/>
        </DkFormItem>
      </DkForm>
    </DkCollapse>
    <!--      下部分按钮区域-->
    <DkSaveButton ref="saveButton" :loading="loading" @save="save(true)" @close="close"/>

    <!-- DkModal应收款单 -->
    <DkModal :loading="loading" v-model="receivableModal" ref="modal_receivable"
             @modalOk="receivableOk" :title='this.$t("应收款单")' :height="900" :width="1500">
      <BaseIndexButtonGroup ref="BaseIndexButtonGroup2" id="BaseIndexButtonGroup2">
        <template #left>
          <BaseIndexButton ref="search" name="search" @click="getReceivableInvoice"></BaseIndexButton>
          <BaseIndexButton ref="clear" name="clear"></BaseIndexButton>
        </template>
      </BaseIndexButtonGroup>
      <DkTable :id="'table-'+$options.name" ref="detail-select" :pageFlag="false"
               :data="tableData_receivable" :height="this.tableHeight" primaryKey="itemId" name="table">
        <DkTableColumn field="accDate" :title="$t('biznisDate')"/>
        <DkTableColumn field="biznisTypeName"/>
        <DkTableColumn field="biznisNo"/>
        <DkTableColumn field="cusName"/>
        <DkTableColumn field="orgName"/>
        <DkTableColumn field="staffName"/>
        <DkTableColumn field="recStatusName"/>
        <DkTableColumn field="amtShould" :title="$t('amtShouldReceivable')"/>
        <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,
      receivableModal: false,
      tableData_receivable: null,
      negativeFlag: false,
      showEditTable: true,
      // 画面表单数据
      formData: {
        accDate: new Date(),
        rpType: null,
        objectId: null,//客户Id
        cusName: null,
        cusPhone: null,
        addressFull: null,              // 详细地址
        sumAmtRec: 0,    // 合计收款金额
        receivableResidue: 0,
        receiptResidue: 0,
        remarks: null,
        annexPaths: null,
        staffId: this.$store.state.user.id,
        staffName: this.$store.state.user.staffName,
        orgId: this.$store.state.user.orgId,
        orgName: this.$store.state.user.orgName,
        makeStaff: self.$store.state.user.id,
        cpId: self.$store.state.user.cpId,
        itemList: [],
        receivableList: [],
      },
      // 应收合计信息
      receivableFootFormData: {
        sumShouldHandle: 0,
        sumAmtReceivableHandle: 0,
        sumAmtWaiveHandle: 0,
        sumUseReceiptResidue: 0,
      },
      // 应收合计信息
      receivableFootFormData2: {
        sumAmtRec: 0,
        sumAmtReceivableHandle2: 0,
        sumToReceiptResidue: 0,
      },
      receiptColumns: [
        {
          field: 'macName',
          controlId: 'macId',
          type: 'tableSelect',
          width: 200,
          dataType: self.$config.tableSelectType.moneyAccount,
          fieldUpdate: self.$updateColumns.receiptChooseMac,
          searchDetailFlag: true
        },
        //收款金额
        {
          field: 'amtRec',
          type: 'number',
          digits: 2,
          negative: () => self.negativeFlag,
          sum: true,
        },
        {
          field: 'remarks', type: 'text', equal: true,
        },
      ],
      receivableColumns: [
        {field: 'biznisTypeName', type: 'disabled'},
        {field: 'biznisNo', type: 'disabled'},
        {field: 'accDate', type: 'disabled'},
        {field: 'amtShould', title: self.$t('amtShouldReceivable'), type: 'disabled'},
        {field: 'amtHandle', type: 'disabled'},
        {field: 'amtNotHandle', type: 'disabled'},
        // 本次核销金额
        {
          field: 'amtReceivableHandle',
          type: 'number',
          digits: 2,
          number: true,
          sum: true,
          formula: {
            amtResidue: ['amtShould-amtHandle-amtReceivableHandle', 'amtShould', 'amtHandle', 'amtReceivableHandle'],
          },
        },
        // 本次优惠金额
        {
          field: 'amtWaiveHandle',
          type: 'number',
          digits: 2,
          number: true,
          sum: true,
        },
        {field: 'amtResidue', type: 'disabled'},
      ],
    }
  },
  methods: {
    /**
     * @desc   : 加载数据
     * @author : 付斌
     * @date   : 2024-02-20 15:53
     */
    initData() {
    },
    /**
     *   @desc   : 获取客户资料并且监听每一次的客户修改
     *   @date   : 2022/5/24 15:04
     *   @author : 付斌
     */
    selectCustomer(val) {
      if (val && val.length > 0) {
        this.formData.objectId = val[0].cusId
        this.formData.cusPhone = val[0].cusPhone
        this.formData.cusName = val[0].cusName
        // this.formData.orgId = val[0].orgId
        // this.formData.orgName = val[0].orgName
        // this.formData.staffId = val[0].staffId
        // this.formData.staffName = val[0].staffName
        this.formData.addressFull = val[0].addressFull

        // 查询客户可用余额
        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.receivableResidue = res.data.list[0].receivableResidue
            this.formData.receiptResidue = res.data.list[0].receiptResidue
            // 设置预收抵扣
            this.setReceiptResidue();
          }
        })
      }
    },
    /**
     *   @desc   : 收款计算合计
     *   @date   : 2022/5/30 15:31
     *   @author : 付斌
     */
    getTotals() {
      let table = this.$refs['receiptTable'].tableData
      if (table && table.length > 0) {
        this.formData.sumAmtRec = table.sum('amtRec');
        this.receivableFootFormData2.sumAmtRec = this.formData.sumAmtRec;
        // 设置预收抵扣
        this.setReceiptResidue();
      }
    },
    /**
     * @desc   :删除行事件
     * @author : 付斌
     * @date   : 2024-03-30 10:52
     */
    delReceivableTable() {
      this.getReceivableTotals();
      this.receivableFootFormData.sumShouldHandle = this.$refs['receivableTable'].tableData?.sum('amtNotHandle')
    },
    /**
     * @desc   : 应收计算合计
     * @author : 付斌
     * @date   : 2024-03-23 13:21
     */
    getReceivableTotals() {
      let receivableTable = this.$refs['receivableTable'].tableData
      if (receivableTable && receivableTable.length > 0) {
        this.receivableFootFormData.sumAmtReceivableHandle = receivableTable.sum('amtReceivableHandle')
        this.receivableFootFormData.sumAmtWaiveHandle = receivableTable.sum('amtWaiveHandle')
        this.receivableFootFormData2.sumAmtReceivableHandle2 = this.receivableFootFormData.sumAmtReceivableHandle
      } else {
        this.receivableFootFormData.sumAmtReceivableHandle = 0
        this.receivableFootFormData.sumAmtWaiveHandle = 0
        this.receivableFootFormData2.sumAmtReceivableHandle2 = 0
      }
      // 设置预收抵扣
      this.setReceiptResidue();
    },
    /**
     * @desc   : 打开选择应收单据的Modal
     * @author : 付斌
     * @date   : 2024-03-23 11:10
     */
    openReceivableModal() {
      if (!this.formData.objectId) {
        this.$Message.warning('请先选择客户')
        return false;
      }
      this.receivableModal = true
    },
    /**
     * @desc   : 获取应收单据
     * @author : 付斌
     * @date   : 2024-03-22 16:42
     */
    getReceivableInvoice() {
      // 查询客户可用余额
      let params = {
        'objectId': this.formData.objectId,
        'formType': this.type
      }
      this.excute(this.$service.accountService, this.$service.accountService.getReceivableAccountItem, params).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          this.tableData_receivable = res.data
        }
      })
    },
    /**
     * @desc   : 选择应收单据
     * @author : 付斌
     * @date   : 2024-03-23 11:10
     */
    receivableOk() {
      this.formData.receivableList = this.$refs['detail-select'].batchRows
      // 剩余金额清0
      this.formData.receivableList.forEach(row => {
        this.$set(row, 'amtResidue', 0);
      })
      let sumAmtReceivableHandle = this.formData.receivableList.sum('amtReceivableHandle');
      this.receivableFootFormData.sumAmtReceivableHandle = sumAmtReceivableHandle
      this.receivableFootFormData.sumShouldHandle = sumAmtReceivableHandle
      this.receivableFootFormData2.sumAmtReceivableHandle2 = sumAmtReceivableHandle
      this.receivableModal = false
      // 设置预收抵扣
      this.setReceiptResidue();
    },
    /**
     * @desc   : 核销金额改变事件
     * @author : 付斌
     * @date   : 2024-03-23 13:10
     */
    sumAmtReceivableHandleChange(val) {
      this.$refs['receivableTable'].tableData.forEach(row => {
        // 先把本次核销金额清0
        this.$set(row, 'amtReceivableHandle', 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, 'amtReceivableHandle', val);
            this.$set(row, 'amtResidue', amtResidue - val);
            val = 0;
          }
          // 否则把剩余应收赋给本次应收，然后剩余应收为0
          else {
            this.$set(row, 'amtReceivableHandle', amtResidue);
            this.$set(row, 'amtResidue', 0);
            val = val - amtResidue;
          }
        }
      })
      this.receivableFootFormData2.sumAmtReceivableHandle2 = this.receivableFootFormData.sumAmtReceivableHandle
      // 设置预收抵扣
      this.setReceiptResidue();
    },
    /**
     * @desc   : 优惠金额改变事件
     * @author : 付斌
     * @date   : 2024-03-23 13:10
     */
    sumAmtWaiveHandleChange(val) {
      let receivableTable = this.$refs['receivableTable'].tableData
      let sumAmtShould = receivableTable.sum('amtShould')  // 合计核销数量
      // 基本颗粒
      let particle = val / sumAmtShould;
      let amtWaiveHandle = 0;     // 本行计算出的优惠金额
      let sumAmtWaiveHandle = 0;  // 合计优惠金额
      receivableTable.forEach((row, index) => {
        amtWaiveHandle = (particle * parseFloat(row['amtShould'])).toFixed(2)
        // 当是最后一行的时候，用减法算出最后一行的优惠金额
        if (index === receivableTable.length - 1) {
          this.$set(row, 'amtWaiveHandle', val - sumAmtWaiveHandle);
        } else {
          this.$set(row, 'amtWaiveHandle', amtWaiveHandle);
          sumAmtWaiveHandle += parseFloat(amtWaiveHandle);
        }
      })
      // 设置预收抵扣
      this.setReceiptResidue();
    },
    /**
     * @desc   : 校验数据
     * @author : 付斌
     * @date   : 2024-03-11 14:37
     */
    validData() {
      // 校验收款表
      let itemTable = this.$refs['receiptTable'].getTableDataFilter();
      if (itemTable && itemTable.length > 0) {
        for (let it of itemTable) {
          if (!it.amtRec || it.amtRec === '') {
            this.$Message.warning(this.$t('W_042', {'param': '收款金额不能'}))
            return false;
          }
        }
      }

      // 校验应收核销表
      let receivableTable = this.$refs['receivableTable'].getTableDataFilter();
      let receivableHandleIsZero = false;
      receivableTable.forEach(row => {
        // 如果本次核销没有数值，则置为0
        if (!row['amtReceivableHandle'] || row['amtReceivableHandle'] === '') {
          this.$set(row, 'amtReceivableHandle', 0);
          receivableHandleIsZero = true;
        }
        // 如果本次优惠没有数值，则置为0
        if (!row['amtWaiveHandle'] || row['amtWaiveHandle'] === '') {
          this.$set(row, 'amtWaiveHandle', 0);
        }
        // 将优惠金额设置成保存时需要的列名
        this.$set(row, 'amtWaive', row['amtWaiveHandle']);
      })
      if (receivableHandleIsZero) {
        this.$Message.warning('请将本次核销金额为0的行去掉')
        return false;
      }
      let sumAmtReceivableHandle = receivableTable.sum('amtReceivableHandle') // 本次核销金额
      let sumAmtWaiveHandle = receivableTable.sum('amtWaiveHandle')           // 本次优惠金额
      if (this.receivableFootFormData.sumAmtReceivableHandle != sumAmtReceivableHandle) {
        this.$Message.warning('本次核销金额合计与本次总核销金额不一致')
        return false;
      }
      if (this.receivableFootFormData.sumAmtWaiveHandle != sumAmtWaiveHandle) {
        this.$Message.warning('本次优惠金额合计与本次总优惠金额不一致')
        return false;
      }
      if (Math.abs(sumAmtWaiveHandle) > Math.abs(sumAmtReceivableHandle)) {
        this.$Message.warning('优惠金额不能超出本次核销总额')
        return false;
      }
      // 超出金额 = 核销总额 - 优惠总额 - 收款总额 - 客户预收
      let excessAmt = parseFloat(this.receivableFootFormData.sumAmtReceivableHandle) - parseFloat(this.receivableFootFormData.sumAmtWaiveHandle)
        - parseFloat(this.receivableFootFormData2.sumAmtRec) - parseFloat(this.formData.receiptResidue)
      if (excessAmt > 0) {
        this.$Message.warning('（本次总核销金额 - 优惠金额）不能大于（收款金额 + 预收金额）')
        return false;
      }
      // for (let it of receivableTable) {
      //   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.shouKuan
      } else if (this.type === this.$config.formMode.refund) {
        this.formData.rpType = this.$config.rpType.tuiShouKuan
      }
      this.formData.accDate = new Date(this.formData.accDate).toDateStr();
      // 修改新增的表数据
      let itemTable = this.$refs['receiptTable'].getTableDataFilter();
      let receivableTable = this.$refs['receivableTable'].getTableDataFilter();

      this.formData.itemList = itemTable
      this.formData.receivableList = receivableTable
      Object.assign(this.params, this.formData, this.receivableFootFormData)
    },
    /**
     * @desc   : 保存数据
     * @author : 付斌
     * @date   : 2023/6/25 14:31
     */
    saveData() {
      if (this.type === this.$config.formMode.add) {
        return this.excute(this.$service.receiptService, this.$service.receiptService.insertReceivableReceipt, 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,              // 详细地址
        sumAmtRec: 0,    // 合计收款金额
        receivableResidue: 0,
        receiptResidue: 0,
        remarks: null,
        annexPaths: null,
        staffId: this.$store.state.user.id,
        staffName: this.$store.state.user.staffName,
        orgId: this.$store.state.user.orgId,
        orgName: this.$store.state.user.orgName,
        makeStaff: self.$store.state.user.id,
        cpId: self.$store.state.user.cpId,
        itemList: [],
        receivableList: [],
      }
    },
    /**
     * @desc   :设置预收抵扣和转预收金额
     * @author : 付斌
     * @date   : 2024-03-30 9:52
     */
    setReceiptResidue() {
      if (this.formData.receiptResidue != null) {
        // 本次要用到的预存 = 核销总额-优惠总额-收款总额
        let useReceiptResidue = parseFloat(this.receivableFootFormData.sumAmtReceivableHandle)
          - parseFloat(this.receivableFootFormData2.sumAmtRec) - parseFloat(this.receivableFootFormData.sumAmtWaiveHandle);
        if (useReceiptResidue >= 0) {
          this.receivableFootFormData2.sumToReceiptResidue = 0;
          if (this.formData.receiptResidue >= useReceiptResidue) {
            this.receivableFootFormData.sumUseReceiptResidue = useReceiptResidue
          } else {
            this.receivableFootFormData.sumUseReceiptResidue = this.formData.receiptResidue
          }
        } else {
          this.receivableFootFormData.sumUseReceiptResidue = 0
          this.receivableFootFormData2.sumToReceiptResidue = -useReceiptResidue;
        }
      }
    },
  },
  /**
   * @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>
