<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" :class="[$v.payment.required ? 'has-error select-error' : '']">
            <label for="f_paytype" class=" font_normal_body">付款方式</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">
            <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">
            <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,2]" placeholder="应收金额" disabled>
          </div>

        </div>
        <div class="row" style="padding-top: 0.5em;">
          <div class="col-sm-4">
            <label for="f_pregas" class=" font_normal_body">&nbsp;&nbsp;&nbsp;用气量</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">
            <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">
            <label for="f_totalcost" class=" font_normal_body">应收金额</label>
            <input class="input_search" style="width:60%" 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">
            <label for="f_overdue" class="font_normal_body">&nbsp;&nbsp;&nbsp;违约金</label>
            <input class="input_search" style="width:60%"  type="number" v-model="newOverdue"
                   v-scale="[newOverdue,2]" placeholder="违约金" @blur="calOverdue()"
                   disabled>
            <button type="button" name="button" class="btn btn-link" @click="modefiy()" v-if="authArr.includes('滞纳金修改')">修改</button>
          </div>
          <div class="col-sm-4">
            <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" :class="[$v.f_collection.required || $v.f_collection.dctest ? 'has-error select-error' : '']">
            <label for="f_collection" class="font_normal_body">&nbsp;&nbsp;&nbsp;收款&nbsp;&nbsp;&nbsp;</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]"
                   @keyup.enter="confirm()">
          </div>
        </div>

        <div class="row" style="padding-top: 0.5em;">

          <div class="col-sm-12">
            <label for="f_comments" class="font_normal_body">&nbsp;&nbsp;&nbsp;备注&nbsp;&nbsp;&nbsp;</label>
            <input class="input_search" style="width:53.7%" 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%">
        <button class="button_search" @click="confirm()"  :disabled='!$v.valid || validateOk'>确认</button>
        <!--<button class="btn btn-success" @click="confirmUserinfo()"  :disabled='!$v.valid'>信息保存</button>-->
        <button class="button_clear" @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="close"><span>&times;</span></button>
        <h4 class="modal-title">修改滞纳金</h4>
      </header>
      <article slot="modal-body" class="modal-body">
        <div class="form-group">
          <label for="newOverdue" class="font_normal_body">原违约金</label>
          <input id="newOverdue" type="text" class="input_search" style="width:60%" style="width:60%" v-once v-model="newOverdue" disabled>
          <label for="editOverdue" class="font_normal_body">新违约金</label>
          <input id="editOverdue" type="text" class="input_search" style="width:60%" style="width:60%" v-model="editOverdue">
          <p v-if="showErrorMsg" class="text-danger">请输入新的违约金金额！</p>
        </div>
      </article>

      <footer slot="modal-footer" class="modal-footer">
        <button v-show="showOverdueModal" type="button" class="button_clear" @click='closeOverdue'>取消</button>
        <button v-show="showOverdueModal" type="button" class="button_search" @click='confirmOverdue()'>确认</button>
      </footer>
    </modal>
  </div>
</template>
<script>
  /**
   *售气收费
   *机表收费组件
   */

  let asyncMachineMeterCenter = async function (self){
    await self.$getConfig(self,'MachineMeterCenter')
    console.log('机表收费config', self.config)
    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 {
      let res = await self.$MachineChargeService.marchineCharge(self.data, self.row)
      console.log('机表收费返回id', res)
      // 开始打票
      if (self.config.hasPrint) {
        if (self.data.f_print.indexOf('普通收据') !== -1) {
          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 {
            self.data.id = res.data
            self.print = true
          }
        } else if (self.data.f_print[0] === '国税发票') {
          // TODO
        } else if (self.data.f_print[0] === '电子发票') {
          // TODO
        }
      } else {
        self.$dispatch('success')
      }
    } catch (error) {
      self.$showAlert(error, 'danger', 0)
      self.$dispatch('refresh')
    }
  }

  export default {
    title: '收费',
    data () {
      return {
        config: {
          hasPrint: false,  // 默认打票
          hasBillManage: false,  // 默认不启用发票管理
          billType: '燃气费',   // 票据类型（燃气费，其他费用，调用的发票代码不同）
          printType: '普通收据', // 收据/电子票/专用发票/国税发票
          payment: '现金缴费'
        },
        newOverdue: 0,
        print: false,
        isConfirm: true,
        show: false,
        billData: {
          url: 'rs/report/machine_bill',
          bill: ''
        },

        // 启用发票管理需要对票号进行验证
        hasValidateBill: false,
        validateOk: false,

        showOverdueModal: false,
        editOverdue: null,
        showErrorMsg: false,
        paytype: this.$appdata.getParam('付款方式') ? this.$appdata.getParam('付款方式') : [],
        printstyle: this.$appdata.getParam('打印格式') ? this.$appdata.getParam('打印格式') : []
      }
    },
    props: ['data', 'row'],
    ready () {
      this.data.f_last_overdue = this.data.f_overdue
      this.newOverdue = this.row.f_overdue_date ? this.row.f_overdue : this.data.f_overdue
      this.calOverdue()
      asyncMachineMeterCenter(this)
    },
    methods: {
      checkOverdue () {
        this.$nextTick(() => {
          this.newOverdue = this.row.f_overdue_date ? this.row.f_overdue : this.data.f_overdue
          this.calOverdue()
        })
      },
      modefiy () {
        this.showOverdueModal = true
      },
      confirmOverdue () {
        if (!this.editOverdue) {
          this.showErrorMsg = true
          return
        }
        this.newOverdue = this.editOverdue
        this.showErrorMsg = false
        let data = {
          f_overdue: this.newOverdue,
          f_user_id: this.data.f_user_id,
          f_userfiles_id:this.data.f_userfiles_id
        }
        console.log(data, 'data-overude')
        this.$resetpost('rs/logic/editOverdue', data).then(() => {
          this.showOverdueModal = false
          this.$dispatch('success', '机表收费')
        })
      },
      closeOverdue () {
        this.showOverdueModal = false
        this.editOverdue = null
        this.showErrorMsg = false
      },
      confirm () {
        this.data.f_overdue = this.newOverdue
        console.log(this.data.f_overdue, this.data.f_last_overdue, '滞纳金')
        // 未滞纳金修改添加，将修改的值，原因添加到this.data.logicmodel中
        // 如果有变更原因说明有变更
        if (this.f_cause && this.f_cause.length > 0) {
          this.data.f_paydelaypay = this.f_paydelaypay // 应缴滞纳金
          this.data.f_delaypay = this.f_delaypay // 实缴滞纳金
          this.data.f_cause = this.f_cause // 变更原因
        }
        this.$showMessage(`确定对用户${this.row.f_user_name}进行机表缴费吗？`, ['confirm', 'cancel']).then((res) => {
          if (res === 'confirm') {
            machineChargeGen(this)
          }
        })
      },
      calOverdue () {
        this.data.f_last_overdue = this.data.f_overdue
        this.data.f_lowest = this.data.f_lowest - (this.data.f_overdue - this.newOverdue)
        this.data.f_totalcost = this.data.f_totalcost - (this.data.f_overdue - this.newOverdue)
        this.data.f_overdue = this.newOverdue
        this.data.f_collection = this.data.f_totalcost
      },
      clean () {
        this.$dispatch('success', '机表收费', this.data)
        this.$info('取消操作')
      },
      validateBill (val) {
        this.validateOk = !val.isOk
        this.billData.bill = val.bill
      },
      printok () {
        this.$dispatch('success')
      },
      close () {
        this.print = false
        this.clean()
      },
      changeOverdue (val, reason) {
        this.$set('f_paydelaypay', this.newOverdue) // 应交滞纳金
        this.newOverdue = val // 实缴滞纳金
        this.$set('f_delaypay', this.newOverdue) // 实缴滞纳金
        this.$set('f_cause', this.reason) // 实缴滞纳金
        this.calOverdue()
      }
    },
    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
      }
    },
    computed: {
      authArr () {
        return this.$login.r ? this.$login.r : []
      },
      curbalance () {
        return ((this.data.f_collection - 0) + (this.data.f_balance - 0) - (this.data.f_totalcost - 0) - (this.newOverdue - 0)).toFixed(2)
      }
    }
  }
</script>
