<template>
  <div class="auto">
    <validator name='v'>
      <form novalidate class="form-horizontal">
        <div class="row" style="margin-top:10px;">

          <div class="col-sm-4 form-group" :class="[$v.f_pregas.required || $v.f_pregas.dctest? 'has-error' : 'has-success']">
            <label for="f_pregas" class=" font_normal_body">*超用气量</label>
            <input  class="input_search" style="width:60%" type="number"
                    v-validate:f_pregas='{required: true, dctest: [0, ">" ]}' v-model="model.f_pregas" v-scale = "[model.f_pregas, 4]">
          </div>

          <div class="col-sm-4 form-group">
            <label for="f_pregas" class=" font_normal_body">单&emsp;&emsp;价</label>
            <input  class="input_search" style="width:60%" type="number" v-model="model.f_price" v-scale = "[model.f_price, 4]" @blur="priceChange">
          </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="model.f_preamount.toFixed(4)" disabled>
          </div>
        </div>
        <div class="row" style="margin-top:10px;">
          <div class="col-sm-4 form-group">
            <label for="f_payment" class="font_normal_body">&nbsp;付款方式</label>
            <v-select id="f_payment"
                      v-model="model.f_payment"
                      placeholder='请选择'
                      :value.sync="model.f_payment"
                      :options='paytype'
                      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="f_print"
                      placeholder='请选择'
                      :multiple="mulPrint"
                      :value.sync="model.f_print"
                      :options='printstyle'
                      close-on-select clear-button>
            </v-select>
          </div>
          <!--<div class="col-sm-4 form-group" v-if="model.f_payment[0].includes('POS')">-->
          <!--<label for="f_voucher_number" class="font_normal_body">凭证号</label>-->
          <!--<input type="text" class="input_search col-sm-2" v-model="model.f_voucher_number" placeholder="凭证号">-->
          <!--</div>-->
          <!--<div class="col-sm-4 form-group" v-if="!model.f_payment[0].includes('POS')">-->
          <!--</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="model.f_totalcost.toFixed(4)" disabled>
          </div>
        </div>
        <div class="row" style="margin-top:10px;">
          <div class=" col-sm-4 form-group">
            <label for="f_totalcost" class=" font_normal_body">&nbsp;上期结余</label>
            <input  class="input_search" style="width:60%" type="number" v-model="row.f_balance" 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="f_curbalance" disabled>
          </div>
          <div  class="col-sm-4 form-group" :class="[$v.f_collection.required ? 'has-error' : 'has-success']">
            <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="model.f_collection"
                   v-validate:f_collection='{required: true, dctest: [model.f_totalcost.toFixed(4), ">=" ] }'
                   v-scale = "[model.f_collection, 4]">
          </div>
        </div>

        <div class="row" style="margin-top:10px;">
          <div class="col-sm-4 form-group" :class="[$v.f_serial_number.required || $v.f_serial_number.dctest ? 'has-error' : 'has-success']">
            <label for="f_serial_number" class="font_normal_body">&nbsp;业务单号</label>
            <input class="input_search" style="width:60%"  type="text" v-validate:f_serial_number='{required: true }'  @change="checkingOrder()"
                   v-model="model.f_serial_number" placeholder="业务单号">
          </div>
          <div class="col-sm-4 form-group" >
            <span v-if="prompts" style="color:red ">业务单号重复请重新输入</span>
          </div>
        </div>
        <div class="row" style="margin-top:5px;">
          <div class="col-sm-9">
          </div>
          <div class="col-sm-3">
            <span v-if="$v.f_collection.dctest" style="color:red ">收款不能小于应收金额</span>
          </div>
        </div>
        <div class="row" style="padding-top: 0.5em;">
          <div class="col-sm-12 form-group">
            <label for="f_comments" class="font_normal_body">&nbsp;备&emsp;&emsp;注</label>
            <input class="input_search" style="width:87%" v-model="model.f_comments" placeholder="备注"/>
          </div>
        </div>
        <div class="row" style="margin-top:10px;" v-if="calculatedetail">
          <div class="col-sm-4 form-group col-sm-offset-7">
            <strong>计算公式: {{calculatedetail}}</strong>
          </div>
        </div>
        <div class="row">
          <div class="col-sm-8">
            <strong style="color:blue">温馨提示: 若为阶梯价，只按照一阶进行计算，并不计入阶梯!!</strong>
          </div>
        </div>
      </form>
      <validate-bill v-if="hasValidateBill" :data="model" @validate-bill="validateBill"></validate-bill>
      <print-bill :show="print" :bill-config='config' :bill-data='billData' v-on:toggle="close" :data='row' @printok="printok" v-ref:printbill></print-bill>
      <div style="text-align:right;margin-top:30px;margin-right:50px;">
        <button class="button_search" @click="confirm()"  :disabled='!$v.valid || validateOk'>确认</button>
        <button class="button_clear" @click="clean()" >取消</button>
      </div>
    </validator>
  </div>
  <upload :blodid="blodid" v-if="config.showupload" isremark="true" fusetype="超用收费"></upload>
</template>
<script>
import {HttpResetClass} from 'vue-client'

/**
*综合业务
*超用收费组件
*/

let getOverUseGen = async function (self) {
  await self.$getConfig(self, 'OverUseCharge')
  console.log('超用config...', self.config)
  self.model.f_print = self.config.printType instanceof Array ? self.config.printType : [self.config.printType]
  self.model.f_payment = [self.config.payment]
  self.mulPrint = self.config.printType instanceof Array

  // 验证发票
  self.model.f_use_type = self.config.billType
  self.model.f_bill_type = self.model.f_print
  self.hasValidateBill = self.config.hasBillManage

  self.model = Object.assign({}, self.model, self.row)

  // 获取单价（阶梯使用一阶， 固定直接是固定）
  let res = await self.$CommonService.feeCalculate(self.model, 0)
  if (self.row.f_price_type == '固定气价') {
    self.model.f_price = res.data.chargeprice[0].f_price - 0
  } else if (self.row.f_price_type == '阶梯气价') {
    self.model.f_price = res.data.f_stair1price - 0
  }
}

// let overUseGasGen = async function (self) {
//   let res = await self.$CommonService.gasCalculate(self.model, self.model.f_pregas)
//
//   if (self.row.f_price_type == '固定气价') {
//     self.model.f_preamount = (res.data.chargenum - 0)
//     self.model.f_totalcost = self.model.f_balance > self.model.f_preamount ? 0 : self.model.f_preamount - self.model.f_balance
//     self.model.f_collection = self.model.f_totalcost
//     self.model.chargeprice = [{
//       f_price: (res.data.chargeprice[0].f_price - 0),
//       f_gas: self.model.f_pregas,
//       f_money: self.model.f_preamount,
//       f_price_name: '固定气价',
//       f_user_id: self.row.f_user_id,
//       f_userfiles_id: self.row.f_userfiles_id,
//       f_operate_date: self.$login.toStandardTimeString(),
//       f_state: '有效',
//       f_type: '超用收费'
//     }]
//     self.calculatedetail = res.data.chargeprice[0].f_price + ' x ' + self.model.f_pregas
//   } else if (self.row.f_price_type == '阶梯气价') {
//     self.model.f_preamount = (res.data.f_stair1price - 0) * (self.model.f_pregas - 0)
//     self.model.f_totalcost = self.model.f_balance > self.model.f_preamount ? 0 : self.model.f_preamount - self.model.f_balance
//     self.model.f_collection = self.model.f_totalcost
//     self.model.chargeprice = [{
//       f_price: (res.data.f_stair1price - 0),
//       f_gas: self.model.f_pregas,
//       f_money: self.model.f_preamount,
//       f_price_name: '阶梯1',
//       f_user_id: self.row.f_user_id,
//       f_userfiles_id: self.row.f_userfiles_id,
//       f_operate_date: self.$login.toStandardTimeString(),
//       f_state: '有效',
//       f_type: '超用收费'
//     }]
//     self.calculatedetail = res.data.f_stair1price + ' x ' + self.model.f_pregas
//   }
//
//
// }

let overChargeGen = async function (self) {
  try {
    // 组织价格明细
    self.model.chargeprice = [{
      f_price: (self.model.f_price - 0),
      f_gas: self.model.f_pregas,
      f_money: self.model.f_preamount,
      f_price_name: self.row.f_meter_type == '固定气价' ? '固定气价' : '阶梯1',
      f_user_id: self.row.f_user_id,
      f_userfiles_id: self.row.f_userfiles_id,
      f_operate_date: self.$login.toStandardTimeString(),
      f_state: '有效',
      f_type: '超用收费'
    }]

    let res = await self.$ChangeMeterService.overCharge(self.model, self.row)
    console.log('超用收费返回id', res)
    if (self.config.hasPrint) {
      if (self.model.f_print.indexOf('电子发票') == -1) {
        if (self.config.hasBillManage) {
          // 启用发票管理，获取票据管理中的票号并存储记录
          self.row.id = res.data.id
          self.row.f_bill_type = '超用收费'
          self.row.f_bill_style = self.model.f_print[0]
          self.print = true
        } else {
          self.row.id = res.data.id
          self.print = true
        }
      } else {
        if (self.model.f_print[0] === '电子发票') {
          self.$CommonService.openEticket(res.data.id, '超用收费')
          self.$dispatch('success')
        }
      }
    } else {
      self.$dispatch('success')
    }
  } catch (error) {
    self.$showAlert(error, 'danger', 0)
    self.$dispatch('refresh')
  }
}

export default {
  title: '超用收费',
  data () {
    return {
      config: {
        showupload: false, // 默认不显示附件
        hasPrint: false,  // 默认打票
        hasBillManage: false,  // 默认不启用发票管理
        billType: '燃气费',   // 票据类型（燃气费，其他费用，调用的发票代码不同）
        printType: '普通收据', // 收据/电子票/专用发票/国税发票
        payment: '现金缴费'
      },
      disable: false,
      total: 0,
      blodid: '',

      model: {
        f_pregas: '',
        f_price: 0,
        f_preamount: 0,
        f_totalcost: 0,
        f_collection: 0,
        f_balance: '',
        f_curbalance: '',
        f_payment: '现金缴费',
        f_print: [],
        f_voucher_number: '',
        f_comments: ''
      },
      // 本期结余
      f_curbalance: 0,

      cal: false,
      calculatedetail: '',

      oldprice: 0,

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

      billData: {
        url: 'rs/report/overuse_bill',
        bill: ''
      },
      print: false,

      mulPrint: false,
      paytype: this.$appdata.getParam('付款方式'),
      printstyle: this.$appdata.getParam('打印格式'),
      mjshow: false,
      prompts: ''
    }
  },
  props: ['row'],
  ready () {
    this.blodid = this.row.f_userinfo_id
    // 获取超用记录并赋值
    getOverUseGen(this)
  },
  methods: {
    async checkingOrder () {
      console.log('看看业务单号', this.model.f_serial_number, this.row)
      let http = new HttpResetClass()
      let temp = await http.load('post', 'rs/logic/serialnumberVerify', {data: {f_serial_number: this.model.f_serial_number}}, {resolveMsg: null, rejectMsg: null})
      console.log('看看返回值', temp)
      if (temp.data) {
        this.model.f_serial_number = ''
        this.prompts = '业务单号重复请重新输入'
      } else {
        this.prompts = ''
      }
    },
    confirm () {
      this.model.f_curbalance = this.f_curbalance
      overChargeGen(this)
    },
    clean () {
      this.$dispatch('refresh')
    },
    close () {
      this.showprint = false
      this.print = false
      this.clean()
    },
    printok () {
      // 收据打完，判断是否还有其他票据进行请求
      for (let i = 0; i < this.model.f_print.length; i++) {
        if (this.model.f_print[i] === '电子发票') {
          this.$CommonService.openEticket(this.row.id, '超用收费')
        }
      }
      this.$dispatch('success')
    },
    validateBill (val) {
      this.validateOk = !val.isOk
      this.billData.bill = val.bill
    },
    calPreamount () {
      this.model.f_preamount = (this.model.f_pregas - 0) * (this.model.f_price - 0)
      this.model.f_totalcost = this.model.f_balance > this.model.f_preamount ? 0 : (this.model.f_preamount - 0) - (this.model.f_balance - 0)
      this.model.f_collection = this.model.f_totalcost - 0
    },
    priceChange () {
      console.log('新旧价格', this.model.f_price, this.oldprice)
      if (this.model.f_price - this.oldprice < 0) {
        // 判断是否有超用价格修改权限
        if (!this.$login.r.includes('超用价格修改')) {
          this.$showAlert('您没有将该价格降低的权限！！', 'warning', 3000)
          this.model.f_price = this.oldprice
        }
      }
    }
  },
  watch: {
    'model.f_pregas' () {
      this.calPreamount()
    },
    'model.f_price' (newVal, oldVal) {
      this.oldprice = oldVal
      this.calPreamount()
    },
    'model.f_payment' (val) {
      // 根据付款方式增加业务单号
      if (val == '免交') {
        this.mjshow = true
      } else {
        this.mjshow = false
      }
    }
  },
  computed: {
    'f_curbalance' () {
      if (this.model.f_preamount) {
        return ((this.model.f_collection - 0) + (this.row.f_balance - 0) - (this.model.f_preamount - 0)).toFixed(4)
      } else {
        return this.model.f_balance
      }
    }
  }
}
</script>

<style>
</style>
