<template>
  <div class="auto">
    <validator name='v'>
      <form novalidate class="form-horizontal">
        <p class="bg-info text-center" style="padding: 8px;">卡表收费</p>
        <div class="row">
          <div class="form-group form-input-group col-sm-4">
            <label for="f_paytype" class=" col-sm-2 control-label">付款方式:</label>
            <div class="col-sm-2">
              <v-select id="f_payment"
                        v-model="f_payment"
                        placeholder='请选择'
                        :value.sync="model.f_payment"
                        :options='paytype'
                        close-on-select clear-button></v-select>
            </div>
          </div>
          <div class="form-group form-input-group col-sm-4"
               :class="[$v.f_pregas.required || $v.f_pregas.dctest ? 'has-error' : 'has-success']">
            <label for="f_pregas" class=" col-sm-2 control-label">预购气量:</label>
            <input class="form-control col-sm-2" type="number"
                   @blur="pregas()" v-model="model.f_pregas"
                   v-validate:f_pregas='{required: true,  dctest: [maxgas, "<=" ]}' placeholder="预购气量"
                   v-next-el='sk' :disabled="row.f_collection_type !== '按气量'">
          </div>

          <div class="form-group form-input-group col-sm-4">
            <label for="f_preamount" class=" col-sm-2 control-label">预购金额:</label>
            <input class="form-control col-sm-2" type="number" v-model="model.f_preamount"
                   v-scale="[model.f_preamount, 2]" placeholder="预购金额" disabled>
          </div>
        </div>
        <div class="row" style="margin-top:6px;">
          <div class="form-group form-input-group col-sm-4" :class="[$v.printstyle.required ? 'select-error' : '']">
            <label for="f_print" class="control-label col-sm-2">打印格式:</label>
            <div class="col-sm-2">
              <input type="text" v-show="false" v-model="$refs.printstyle.selectedItems"  v-validate:printstyle='{required: true }'>
              <v-select id="print"
                        v-model="f_print"
                        placeholder='请选择'
                        :multiple="mulPrint"
                        :value.sync="model.f_print"
                        :options='printstyle'
                        close-on-select clear-button v-ref:printstyle>
              </v-select>
            </div>
          </div>
          <div class="form-group form-input-group col-sm-4">
            <label  class="col-sm-2 control-label">限购余气:</label>
            <div class="col-sm-2">
              <input class="form-control"  type="number" v-model="maxgas"
                     v-scale = "[maxgas, 2]" placeholder='限购余气' disabled>
            </div>
          </div>

          <div class="from-group  form-input-group col-sm-4"
               :class="[$v.f_totalcost.required || $v.f_totalcost.dctest ? 'has-error' : 'has-success']">
            <label for="f_temp_amount" v-if="row.f_collection_type === '按气量'"
                   class=" col-sm-2 control-label">应收金额:</label>
            <label for="f_temp_amount" v-if="row.f_collection_type === '按金额'"
                   class=" col-sm-2 control-label">本次缴费:</label>
            <input class="form-control col-sm-2" type="number"
                   @blur="preamount()" v-model="model.f_totalcost"
                   v-validate:f_temp_amount='{required: true, dctest: [0, ">" ] }' placeholder="应收金额"
                   v-next-el='sk' v-scale="[model.f_totalcost, 2]" :disabled="row.f_collection_type !== '按金额'">
          </div>
        </div>
        <div class="row">
          <div class="form-group form-input-group col-sm-4">
            <label for="f_balance" class=" col-sm-1 control-label">上期结余:</label>
            <input class="form-control col-sm-2" type="number" v-model="model.f_balance"
                   v-scale="[model.f_balance, 2]" placeholder="上期结余" disabled>
          </div>
          <div class="from-group form-input-group col-sm-4">
            <label for="f_curbalance" class="col-sm-1 control-label">本期结余:</label>
            <input class="form-control col-sm-2" type="number" v-model="curbalance"
                   v-scale="[model.f_curbalance, 2]" placeholder="本期结余" disabled>
          </div>

          <div class="form-group form-input-group col-sm-4" v-if="row.f_collection_type === '按气量'"
               :class="[$v.f_collection.required ? 'has-error' : 'has-success']">
            <label for="f_collection" class=" col-sm-2 control-label">收款:</label>
            <input id="f_collection" class="form-control col-sm-2" type="number" v-model="model.f_collection"
                   v-validate:f_collection='{required: true, dctest: [model.f_totalcost, ">=" ] }'
                   v-el:sk v-scale="[model.f_totalcost, 2]">
          </div>
          <div class="form-group form-input-group col-sm-4" v-if="row.f_collection_type === '按金额'">
            <label for="f_collection" class=" col-sm-2 control-label">收款:</label>
            <input id="f_collection" class="form-control col-sm-2" type="number" v-model="model.f_collection"
                   v-el:sk v-scale="[model.f_collection, 2]" disabled>
          </div>
        </div>
        <div class="row" style="margin-top:5px;">
          <div class="col-sm-9 form-input-group">
          </div>
          <div class="col-sm-3 form-input-group">
            <span v-if="$v.f_collection.dctest" style="color:red ">收款不能小于应收金额</span>
          </div>
        </div>
        <div class="row" v-if="model.f_payment[0].includes('POS')">
          <div class="form-group form-input-group col-sm-4">
            <label for="f_voucher_number" class="control-label col-sm-2">凭证号:</label>
            <input type="text" class="form-control col-sm-2" v-model="model.f_voucher_number" placeholder="凭证号">
          </div>
        </div>
        <div class="row">
          <div class="col-sm-4 col-sm-offset-8">
            <strong>计算公式:{{calculatedetail ? calculatedetail : ' 暂无'}}</strong>
          </div>
        </div>
        <div class="row">
          <div class="col-sm-5" v-if="row.f_collection_type === '按气量'">
            <strong style="color:blue">温馨提示: 此气表品牌是按气量收费!!</strong>
          </div>
          <div class="col-sm-4" v-if="row.f_collection_type === '按金额'">
            <strong style="color:blue">温馨提示: 此气表品牌是按金额收费!!</strong>
          </div>
        </div>
      </form>
      <print-bill :show="print" :bill-manager='config.hasBillManage' v-ref:printbill :bill-url='billUrl' v-on:toggle="close" @printok="printok" :data='row'></print-bill>
      <div style="text-align:right;margin-top:80px;margin-right:50px;">
        <button class="btn btn-success width-60" @click="confirm()" title="演示系统暂不支持" :disabled="true">确认</button>
        <button class="btn btn-default width-60" @click="clean()" style="width:80px;margin-left:20px;">取消</button>
      </div>
    </validator>
  </div>
</template>
<script>
  /**
   *综合业务
   *卡表收费组件
   */

  // 输入金额，换算气量
  let preamountGen = async function (self) {
    let calFee = (self.model.f_totalcost - 0) + (self.row.f_balance - 0)
    let getGas = await self.$CommonService.feeCalculate(self.model, calFee)
    if (getGas.data.gas) {
      if (self.row.f_isdecimal === '是') {
        if (self.row.f_alias === 'QiaoSong') {
          self.model.f_pregas = (getGas.data.gas - 0).toFixed(1)
        } else {
          self.model.f_pregas = (getGas.data.gas - 0).toFixed(2)
        }
      } else {
        self.model.f_pregas = (getGas.data.gas - 0)
      }
    }
    let getAmount = await self.$CommonService.gasCalculate(self.model, self.model.f_pregas)
    self.model.f_preamount = getAmount.data.chargenum
    self.model.chargeprice = getAmount.data.chargeprice
    Object.assign(self.model, self.model, getAmount.data)
    self.model.f_collection = self.model.f_totalcost
    self.calText(getAmount.data.chargeprice)
  }

  // 输入气量，换算金额
  let pregasGen = async function (self) {
    if (self.row.f_isdecimal === '是') {
      self.model.f_pregas = (self.model.f_pregas - 0).toFixed(2)
    } else {
      self.model.f_pregas = (self.model.f_pregas - 0).toFixed(0)
    }
    if ((self.model.f_pregas - 0) - (self.maxgas - 0) <= 0) {
      self.model.f_meter_type = self.row.f_meter_type
      let getAmount = await self.$CommonService.gasCalculate(self.model, self.model.f_pregas)
      self.model.f_preamount = getAmount.data.chargenum
      self.model.f_totalcost = (self.row.f_balance - 0) > (getAmount.data.chargenum - 0) ? 0 : ((getAmount.data.chargenum - 0) - (self.row.f_balance - 0)).toFixed(2)
      Object.assign(self.model, self.model, getAmount.data)
      self.model.chargeprice = getAmount.data.chargeprice
      self.model.f_collection = self.model.f_totalcost
      self.calText(getAmount.data.chargeprice)
    }
  }

  // 执行保存逻辑
  let sellgasGen = async function (self) {
    try {
      let res = await self.$CardService.sellgas(self.model, self.row, self.cardallot)
      console.log('卡表收费返回id', res)
      // 开始打票
      if (self.config.hasPrint) {
        if (self.model.f_print.indexOf('普通收据') !== -1) {
          if (self.config.hasBillManage) {
            // 启用发票管理，获取票据管理中的票号并存储记录
            self.row.id = res
            self.row.f_bill_type = '卡表收费'
            self.row.f_bill_style = self.model.f_print[0]
            self.row.f_preamount = self.model.f_preamount
            self.row.f_collection = self.model.f_collection
            self.billUrl = 'rs/report/card_bill'
            self.print = true
          } else {
            self.row.id = res
            self.billUrl = 'rs/report/card_bill'
            self.print = true
          }
        } else {
          if (self.model.f_print[0] === '电子发票') {
            self.$CommonService.openEticket(res, '售气收费')
            self.$dispatch('success')
          }
        }
      } else {
        self.$dispatch('success')
      }
      self.clickConfirm = false
    } catch (error) {
      self.$showAlert(error, 'danger', 0)
      self.$dispatch('refresh')
      self.clickConfirm = false
    }
  }

  let asyncCardMeterCenter = async function(self){
    await self.$getConfig(self,'CardMeterCenter')
    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
    // 判断限购
    if ((self.row.f_limit_cycle && self.row.f_limit_gas) && ((self.row.f_limit_cycle - 0) > 0 && (self.row.f_limit_gas - 0) > 0)) {
      let getMaxGas = await self.$resetpost('rs/sql/getremainingras', {data:{singlemouth: self.row.f_limit_cycle, singleGas: self.row.f_limit_gas,f_user_id: self.row.f_user_id}},{resolveMsg: null, rejectMsg: '获取限购异常!!'})
      console.log('限购值', getMaxGas)
      self.maxgas = getMaxGas.data[0].f_remaining_gas
    }
  }
  export default {
    title: '卡表收费',
    data() {
      return {
        config: {
          hasPrint : true,  //默认打票
          hasBillManage :false,  //默认不启用发票管理
          printType: '普通收据', // 收据/电子票/专用发票/国税发票
          payment: '现金缴费'
        },
        model: {
          f_purchase: 0,
          f_payment: '现金缴费',
          f_pregas: '',
          f_preamount: 0,
          f_totalcost: 0,
          f_curbalance: 0,
          f_collection: '',
          f_balance: 0,
          f_print: [],
          f_meter_type: '',
          f_voucher_number: ''
        },
        calculatedetail: '',
        print: false,
        billUrl: '',
        maxgas: 99999, // 限购

        mulPrint: false,
        clickConfirm: false, // 控制确认按钮只能点击一次
        // 下拉框值
        paytype: this.$appdata.getParam('付款方式'),
        printstyle: this.$appdata.getParam('打印格式')
      }
    },
    props: ['row'],
    ready() {
      // this.getPurchase()
      this.model.f_price_id = this.row.f_price_id
      this.model.f_user_id = this.row.f_user_id
      this.model.f_userinfo_id = this.row.f_userinfo_id
      this.model.f_balance = this.row.f_alias === 'QiaoSong' ? Math.trunc(this.row.f_balance) : this.row.f_balance
      asyncCardMeterCenter(this)
    },
    methods: {
      confirm() {
        this.clickConfirm = true
        this.model.f_curbalance = this.curbalance
        sellgasGen(this)
      },
      clean() {
        this.$info('取消操作')
        this.$dispatch('refresh', this.row)
      },
      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')
      },
      pregas() {
        if (this.model.f_pregas && this.model.f_pregas > 0) {
          try {
            pregasGen(this)
          } catch (error) {
            this.$showAlert(`发卡售气划价错误，错误类型：${error}`, 'danger', 0)
            this.$dispatch('error', '发卡售气', this.model, error)
          }
        }
      },
      preamount() {
        if (this.model.f_totalcost && this.model.f_totalcost > 0) {
          try {
            preamountGen(this)
          } catch (error) {
            this.$showAlert(`发卡售气划价错误，错误类型：${error}`, 'danger', 0)
            this.$dispatch('error', '发卡售气', this.model, error)
          }
        }
      },
      calText(val) {
        let str = ''
        val.forEach((item) => {
          str = str + item.f_price + ' x ' + item.f_gas + '+'
        })
        str = str.slice(0, str.length - 1)
        this.calculatedetail = str
      },
      close() {
        this.showprint = false
        this.print = false
        this.clean()
      }
    },
    computed: {
      'curbalance'() {
        if (this.model.f_preamount) {
          if (this.row.f_collection_type === '按金额') {
            return ((this.model.f_totalcost - 0) + (this.row.f_balance - 0) - (this.model.f_preamount - 0)).toFixed(2)
          } else {
            if ((this.row.f_balance - 0) > (this.model.f_preamount - 0)) {
              return ((this.row.f_balance - 0) - (this.model.f_preamount - 0)).toFixed(2)
            } else {
              return ((this.model.f_collection - 0) - (this.model.f_totalcost - 0)).toFixed(2)
            }
          }
        } else {
          return 0
        }
      }
    }
  }
</script>

<style>
</style>
