<template>
  <div class="span" style="overflow-y: auto !important;">
    <validator name='v'>
      <form class="form-horizontal">
        <div class="row" style="padding-top: 0.5em;">
          <div class="col-sm-4 form-group" :class="[$v.payment.required ? 'has-error select-error' : '']">
            <label for="f_paytype" class=" font_normal_body" title="参数名称：付款方式">收款方式</label>
            <input type="text" v-show="false" v-model="$refs.payment.selectedItems" v-validate:payment='{required: true }'>
            <v-select id="f_payment"
                      v-model="f_payment"
                      style="width:60%"
                      placeholder='请选择'
                      :value.sync="data.f_payment"
                      :options='paytype'
                      v-ref:payment
                      close-on-select clear-button>
            </v-select>

          </div>
          <div class="col-sm-4 form-group">
            <label for="f_print" class="font_normal_body">打印格式</label>

            <v-select id="print"
                      v-model="data.f_print"
                      placeholder='请选择'
                      style="width:60%"
                      :value.sync="data.f_print"
                      :options='printstyle'
                      close-on-select clear-button>
            </v-select>

          </div>
          <div class="col-sm-4 form-group">
            <label for="f_overdue" class="font_normal_body">违&ensp;约&ensp;金</label>
            <input class="input_search" style="width:60%"  type="number" v-model="newOverdue"
                   v-scale="[newOverdue,2]" placeholder="违约金"
                   disabled>
            <!--<button type="button" name="button" class="btn btn-link" @click="modefiy()" v-if="authArr.includes('违约金修改')">修改</button>-->
          </div>
        </div>
        <div class="row" style="padding-top: 0.5em;" >

          <div class="col-sm-4 form-group">
            <label for="f_pregas" class=" font_normal_body">用&ensp;气&ensp;量</label>
            <input class="input_search" style="width:60%"  type="number"
                   v-model="data.f_pregas" placeholder="用气量"
                   v-scale = "[data.f_pregas, 2]" disabled>
          </div>
          <div class="col-sm-4 form-group">
            <label for="f_preamount" class="font_normal_body">实欠气费</label>
            <input class="input_search" style="width:60%" style="width:60%"  type="number" v-model="data.f_preamount"
                   v-scale = "[data.f_preamount, 2]"
                   placeholder="实欠气费" disabled>
          </div>

          <div class="col-sm-4 form-group">
            <label for="f_totalcost" class=" font_normal_body">应收金额</label>
            <input class="input_search" style="width:60%"   type="number" v-model="data.f_totalcost"
                   v-scale = "[data.f_totalcost, 2]" placeholder="应收金额" disabled>
          </div>
        </div>

        <div class="row" style="padding-top: 0.5em;">
          <div class="col-sm-4 form-group">
            <label for="f_balance"  class="font_normal_body">上期结余</label>
            <input class="input_search" style="width:60%"  type="number" v-model="data.f_balance"
                   v-scale="[data.f_balance,4]" placeholder="上期结余" disabled>
          </div>
          <div class="col-sm-4 form-group">
            <label for="f_overdue" class="font_normal_body">本期结余</label>
            <input class="input_search" style="width:60%"  type="number" v-model="curbalance" disabled>
          </div>
          <div  class="col-sm-3 form-group" v-if="config.hasfindaReail" :class="[$v.f_collection.required || $v.f_collection.dctest ? 'has-error select-error' : '']">
            <label for="f_collection" class="font_normal_body">收&emsp;&emsp;款</label>
            <input id="f_collection" class="input_search" style="width:60%" type="number" v-model="data.f_collection"
                   v-validate:f_collection='{required: true, dctest: [0, ">=" ]}'  v-scale = "[data.f_collection, 2]"
                   @mousewheel.native.prevent @keyup.enter="confirm()" :disabled="$refs.givechange.promptText != ''">
          </div>
          <div  class="col-sm-4 form-group" v-if="!config.hasfindaReail" :class="[$v.f_collection.required || $v.f_collection.dctest ? 'has-error select-error' : '']">
            <label for="f_collection" class="font_normal_body">收&emsp;&emsp;款</label>
            <input id="f_collection" class="input_search" style="width:60%" type="number" v-model="data.f_collection"
                   v-validate:f_collection='{required: true, dctest: [0, ">=" ]}'  v-scale = "[data.f_collection, 2]"
                   @mousewheel.native.prevent @keyup.enter="confirm()" :disabled="$refs.givechange.promptText != ''">
          </div>
          <div class="col-sm-1 form-group" v-if="config.hasfindaReail">
            <give-change :curbalance="curbalance" :collection.sync="data.f_collection" v-ref:givechange></give-change>
          </div>
        </div>

        <div class="row" style="margin-top:5px;" v-show="authArr.includes('优惠权限')">
          <div class="col-sm-4 form-group">
            <label class="font_normal_body">优惠方式</label>
            <v-select v-model="data.f_privilege_id" @blur.native.capture="privilegeCalculate"
                      placeholder='请选择'
                      :value.sync="data.f_privilege_id"
                      :options='privilegeList' clear-button value-single>
            </v-select>
          </div>
          <div class="col-sm-4 form-group">
            <label for="f_preamount" class=" font_normal_body">优惠金额</label>
            <input class="input_search" style="width:60%" type="number" v-model="data.f_privilege_money"
                   v-scale="[data.f_privilege_money, 2]" placeholder="优惠金额" disabled>
          </div>
          <div class="col-sm-4 form-group">
            <label for="f_preamount" class=" font_normal_body">实际收款</label>
            <input class="input_search" style="width:60%" type="number" v-model="data.f_after_discount"
                   v-scale="[data.f_after_discount, 2]" placeholder="优惠后收款" disabled>
          </div>
        </div>

        <div class="row" style="padding-top: 0.5em;">
          <div class="col-sm-4 form-group" v-show="row.f_garbage_fee === '是'">
            <label for="f_garbage_fee" class="font_normal_body">垃&ensp;圾&ensp;费</label>
            <input class="input_search" style="width:60%"  type="number" v-model="data.f_garbage_fee" disabled>
          </div>
        </div>

        <div class="row" style="padding-top: 0.5em;">
          <div class="col-sm-4" v-if="!mjshow" >
            <label for="f_serial_number" class=" font_normal_body">业务单号</label>
            <input class="input_search" style="width:60%"  type="text"
                   v-model="data.f_serial_number" placeholder="业务单号">
          </div>
          <div class="col-sm-4" v-if="mjshow" :class="[$v.f_serial_number.required || $v.f_serial_number.dctest ? 'has-error' : 'has-success']">
            <label for="f_serial_number" class=" font_normal_body">业务单号</label>
            <input class="input_search" style="width:60%"  type="text" v-validate:f_serial_number='{required: true }'
                   v-model="data.f_serial_number" placeholder="业务单号">
          </div>
          <div class="col-sm-8">
            <label for="f_comments" class="font_normal_body">备&emsp;&emsp;注</label>
            <input class="input_search" style="width:87%" v-model="data.f_comments" placeholder="备注">
          </div>
        </div>
      </form>
      <book-bill :show="bookprint" :url="'rs/report/book_detail_bill'" :data='bookData' @toggle="closeBookPrint" @printok="printok2"  v-ref:bookbill></book-bill>
      <validate-bill v-if="hasValidateBill" :data="data" @validate-bill="validateBill"></validate-bill>
      <print-bill :show="print" :bill-config='config' :bill-data='billData' v-on:toggle="close" :data='data' @printok="printok" v-ref:printbill></print-bill>
      <ticket-print  :show="eticket_show" @toggle="eticket_toggle"  v-ref:eticketbill></ticket-print>
      <eticket-modal :show="eticket_msg" @closemodalshow="eticket_msg = false" :row="row" @confirm="confirm"></eticket-modal>
      <div class="text-right" style="margin-top: 1%">
        <strong style="color:red;margin-right: 5px">{{ $refs.givechange.promptText }}</strong>
        <payment-code-button :clickable="!$v.valid || validateOk"
                             :payment.sync="data.f_payment" :payment-data="paytype"
                             @confirm-payment="confirm()">
        </payment-code-button>
        <button class="button_search btn-gn" @click="checkInvoiceMsg()"  :disabled='!$v.valid || validateOk'>确认</button>
        <!--<button class="btn btn-success" @click="confirmUserinfo()"  :disabled='!$v.valid'>信息保存</button>-->
        <button class="button_clear btn-gn" @click="clean()">取消</button>
      </div>
    </validator>
    <!--<modal :show.sync="showOverdueModal" v-ref:modal backdrop="false">-->
    <!--<header slot="modal-header" class="modal-header">-->
    <!--<button type="button" class="close" @click="closeOverdue"><span>&times;</span></button>-->
    <!--<h4 class="modal-title">修改违约金</h4>-->
    <!--</header>-->
    <!--<article slot="modal-body" class="modal-body">-->
    <!--<validator name='m'>-->
    <!--<form class="form-horizontal">-->
    <!--<div class="row">-->
    <!--<div class="col-sm-6">-->
    <!--<label for="oldOverdue" class="font_normal_body">原违约金</label>-->
    <!--<input type="text" class="input_search" style="width:60%" v-once v-model="overdueModal.f_old_overdue" disabled>-->
    <!--</div>-->
    <!--</div>-->
    <!--<div class="row">-->
    <!--<div class="col-sm-6" :class="[$m.f_new_overdue.required ? 'has-error select-error' : '']">-->
    <!--<label for="newOverdue" class="font_normal_body">新违约金</label>-->
    <!--<input type="text" class="input_search" style="width:60%" v-model="overdueModal.f_new_overdue"-->
    <!--v-validate:f_new_overdue='{required: true}'>-->
    <!--</div>-->
    <!--</div>-->
    <!--</form>-->
    <!--</validator>-->
    <!--</article>-->

    <!--<footer slot="modal-footer" class="modal-footer">-->
    <!--<button type="button" class="button_search" :disabled='!$m.valid' @click='confirmOverdue()'>确认</button>-->
    <!--<button type="button" class="button_clear" @click='closeOverdue'>取消</button>-->
    <!--</footer>-->
    <!--</modal>-->
    <payment-code v-ref:paymentcode :payment="data.f_payment" :row="row" :money="data.f_after_discount"></payment-code>
  </div>
  <upload :blodid="row.f_userinfo_id" v-if="config.showupload" isremark="true" fusetype="机表收费"></upload>
</template>
<script>
  import {HttpResetClass} from 'vue-client'

/**
 *售气收费
 *机表收费组件
 */

let asyncMachineMeterCenter = async function (self) {
    await self.$getConfig(self, 'MachineMeterCenter')
    self.data.f_print = self.config.printType instanceof Array ? self.config.printType : [self.config.printType]
    self.data.f_payment = [self.config.payment]
    self.data.f_use_type = self.config.billType
    self.data.f_bill_type = self.data.f_print
    self.hasValidateBill = self.config.hasBillManage
  }

  let machineChargeGen = async function (self) {
    try {
      if (!self.model) self.model = {}
      // 加入扫码盒付款码支付流水号
      self.model.f_serial_id = self.$refs.paymentcode.paymentCodeReturnData.f_out_trade_no
      console.log('查看传过来的数据=====================>', self)
      let res = await self.$MachineChargeService.marchineCharge(self.data, self.model, self.row, self.floor)
      let localeSustainMoney = window.localStorage.getItem('sustainMoney')
      if (localeSustainMoney != null) {
        localeSustainMoney = (localeSustainMoney - 0) + (self.data.f_collection - self.data.f_garbage_fee)
        window.localStorage.setItem('sustainMoney', localeSustainMoney)
      }
      let param = []
      for (let row of self.resid) {
        param.push({id: row.id})
      }
      let data = {
        param: param,
        f_blobid: res.data
      }

      await self.$resetpost('rs/logic/updatefiles', data)

      // 开始打票
      if (self.config.hasPrint) {
        if (self.data.f_print.indexOf('电子发票') == -1) {
          if (self.$login.r.includes('非民用纸质票据拆分')) {
            if (self.row.f_user_type === '非民用') {
              self.billData.url = 'rs/report/fmy_machine_bill'
            }
          }
          if (self.config.hasBillManage) {
            // 启用发票管理，获取票据管理中的票号并存储记录
            self.data.id = res.data
            self.data.f_bill_type = '机表收费'
            self.data.f_bill_style = self.data.f_print[0]
            self.print = true
          } else {
            // 如果不欠费就用下边的预存收据
            if (self.$parent.$children[0].selecteds) {
              console.log('1111111', self.$parent.$children[0].selecteds)
              if (self.$parent.$children[0].selectedRows === 0) {
                console.log('22222222', self.$parent.$children[0].selectedRows)
                self.billData.url = 'rs/report/pre_sell'
              }
              // 获取选中的handplan的id
              self.data.handid = ''
              self.$parent.$children[0].selecteds.forEach((row, index) => {
                self.data.handid = self.data.handid + "','" + row.handplan_id
              })
            } else {
              console.log('3333333')
              self.billData.url = 'rs/report/pre_sell'
              self.data.handid = ''
            }
            self.data.id = res.data
            self.print = true
          }
        } else if (self.data.f_print[0] === '国税发票') {
          // TODO
        } else if (self.data.f_print[0] === '电子发票') {
          self.eticket_show = true
          await self.$refs.eticketbill.openETicket([res.data], self.row, '是', self.invoice_is_pax, '机表收费')
          // await self.$CommonService.openEticket(res.data, '售气收费')
          // 如果不欠费就用下边的预存收据
          // if (self.$parent.$children[0].selecteds) {
          //   if (self.$parent.$children[0].selectedRows === 0) {
          //     self.billData.url = 'rs/report/pre_sell'
          //   }
          //   // 获取选中的handplan的id
          //   self.data.handid = ''
          //   self.$parent.$children[0].selecteds.forEach((row, index) => {
          //     self.data.handid = self.data.handid + "','" + row.handplan_id
          //   })
          // } else {
          //   self.billData.url = 'rs/report/pre_sell'
          //   self.data.handid = ''
          // }
          // self.data.id = res.data
          // self.print = true
        }
      } else {
        if (self.config.isPrintBook) {
          self.printok()
        } else {
          self.$dispatch('success', '机表收费确认', self.row, self.data)
        }
      }
    } catch (error) {
      self.$showAlert(error, 'danger', 0)
      self.$dispatch('refresh')
    }
  }

  export default {
    title: '收费',
    data () {
      return {
        mjshow: false,
        resid: [],  // 存放新增的f_files表中id
        config: {
          showupload: true, // 显示上传
          hasPrint: true,  // 默认打票
          hasBillManage: false,  // 默认不启用发票管理
          hasfindaReail: true,  // 默认开启找零功能
          billType: '燃气费',   // 票据类型（燃气费，其他费用，调用的发票代码不同）
          printType: '普通收据', // 收据/电子票/专用发票/国税发票
          payment: '现金缴费',
          isPrintBook: true  // 是否打折
        },
        eticket_msg: false,
        eticket_show: false,
        invoice_is_pax: '征税',
        is_pax: [{label: '征税', value: '征税'}, {label: '不征税', value: '不征税'}],
        // 垃圾费
        f_garbage_fee: 0,
        overdueModal: {
          f_old_overdue: 0,
          f_new_overdue: ''
        },
        newOverdue: 0,
        isBreakOverdue: false,
        breakOverdue: {},

        showErrorMsg: false,
        print: false,
        isConfirm: true,
        show: false,
        count: 0,
        billData: {
          url: 'rs/report/machine_bill',
          bill: ''
        },

        // 启用发票管理需要对票号进行验证
        hasValidateBill: false,
        validateOk: false,
        handid: '',
        showOverdueModal: false,
        editOverdue: this.$login.r.includes('违约金修改'),
        paytype: [],
        printstyle: this.$appdata.getParam('打印格式') ? this.$appdata.getParam('打印格式') : [],
        privilegeList: [{label: '无优惠', value: '0'}],
        // 在向下取整时,保存所有的应交金额
        totalcost: 0,
        serialShow: false,
        bookprint: false,
        bookData: {},
        gasMonth: ''
      }
    },
    props: ['data', 'row', 'floor', 'ceil', 'charge'],
    ready () {
      this.paytype = this.$appdata.getParam('付款方式') ? this.$appdata.getParam('付款方式') : []
      if (!this.$login.r.includes('免交充值付款')) {
        this.paytype = this.paytype.filter((item) => {
          return item.label != '免交'
        })
      }
      // this.calOverdue()
      this.newOverdue = this.overdueModal.f_old_overdue = this.data.f_overdue
      if (this.floor) {
        this.totalcost = this.data.f_totalcost
      }
      document.getElementById('f_collection').focus()
      asyncMachineMeterCenter(this)
      this.getGasMonth()
    },
    events: {
      // 删除Resid数组元素
      'delResid' (val) {
        this.resid.$remove({id: val, f_biobid: ''})
      // this.resid.splice(this.resid.indexOf({id:val,f_biobid:''}),1);
      },
      // 增加Resid数组元素
      'resid' (val) {
        this.resid.push({id: val, f_biobid: ''})
      }
    },
    modefiy () {
      this.overdueModal.f_new_overdue = ''
      this.showOverdueModal = true
    },
    methods: {
      // 校验发票信息
      checkInvoiceMsg () {
        if (this.data.f_print[0] === '电子发票') {
          if (!this.row.f_taxpayer_id) {
            this.row.f_taxpayer_id = this.row.f_idnumber
          }
          if (!this.row.f_paper_name) {
            this.row.f_paper_name = this.row.f_user_name
          }
          if (!this.row.f_address_phone) {
            this.row.f_address_phone = this.row.f_address + ' ' + this.row.f_user_phone
          }
          if (!this.row.f_email) {
            this.row.f_email = this.row.f_email
          }
          this.eticket_msg = true
        } else {
          this.confirm()
        }
      },
      confirmOverdue () {
        this.breakOverdue = {
          f_user_id: this.data.f_user_id,
          f_userfiles_id: this.data.f_userfiles_id,
          f_userinfo_id: this.data.f_userinfo_id,
          f_old_overdue: this.overdueModal.f_old_overdue,
          f_new_overdue: this.overdueModal.f_new_overdue,
          f_operator: this.$login.f.name,
          f_operatorid: this.$login.f.id,
          f_orgid: this.$login.f.orgid,
          f_orgname: this.$login.f.orgs,
          f_depid: this.$login.f.depids,
          f_depname: this.$login.f.deps,
          f_zoneid: this.$login.f.zoneid,
          f_zones: this.$login.f.zones
        }
        this.showOverdueModal = false
        this.newOverdue = this.overdueModal.f_new_overdue
        this.isBreakOverdue = (this.overdueModal.f_new_overdue - this.overdueModal.f_old_overdue != 0)
      },

      closeOverdue () {
        this.showOverdueModal = false
        this.editOverdue = null
        this.showErrorMsg = false
      },
      /**
       * 用来进行小数相加的工具方法
       * @param {*} num1
       * @param {*} num2
       */
      addNum (num1, num2) {
        let sq1, sq2, multiple
        try {
          sq1 = num1.toString().split('.')[1].length
        } catch (e) {
          sq1 = 0
        }
        try {
          sq2 = num2.toString().split('.')[1].length
        } catch (e) {
          sq2 = 0
        }
        multiple = Math.pow(10, Math.max(sq1, sq2) + 1)
        return (num1 * multiple + num2 * multiple) / multiple
      },
      /**
       * 用来进行小数相减的工具方法
       * @param {*} num1
       * @param {*} num2
       */
      subNum (num1, num2) {
        let sq1, sq2, multiple
        try {
          sq1 = num1.toString().split('.')[1].length
        } catch (e) {
          sq1 = 0
        }
        try {
          sq2 = num2.toString().split('.')[1].length
        } catch (e) {
          sq2 = 0
        }
        multiple = Math.pow(10, Math.max(sq1, sq2) + 1)
        return (num1 * multiple - num2 * multiple) / multiple
      },
      confirm () {
        this.eticket_msg = false
        // 如果有变更原因说明有变更
        if (this.data.f_collection < 0) {
          this.$showMessage('收款金额不能小于零！！')
          return
        }
        if (this.charge) {
          let inti = this.subNum(this.addNum(this.data.f_collection, this.data.f_balance), this.data.f_totalcost)
          console.log('===>', inti)
          if (this.floor) {
            if (inti < -1) {
              this.$showMessage('收款金额不足以清缴欠费，请核查，并重新输入收款金额！！')
              return
            }
          } else {
            if (inti < 0) {
              this.$showMessage('收款金额不足以清缴欠费，请核查，并重新输入收款金额！！')
              // this.data.f_collection = this.data.f_totalcost
              return
            }
          }
        }
        if (this.newOverdue > 0) {
          let inti = this.subNum(this.addNum(this.data.f_collection, this.data.f_balance), this.data.f_totalcost)
          console.log('===>', inti)
          if (this.floor) {
            if (inti < -1) {
              this.$showMessage('该户已产生违约金，必须全部进行清缴，请核查，并重新输入收款金额！！')
              return
            }
          } else {
            if (inti < 0) {
              this.$showMessage('该户已产生违约金，必须全部进行清缴，请核查，并重新输入收款金额！！')
              // this.data.f_collection = this.data.f_totalcost
              return
            }
          }
        }

        this.data.f_overdue = this.newOverdue
        this.data.isBreakOverdue = this.isBreakOverdue
        if (this.isBreakOverdue) {
          this.data.breakOverdue = this.breakOverdue
        }
        this.$showMessage(`确定对用户${this.row.f_user_name}进行机表缴费吗？`, ['confirm', 'cancel']).then(async (res) => {
          if (res === 'confirm') {
            // 先调用付款码支付组件流程
            let ss = await this.$refs.paymentcode.flowPath()
            this.$refs.paymentcode.paymentCodeShow = false
            console.log('付款码操作返回', ss)
            if (!ss.result) return
            machineChargeGen(this)
          }
        })
      },
      calOverdue () {
        this.data.f_totalcost = this.data.f_totalcost - (this.data.f_overdue - this.newOverdue)
        this.data.f_overdue = this.newOverdue
      },
      clean () {
        this.$dispatch('success', '机表收费', this.data)
        this.$info('取消操作')
      },
      validateBill (val) {
        this.validateOk = !val.isOk
        this.billData.bill = val.bill
      },
      async getGasMonth () {
        // 获取用气月份
        let condition1 = `f_userinfo_id = ${this.data.f_userinfo_id} and f_whether_pay='否' AND f_hand_state = '有效' and f_meter_state = '已抄表' AND f_oughtfee !=0 `
        let HttpReset = new HttpResetClass()
        let data = {
          items: 'f_input_date',
          tablename: 't_handplan',
          condition: condition1,
          orderitem: 'f_input_date desc'
        }
        let res = await HttpReset.load('POST', 'rs/sql/singleTable_OrderBy', { data: data }, {resolveMsg: null, rejectMsg: '获取用气月份失败!'})
        let date1,date2,previousMonth1,previousMonthDate1,previousMonth2,previousMonthDate2
        if (res.data.length > 1) {
          let len = res.data.length
          date1 = new Date(res.data[len - 1].f_input_date)
          date2 = new Date(res.data[0].f_input_date)
          previousMonthDate1 = new Date(date1.getFullYear(), date1.getMonth() - 1, date1.getDate())
          previousMonth1 = previousMonthDate1.getMonth() + 1
          previousMonthDate2 = new Date(date2.getFullYear(), date2.getMonth() - 1, date2.getDate())
          previousMonth2 = previousMonthDate2.getMonth() + 1
          this.gasMonth = (previousMonth1 < 10 ? '0' + previousMonth1 : previousMonth1) + '-' + (previousMonth2 < 10 ? '0' + previousMonth2 : previousMonth2)
          console.log("this.gasMonth=====》", this.gasMonth)
        } else if (res.data.length === 1) {
          date1 = new Date(res.data[0].f_input_date)
          previousMonthDate1 = new Date(date1.getFullYear(), date1.getMonth() - 1, date1.getDate())
          previousMonth1 = previousMonthDate1.getMonth() + 1
          this.gasMonth = (previousMonth1 < 10 ? '0' + previousMonth1 : previousMonth1) + '-' + (previousMonth1 < 10 ? '0' + previousMonth1 : previousMonth1)
          console.log("this.gasMonth=====》", this.gasMonth)
        }
      },
      printok () {
        this.bookData = {
          f_userinfo_id: this.row.f_userinfo_id,
          f_book_no: this.row.f_book_no,
          f_zzhh: this.row.f_zzhh,
          content: {
            f_operate_date: `'${this.$login.toStandardDateString()}'`,
            f_abstract: `'消费'`,
            f_gas_month: `'${this.gasMonth}'`,
            f_meter_base: `'${this.row.f_meter_base}'`,
            f_gas: `'${this.data.f_pregas}'`,
            f_money: `'${this.data.f_collection}'`,
            f_omoney: `'${this.newOverdue}'`,
            f_balance: `'${this.curbalance}'`,
            f_operator: `'${this.$login.f.name}'`
          }
        }
        this.print = false
        this.bookprint = true
      },
      printok2 () {
        this.$dispatch('success')
      },
      checkOverdue () {
        this.$nextTick(() => {
          this.newOverdue = this.data.f_overdue
          this.calOverdue()
        })
      },
      close () {
        this.print = false
        if (this.config.isPrintBook) {
          this.printok()
        } else {
          this.clean()
        }
      },
      closeBookPrint () {
        this.bookprint = false
        this.clean()
      },
      // 根据选择的付款方式 获取优惠列表
      async getPrivilegeList () {
        // 初始化下拉选择列表
        this.privilegeList = [{label: '无优惠', value: '0'}]
        // 初始为无优惠
        this.data.f_privilege_id = '0'
        if (this.data.f_payment && this.data.f_payment.length) {
          // 查询条件
          let payments = JSON.stringify(this.data.f_payment)
          payments = payments.replace('[', '(').replace(']', ')').replace(/"/g, '\'')
          let HttpReset = new HttpResetClass()
          let privilege = await HttpReset.load('POST', 'rs/sql/singleTable_OrderBy', {
            data: {
              items: 'id,f_privilege_name,f_privilege_type',
              tablename: 't_privilege',
              condition: `f_payment in ${payments} and f_gasproperties = '${this.row.f_gasproperties}' and f_user_type = '${this.row.f_user_type}' and f_perform_date <= GETDATE() and f_end_date >= GETDATE() and f_state = '有效'`,
              orderitem: 'id'
            }
          }, {resolveMsg: null, rejectMsg: '查询优惠信息失败'})
          // 查询结果放到下拉列表
          console.log('privilege.data======>',privilege.data)
          for (let p of privilege.data) {
            this.privilegeList.push({label: p.f_privilege_name, value: p.id, type: p.f_privilege_type})
          }
          this.privilegeCalculate()
        }
      },
      eticket_toggle () {
        this.eticket_show = false
        this.$dispatch('success')
      },
      // 优惠计算
      async privilegeCalculate () {
        // 初始化减免金额
        this.data.f_privilege_money = 0
        this.data.f_after_discount = this.data.f_collection
        // 判断是否是自定义优惠
        if (parseInt(this.data.f_privilege_id)) {
          for (let p of this.privilegeList) {
            if (p.value == this.data.f_privilege_id && p.type == '自定义') {
              this.data.f_privilege_money = window.prompt('请输入你想优惠的金额')
              if (!(/^[1-9]\d*(\.\d+)?$/).test(this.data.f_privilege_money) || !(/^[1-9]\d*(\.\d+)?$/).test(this.data.f_privilege_money)) {
                this.$showMessage('金额输入格式不正确!')
                this.data.f_privilege_money = 0
                return
              }
              if ((this.data.f_privilege_money - 0) >= this.data.f_collection) {
                this.$showMessage('减免金额不能大于等于收款金额')
                this.data.f_privilege_money = 0
                return
              }
            }
          }
        }
        // 优惠方式, 收款 缺一不计算
        if (this.data.f_payment && this.data.f_payment.length && parseInt(this.data.f_privilege_id) && this.data.f_collection) {
          let c = {
            f_privilege_id: this.data.f_privilege_id,
            f_collection: this.data.f_collection,
            f_privilege_money: this.data.f_privilege_money
          }
          let privilegeData = await this.$resetpost('rs/logic/calculatePrivilege', c, {resolveMsg: null, rejectMsg: '计算优惠金额出错'})
          // 减免金额
          this.data.f_privilege_money = privilegeData.data.f_privilege_money
          // 减免后收款金额
          this.data.f_after_discount = privilegeData.data.f_collection
        }
      },
      async speckText (str) {
        var url = 'http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&spd=6&text=' + encodeURI(str)
        await new Audio(url).play()
      }
    },
    watch: {
      'data.f_overdue' (val) {
        // this.data.f_last_overdue = this.newOverdue
        this.newOverdue = val
      },
      'splitAll' (val) {
        this.data.f_pregas = this.data.f_pregas - val
      },
      'invoice_show_gas' () {
        return this.row.f_collection_type === '按气量' ? '是' : '否'
      },
      'newOverdue' (val) {
        this.data.f_totalcost = (this.data.f_preamount - 0) + (val - 0)
        if (this.data.f_totalcost - this.data.f_balance > 0) {
          if (this.floor) {
            this.data.f_collection = Math.floor(this.data.f_totalcost - this.data.f_balance)
          } else if (this.ceil) {
            this.data.f_collection = Math.ceil(this.data.f_totalcost - this.data.f_balance)
          } else {
            this.data.f_collection = this.data.f_totalcost - this.data.f_balance
          }
        } else {
          this.data.f_collection = 0
        }
      },
      'data.f_payment' (val) {
        this.getPrivilegeList()
        // 根据付款方式增加业务单号
        if (val == '免交') {
          this.mjshow = true
        } else {
          this.mjshow = false
        }
      },
      async 'data.f_collection' (val) {
        if ((this.data.f_totalcost - 0) > (val - 0)) {
          if (this.authArr.includes('机表收费语音播报')) {
            await this.speckText('请注意，当前收款小于欠费')
          }
        }
        // 没获取优惠之前默认和收款一样,防止获取优惠太慢导致收款金额与实际收款不符
        this.data.f_after_discount = this.data.f_collection
        // 获取计算优惠
        this.getPrivilegeList()
      }
    },
    computed: {
      authArr () {
        return this.$login.r ? this.$login.r : []
      },
      curbalance () {
        if (((this.data.f_collection - 0) + (this.data.f_balance - 0)) > (this.data.f_totalcost - 0)) {
          return ((this.data.f_collection - 0) + (this.data.f_balance - 0) - (this.data.f_totalcost - 0)).toFixed(4)
        } else if (this.floor) {
          return ((this.data.f_collection - 0) + (this.data.f_balance - 0) - (this.data.f_totalcost - 0)).toFixed(4)
        } else {
          return 0
        }
      }
    }
  }
</script>
