<!-- @desc:收款  @auth:周兴  @time:2022/6/15 10:53 -->
<template>
  <div>
    <div style="display: flex;height: 28px">
      <InputNumberPop size="small" v-model="sumAmount" ref="sumAmount" :digits="2"
                      :readonly=true @on-focus="handleInputFocus" @on-keydown="handleInputKeydown">
      </InputNumberPop>
      <div class="close-class" v-if="!readonly && sumAmount!=0">
        <Icon slot="prefix" type="ios-close-circle" @click.stop="clear"/>
      </div>
      <Icon @click="handleOpen" type="md-search" class="search-button-class"/>
    </div>

    <div>
      <DkModal
        v-model="showModal"
        @modalOk="modalOk"
        @modalCancel="handleClose"
        ref="modal_receiptAmount"
        :title="$t('sumReceiptAmount')"
      >
        <!--合计金额-->
        <Row style="padding-bottom: 5px">
          <Col span="12">
            <DkFormItem prop="sumAmount" :label="$t('needReceivable')">
              <InputNumberPop size="small" v-model="totalAmount" ref="totalAmount" :digits="2"
                              :readonly=true></InputNumberPop>
            </DkFormItem>
          </Col>
          <Col span="12">
            <DkFormItem prop="surplusAmount">
              <InputNumberPop size="small" v-model="surplusAmount" ref="surplusAmount" :digits="2"
                              :readonly=true></InputNumberPop>
            </DkFormItem>
          </Col>
        </Row>

        <EditTable ref="receiptAmountTable" name="table" :height="height" :data="dataFinal" showFooter
                   :operate-flag="false" @changeValue="changeValue" @on-keydown="handleKeydown"
                   :columns="columns" controlId="typeId"
        ></EditTable>

<!--        <div slot="footer" style="width:100%;border:none;">-->
<!--          <DkButton ref="confirm" type="primary" name="confirm" @click="modalOk">{{-->
<!--              $t('confirm')-->
<!--            }}-->
<!--          </DkButton>-->
<!--          <DkButton ref="close" name="close" @click="handleClose">{{ $t('close') }}</DkButton>-->
<!--        </div>-->
        <span style="color:grey;font-size: 14px">注：可以在金额中使用=进行快速输入需收款金额</span>
      </DkModal>
    </div>
  </div>
</template>

<script>

export default {
  name: "modal-receipt",
  props: {
    value: {
      type: Number,
      default: 0
    },
    data: {
      type: Array,
      default: () => []
    },
    // table的高度
    height: {
      type: [String, Number],
      default: 300
    },
    // 合计金额
    totalAmount: {
      type: Number,
      default: 0
    },
    // 可用预存
    usablePrestore: {
      type: Number,
      default: 0
    },
    //是否只读
    readonly: {
      type: Boolean,
      default: false
    },
    //是否为负,如果为负数，那么输入的正数也会自动变为负数
    negative: {
      type: Boolean,
      default: false
    },
  },
  watch: {
    data(n, o) {
      this.dataFinal = [...n]
      this.$refs['receiptAmountTable'].$refs['table'].reloadData(this.dataFinal)
      // 如果可用预存有值，需要传入
      this.setPrestore();
      this.sumAmount = this.sumFinal;
      this.dataSocial = JSON.parse(JSON.stringify(this.dataFinal))
    },
    totalAmount(n, o) {
      // 合计金额变化，并且剩余应收跟合计金额相乘为负数,清空收款记录
      if(n != o && this.surplusAmount && this.surplusAmount * n < 0 && !this.readonly){
        this.clear();
      }
      //计算剩余应收
      this.setPrestore();
      this.negativeData = n < 0 ? true : false;
    },
    sumAmount(n, o) {
      //计算剩余应收
      this.setPrestore();
    },
    usablePrestore(n, o) {
      // 去掉使用预存
      if (!n) {
        this.dataFinal = this.dataFinal.filter(it => it['typeId'] !== -1);
        this.dataSocial = JSON.parse(JSON.stringify(this.dataFinal))
      } else {
        //设置预存
        this.setPrestore();
      }
    },
    negative(n, o) {
      this.negativeData = n;
    },
  },
  data() {
    let self = this;
    return {
      columns: [
        {field: 'typeName', type: 'disabled', title: self.$t('settlementTypesName'), width: 'auto'},
        {field: 'itemAmount', type: 'number', digits: 2, sum: true, negative:()=> self.negativeData},
      ],
      negativeData: false,
      showModal: false,
      sumAmount: 0,  //返回的数据
      sumFinal: 0,   //临时数据
      dataFinal: [], // 数据
      dataSocial: [],// 记录原始的数据
      receiptList: [],//收款金额
      surplusAmount: 0,// 剩余应收
      errorFlag: false,// 校验标识
      calcPrestoreFlag: true,// 是否计算预存
    }
  },
  methods: {
    /**
     * @desc   : 打开窗体
     * @author : 周兴
     * @date   : 2022/6/21 19:15
     */
    handleOpen() {
      if (this.readonly) {
        return;
      }
      this.setPrestore();
      this.showModal = true;
    },
    /**
     * @desc   : 设置预存
     * @author : 周兴
     * @date   : 2022/6/16 20:06
     */
    setPrestore() {
      // console.log('tts',this.usablePrestore,this.calcPrestoreFlag)
      if (this.usablePrestore > 0 && this.calcPrestoreFlag) {
        let filterRows = this.dataFinal.filter(it => it['typeId'] === -1);
        if (!filterRows || filterRows.length === 0) {
          let row = {};
          row.typeId = -1;
          row.typeName = this.$t('usePrestore') + "【" + this.usablePrestore + "】";
          // 如果可用预存大于合计金额，那么预存就等于合计金额
          if (this.usablePrestore > this.totalAmount) {
            row.itemAmount = this.totalAmount;
          } else {
            row.itemAmount = this.usablePrestore;
          }
          this.dataFinal.splice(0, 0, row);
        } else {
          // 如果可用预存大于合计金额，那么预存就等于合计金额
          if (this.usablePrestore > this.totalAmount) {
            filterRows[0].itemAmount = this.totalAmount;
          } else {
            filterRows[0].itemAmount = this.usablePrestore;
          }
        }
        // this.dataSocial = JSON.parse(JSON.stringify(this.dataFinal))
      }
      // 计算剩余应收
      this.changeValue();
    },
    /**
     * @desc   : 点回车显示modal
     * @author : 周兴
     * @date   : 2022/6/16 19:22
     */
    handleInputKeydown(e) {
      if (this.readonly) {
        return;
      }
      if (e.key === 'Enter') {
        this.showModal = true
      }
    },
    /**
     * @desc   : 计算剩余应收
     * @author : 周兴
     * @date   : 2022/6/15 13:08
     */
    calcSurplusAmount() {
      this.surplusAmount = this.totalAmount - this.sumFinal;
    },
    /**
     * @desc   : 光标进入之后，没有值就打开
     * @author : 周兴
     * @date   : 2022/6/15 9:19
     */
    handleInputFocus() {
      if (this.readonly) {
        return;
      }
      if (!this.sumAmount || this.sumAmount === 0) {
        this.showModal = true;
      }
    },
    /**
     * @desc   : 改变值后，进行处理数据
     * @author : 周兴
     * @date   : 2022/6/15 13:15
     */
    changeValue() {
      let list = this.dataFinal.filter(it => it.itemAmount != 0)
      if (list && list.length > 0) {
        let amount = 0;
        for (let row of list) {
          //计算总金额
          amount += parseFloat(row.itemAmount);
        }
        this.sumFinal = amount;
      }
      //计算剩余金额
      this.calcSurplusAmount();
    },
    /**
     * @desc   : 如果按等号，直接就等于剩余应收
     * @author : 周兴
     * @date   : 2022/6/15 13:21
     */
    handleKeydown(e) {
      if (e.key === '=') {
        // 说明有可用预存，可用预存使用等号，等于可用预存
        if (this.dataFinal[e.rowIndex]['typeId'] === -1) {
          this.dataFinal[e.rowIndex][e.column.field] = this.usablePrestore;
          if (this.$refs.receiptAmountTable.$refs[e.column.field + e.rowIndex]) {
            this.$refs.receiptAmountTable.$refs[e.column.field + e.rowIndex][0].value = this.usablePrestore;
          }
        } else {
          let amount = 0;
          // 计算输入的金额
          if (this.dataFinal && this.dataFinal.length > 0) {
            for (let i in this.dataFinal) {
              if (e.rowIndex != i) {
                //计算总金额
                amount += parseFloat(this.dataFinal[i].itemAmount);
              }
            }
          }
          //负数
          if(this.negativeData){
            amount = this.totalAmount - amount;
          }else{
            amount =  this.totalAmount - amount < 0 ? 0 : this.totalAmount - amount;
          }
          this.dataFinal[e.rowIndex][e.column.field] = amount;
          if (this.$refs.receiptAmountTable.$refs[e.column.field + e.rowIndex]) {
            this.$refs.receiptAmountTable.$refs[e.column.field + e.rowIndex][0].inputValue = amount?amount:0;
          }
        }
        //计算剩余金额
        this.changeValue();
      }
    },
    /**
     *   @desc   : 清空
     *   @date   : 2022/6/9 11:46
     *   @author : 周兴
     */
    clear() {
      this.calcPrestoreFlag = true;
      this.sumAmount = 0
      this.sumFinal = 0;
      this.surplusAmount = 0;
      this.dataFinal = JSON.parse(JSON.stringify(this.dataSocial))
      this.$emit('on-choose', 0, [])
    },
    /**
     * @desc   : 关闭
     * @author : 周兴
     * @date   : 2022/6/17 15:17
     */
    handleClose() {
      if (this.errorFlag) {
        this.sumAmount = 0
        this.sumFinal = 0;
        this.surplusAmount = 0;
        this.dataFinal = JSON.parse(JSON.stringify(this.dataSocial))
      }
      this.showModal = false
    },
    /**
     *   @desc   : 计算总额
     *   @date   : 2022/6/15 11:46
     *   @author : 周兴
     */
    modalOk() {
      this.errorFlag = false;
      this.$refs['receiptAmountTable'].$refs.table.clearActived();
      // 判断剩余应收是否小于0
      // if (!this.negativeData && this.surplusAmount < 0) {
      //   this.$Message.warning(this.$t('W_041', {'param': this.$t('surplusAmount')}))
      //   this.errorFlag = true;
      //   return;
      // }
      if (this.negativeData && this.surplusAmount > 0) {
        this.$Message.warning(this.$t('W_008', {'param1': this.$t('refundAmount'), 'param2': this.$t('canRefundAmount')}))
        this.errorFlag = true;
        return;
      }
      // 如果有使用预存，是否超过使用预存
      if (this.usablePrestore > 0) {
        let filterRows = this.dataFinal.filter(it => it.typeId === -1);
        if (filterRows && filterRows.length > 0) {
          if (this.usablePrestore < filterRows[0]['itemAmount']) {
            this.$Message.warning(this.$t('W_008', {
              'param1': this.$t('prestoreAmount'),
              'param2': this.$t('canUsePrestore')
            }))
            this.errorFlag = true;
            return;
          }
        }
      }
      this.calcPrestoreFlag = true;
      this.showModal = false
      this.sumFinal = 0
      //过滤出费用金额不是0的
      this.receiptList = []
      let list = this.dataFinal.filter(it => it.itemAmount != 0)
      if (list && list.length > 0) {
        let amount = 0;
        for (let row of list) {
          this.receiptList.push(row)
          //计算总费用金额
          amount += parseFloat(row.itemAmount);
        }
        this.sumFinal = amount;
      }
      this.sumAmount = this.sumFinal;
      this.$refs['sumAmount'].$refs.inputNumber.focus();
      this.$emit('on-choose', this.sumAmount, this.receiptList)
      this.showModal = false;
      this.calcPrestoreFlag = false;
    },
  },
  created() {
    this.negativeData = this.negative;
    // 根据需收款金额进行判断，如果小于0 ，就可以输入负数
    if (this.totalAmount < 0) {
      this.negativeData = true;
    }
    this.dataFinal = [...this.data]
    this.sumAmount = this.sumFinal;
    this.dataSocial = JSON.parse(JSON.stringify(this.dataFinal))
    // 计算剩余应收
    this.calcSurplusAmount();
  }
}
</script>

<style scoped>
.search-button-class {
  justify-content: center;
  align-items: center;
  display: flex;
  height: 28px;
  width: 24px;
  cursor: pointer;
  border-bottom: 1px solid rgb(220, 222, 226);
  border-right: 1px solid rgb(220, 222, 226);
  border-top: 1px solid rgb(220, 222, 226);
}

.close-class {
  cursor: pointer;
  width: 24px;
  position: absolute;
  top: 5px;
  right: 15px;
  align-items: center;
  justify-content: center;
  height: 24px;
  color: #a0a5ac;
  z-index: 99;
}
</style>
