<template>
  <div id="BatchCharge">
    <div class="span" style="overflow-y: auto;">
      <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="data.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="data.overdue_all"
                     v-scale="[data.overdue_all,2]" placeholder="违约金" disabled>
            </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.oughtamount_all" placeholder="用气量"
                     v-scale="[data.oughtamount_all, 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%"  type="number" v-model="data.oughtfee_new_all"
                     v-scale = "[data.oughtfee_new_all, 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.oughtfee_all"
                     v-scale = "[data.oughtfee_all, 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-4 form-group" :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="!editCollection" v-el:paycode>
            </div>
          </div>

          <div class="row" style="padding-top: 0.5em;">
            <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>
        <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>
        <div class="text-right" style="margin-top: 1%">
          <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="confirm()"  :disabled='!$v.valid || validateOk'>确认</button>
          <button class="button_clear btn-gn" @click="clean()">取消</button>
        </div>
      </validator>
      <payment-code v-ref:paymentcode :payment="data.f_payment" :row="row" :money="data.f_after_discount"></payment-code>
    </div>
  </div>
  <modal :show.sync="show" v-ref:modal backdrop="false">
    <header slot="modal-header" class="modal-header text-center">
      <h4 class="modal-title">正在批量处理中, 请耐心等待...</h4>
    </header>
    <article slot="modal-body">
      <div class="progress" style="margin: 20px">
        <div class="progress-bar progress-bar-success progress-bar-striped active" :style="{width: `${percent}%`}">
          {{ percent }}
        </div>
      </div>
    </article>
    <footer slot="modal-footer" class="modal-footer">
    </footer>
  </modal>
</template>

<script>
import {HttpResetClass} from 'vue-client'

let asyncMachineMeterCenter = async function (self) {
  await self.$getConfig(self, 'BatchCharge')
  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
}
export default {
  name: 'BatchCharge',
  title: '团体缴费',
  data () {
    return {
      // 请求对象(批量导入,查询进度使用)
      HttpReset: new HttpResetClass(),
      timer: null,
      config: {
        showupload: true, // 显示上传
        ceilCollcition: false, // 是否向上取整
        hasPrint: true,  // 默认打票
        postAsync: false,  // 是否异步请求  存完主记录再存明细
        hasBillManage: false,  // 默认不启用发票管理
        hasfindaReail: true,  // 默认开启找零功能
        billType: '燃气费',   // 票据类型（燃气费，其他费用，调用的发票代码不同）
        printType: '普通收据', // 收据/电子票/专用发票/国税发票
        payment: '现金缴费'
      },
      print: false,
      billData: {
        url: 'rs/report/charge_manage_group_bill',
        bill: ''
      },
      paytype: this.$appdata.getParam('付款方式') ? this.$appdata.getParam('付款方式') : [],
      printstyle: this.$appdata.getParam('打印格式') ? this.$appdata.getParam('打印格式') : [],
      // 启用发票管理需要对票号进行验证
      hasValidateBill: false,
      validateOk: false,
      editCollection: false,
      // 收费进度
      show: false,
      percent: 0
    }
  },
  props: ['data', 'owe', 'civill'],
  beforeDestroy () {
    // 销毁定时器
    if (this.timer) clearInterval(this.timer)
  },
  ready () {
    this.paycodefocus()
    if (!this.$login.r.includes('免交充值付款')) {
      this.paytype = this.paytype.filter((item) => {
        return item.label != '免交'
      })
    }
    this.editCollection = !!this.civill
    this.data.f_collection = this.data.oughtfee_all - this.data.f_balance > 0 ? this.data.oughtfee_all - this.data.f_balance : 0
    if (this.config.ceilCollcition) {
      this.data.f_collection = Math.ceil(this.data.f_collection)
    }
    asyncMachineMeterCenter(this)
  },
  methods: {
    paycodefocus () {
      this.$nextTick(() => {
        this.$els.paycode.focus()
      })
    },
    /**
     * 用来进行小数相加的工具方法
     * @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 () {
      // if (this.owe.rows.length <= 0) {
      //   this.$showMessage('当前没有欠费！！')
      //   return
      // }
      // 如果有变更原因说明有变更
      if (this.data.f_collection < 0) {
        this.$showMessage('收款金额不能小于零！！')
        return
      }
      let inti = this.subNum(this.addNum(this.data.f_collection, this.data.f_balance), this.data.oughtfee_all)
      if (inti < 0) {
        this.$showMessage('收款金额不足以清缴欠费，请核查，并重新输入收款金额！！')
        return
      }
      let msg = '确定进行批量收费吗？'
      if (this.row) {
      }
      this.$showMessage(msg, ['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
          this.machineChargeGen()
        }
      })
    },
    async machineChargeGen () {
      let uuid = this.$login.guid()
      let param = {
        uuid: uuid,
        chargeUser: [],
        f_serial_id: this.$refs.paymentcode.paymentCodeReturnData.f_out_trade_no,
        f_balance: this.data.f_balance,
        f_curbalance: this.curbalance,
        f_pregas: this.data.oughtamount_all,
        f_preamount: this.data.oughtfee_new_all,
        f_delay: this.data.overdue_all,
        f_delaypay: this.data.overdue_all,
        f_collection: this.data.f_collection,
        f_payment: this.data.f_payment[0],
        f_print: this.data.f_print[0],
        f_comments: this.data.f_comments,
        operInfo: {
          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
        }
      }
      for (let row of this.owe.rows) {
        param.chargeUser.push({
          f_userinfo_id: row.f_userinfo_id,
          f_collection: row.f_oughtfee_all,
          f_oughtfee: row.f_oughtfee,
          f_oughtamount: row.f_oughtamount,
          min_handplan_id: row.min_handplan_id,
          max_handplan_id: row.max_handplan_id
        })
      }
      if (this.civill) {
        param = Object.assign(this.civill, param)
      }
      let batchId = ''
      // 如果配置了异步请求
      if (this.config.postAsync) {
        // 插入主收费记录
        let batch = await this.$resetpost('rs/logic/asyncbatchPaymentSellinggas', {data: param}, {resolveMsg: null, rejectMsg: null}, 1000)
        batchId = param.f_batch_id = batch.data.f_batch_id
        // 处理记录明细抄表明细
        // await this.$resetpost('rs/logic/async/asyncbatchPaymentFiles', {data: param}, {resolveMsg: null, rejectMsg: null}, 1000)
      } else {
        try {
          await this.$resetpost('rs/logic/batchPayment', {data: param}, {resolveMsg: null, rejectMsg: null}, 1000)
        } catch (e) {}
        // this.$showMessage(`正在批量处理中, 请耐心等待...`, [])
        this.show = true
        // 启动定时器定时查询处理结果
        this.timer = setInterval(async () => {
          let res = await this.HttpReset.load('POST', 'rs/logic/getBatchOperaPro', {data: {uuid: uuid}}, {resolveMsg: null, rejectMsg: null})
          if (res.data.percent) {
            this.percent = res.data.percent
          }
          if (res.data.msg || res.data.error) {
            this.show = false
            clearInterval(this.timer)
            this.$closeMessage()
            if (res.data.error) {
              this.$showAlert(`${res.data.error}`, 'danger')
              return
            }
            await this.$showMessage(res.data.msg)
            batchId = res.data.id
          }
        }, 1500)
      }
      if (this.config.hasPrint) {
        if (this.data.f_print.indexOf('电子发票') == -1) {
          console.log('this.config.hasBillManage', this.config.hasBillManage)
          if (this.config.hasBillManage) {
            // 启用发票管理，获取票据管理中的票号并存储记录
            this.row.id = batchId
            this.row.f_bill_type = '物联网收费'
            this.row.f_bill_style = this.model.f_print[0]
            this.print = true
          } else {
            this.data.id = batchId
            this.print = true
          }
        } else if (this.config.printType === '国税发票') {
          // TODO
        } else if (this.model.f_print[0] === '电子发票') {
          this.eticket_show = true
          await this.$refs.eticketbill.openETicket([batchId], this.row, this.invoice_show_gas, this.invoice_is_pax, '物联网收费')
        }
      } else {
        this.clean()
      }
    },
    clean () {
      this.$dispatch('success')
    },
    validateBill (val) {
      this.validateOk = !val.isOk
      this.billData.bill = val.bill
    },
    printok () {
      this.$dispatch('success')
    },
    close () {
      this.print = false
      this.clean()
    }
  },
  watch: {
  },
  computed: {
    curbalance () {
      if (((this.data.f_collection - 0) + (this.data.f_balance - 0)) > (this.data.oughtfee_all - 0)) {
        return ((this.data.f_collection - 0) + (this.data.f_balance - 0) - (this.data.oughtfee_all - 0)).toFixed(2)
      } else {
        return 0
      }
    }
  }
}
</script>

<style lang="less">

</style>
