<template>
  <div class="flex-row">
    <div class="span" style="overflow-y: hidden">
      <validator name='v'>
        <form novalidate class="form-horizontal">
          <div class="row">
            <div class="col-sm-4" :class="[$v.payment.required ? 'has-error' : '']">
              <label class=" font_normal_body" title="参数名称：付款方式">收款方式</label>
              <input type="text" v-show="false" v-model="$refs.payment.selectedItems"
                     v-validate:payment='{required: true }'>
              <v-select v-model="f_payment"
                        placeholder='请选择'
                        :value.sync="model.f_payment"
                        :options='paytype' clear-button v-ref:payment></v-select>
            </div>

            <div class="col-sm-4" v-if="row.f_collection_type == '按气量'"
                 :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"
                     @blur="pregas()" v-model="model.f_pregas" v-el:fpregas
                     v-validate:f_pregas='{required: true, dctest: [maxgas, "<=" ]}' placeholder="预购气量"
                     v-next-el='fcollection'>
            </div>
            <div class="col-sm-4" v-if="row.f_collection_type == '按金额'">
              <label for="f_pregas" class=" font_normal_body">*预购气量</label>
              <input class="input_search" style="width:60%" type="number" v-el:fpregas
                     @blur="pregas()" v-model="model.f_pregas" placeholder="预购气量"
                     v-next-el='fcollection'>
            </div>
            <div class="col-sm-4"
                 :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"
                     @blur="preamount()" v-model="model.f_preamount"
                     v-validate:f_preamount='{required: true, dctest: [maxmoney, "<=" ],dctest: [0, ">"]}' placeholder="预购金额"
                     v-next-el='fcollection'>
            </div><!--
            <div class="col-sm-4" v-if="row.f_collection_type == '按气量'">
              <label for="f_preamount" class=" font_normal_body">&nbsp;预购金额</label>
              <input class="input_search" style="width:60%" type="number" v-model="model.f_preamount"
                     v-scale="[model.f_preamount, 4]" placeholder="预购金额" disabled>
            </div>-->

          </div>
          <div class="row" style="margin-top:6px;">
            <div class="col-sm-4" :class="[$v.printstyle.required ? 'has-error' : '']">
              <label for="f_print" class="font_normal_body">打印格式</label>
              <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 class="col-sm-4 " v-if="hasLimit&&limitgas">
              <label class="font_normal_body">&ensp;购气上限</label>
              <input class="input_search" style="width:60%" style="width:60%" type="number" v-model="maxgas"
                     v-scale="[maxgas, 4]" placeholder='限购余气' disabled>
            </div>
            <div class="col-sm-4 form-group" v-if="hasLimit&&limitmoney">
              <label class="font_normal_body">金额上限</label>
              <input class="input_search" style="width:60%" style="width:60%" type="number" v-model="maxmoney"
                     v-scale="[maxmoney, 2]" placeholder='限购金额' disabled>
            </div>
            <div class="col-sm-4" v-if="!hasLimit">
            </div>

            <div class="col-sm-4"
                 :class="[$v.f_totalcost.required || $v.f_totalcost.dctest ? 'has-error' : 'has-success']">
              <label for="f_temp_amount"
                     class=" font_normal_body">&nbsp;应收金额</label>
              <input class="input_search" style="width:60%" type="number"
                     @blur="preamount()" v-model="model.f_totalcost"
                     v-validate:f_totalcost='{required: true, dctest: [0, ">=" ] }' placeholder="应收金额"
                     v-next-el='fcollection' v-scale="[model.f_totalcost, 4]" disabled>
            </div>
          </div>
          <div class="row">

            <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="model.f_balance"
                     v-scale="[model.f_balance, 4]" placeholder="上期结余" disabled>
            </div>

            <div class="col-sm-4">
              <label for="f_curbalance" class="font_normal_body">&nbsp;本期结余</label>
              <input class="input_search" style="width:60%" type="number" v-model="curbalance"
                     v-scale="[curbalance, 4]" placeholder="本期结余" disabled>
            </div>

            <div class="col-sm-3" v-if="row.f_collection_type === '按气量' && model.f_payment!='赠气'"
                 :class="[$v.f_collection.required  || $v.f_collection.dctest ? 'has-error' : 'has-success']">
              <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="model.f_collection"
                     v-validate:f_collection='{required: true, dctest: [(model.f_totalcost - 0), ">=" ] }'
                     v-el:fcollection @keyup.enter="checkInvoiceMsg((!$v.valid || validateOk || !islegal || clickConfirm))" v-scale="[model.f_totalcost, 4]" :disabled="$refs.givechange.promptText != ''">
            </div>
            <div class="col-sm-3" v-if="row.f_collection_type === '按气量' && model.f_payment=='赠气'"
                 :class="[$v.f_collection.required  || $v.f_collection.dctest ? 'has-error' : 'has-success']">
              <label for="f_collection" class=" font_normal_body"><font size="4px" style="font-weight:bold">*收&emsp;款</font></label>
              <input id="f_collection" class="input_search" style="width:60%;font-size: 18px;font-weight:bold;" type="number" v-model="model.f_collection"
                     v-el:fcollection @keyup.enter="checkInvoiceMsg((!$v.valid || validateOk || !islegal || clickConfirm))" v-scale="[model.f_totalcost, 4]" :disabled="$refs.givechange.promptText != ''">
            </div>
            <div class="col-sm-3" v-if="row.f_collection_type === '按金额'">
              <label for="f_collection" class=" font_normal_body"><font size="4px" style="font-weight:bold">*收&emsp;款</font></label>
              <input id="f_collection" class="input_search" style="width:50%;font-size: 18px;font-weight:bold;" type="number" v-model="model.f_collection"
                     v-el:fcollection @keyup.enter="checkInvoiceMsg((!$v.valid || validateOk || !islegal || clickConfirm))" v-scale="[model.f_collection, 4]" :disabled="$refs.givechange.promptText != ''">
            </div>
            <div class="col-sm-1 form-group">
              <give-change :curbalance="curbalance" :collection.sync="model.f_collection" v-ref:givechange></give-change>
            </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="margin-top:5px;" v-show="authArr.includes('优惠权限')">
            <div class="col-sm-4">
              <label class="font_normal_body">优惠方式</label>
              <v-select v-model="model.f_privilege_id" @blur.native.capture="privilegeCalculate"
                        placeholder='请选择'
                        :value.sync="model.f_privilege_id"
                        :options='privilegeList' clear-button value-single>
              </v-select>
            </div>
            <div class="col-sm-4">
              <label for="f_preamount" class=" font_normal_body">&nbsp;优惠金额</label>
              <input class="input_search" style="width:60%" type="number" v-model="model.f_privilege_money"
                     v-scale="[model.f_privilege_money, 2]" placeholder="优惠金额" disabled>
            </div>
            <div class="col-sm-4">
              <label for="f_preamount" class=" font_normal_body">&nbsp;实际收款</label>
              <input class="input_search" style="width:60%" type="number" v-model="model.f_after_discount"
                     v-scale="[model.f_after_discount, 2]" placeholder="优惠后收款" disabled>
            </div>
          </div>

          <div class="row" v-if="model.f_payment[0].includes('POS')">
            <div class="col-sm-4">
              <label for="f_voucher_number" class="font_normal_body">凭证号</label>
              <input type="text" class="input_search" style="width:60%" v-model="model.f_voucher_number"
                     placeholder="凭证号">
            </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="model.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="model.f_serial_number" placeholder="业务单号">
            </div>


            <div class="col-sm-8">
              <label for="f_comments" class="font_normal_body">&nbsp;备&emsp;&emsp;注</label>
              <input class="input_search" style="width:77%" v-model="model.f_comments" rows="1" placeholder="备注">
            </div>
          </div>

          <div v-if="paymentModel.length >1">
            <div class="row" style="margin-top:10px;">
              <p class="col-sm-2 text-left" style="padding: 10px;"><img src="../../../static/juxing.png"/><strong
                style="margin-left: 4%">付款明细</strong></p>
            </div>
            <div class="row" style="margin-top:10px;">
              <div class="col-sm-4 " v-for="pay in paymentModel">
                <label class="font_normal_body">{{pay.f_payment}}:</label>
                <input id="f_money" type="text" class="input_search" style="width:60%" v-model="pay.f_money">
              </div>
              <div class="col-sm-4 ">
                <strong v-if="!islegal" style="color: red">所输入的金额必须等于收款金额</strong>
              </div>
            </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' :data='row' @toggle="close"
                    @printok="printok" v-ref:printbill></print-bill>
        <div style="text-align:right; height: 25%">
          <strong style="color:red;margin-right: 5px">{{ $refs.givechange.promptText }}</strong>
          <strong style="font-size: large" v-if="!config.notShowFormula">计算公式:{{calculatedetail ? calculatedetail : ' 暂无'}}</strong><br/>
          <payment-code-button :clickable="!$v.valid || validateOk || !islegal || clickConfirm"
                               :payment.sync="model.f_payment" :payment-data="paytype"
                               @confirm-payment="confirm()">
          </payment-code-button>
          <button class="button_search btn-gn" type="submit" @click="checkInvoiceMsg()"
                  :disabled='!$v.valid || validateOk || !islegal || clickConfirm'>确认
          </button>
          <button class="button_clear btn-gn" @click="clean()">取消</button>
        </div>
      </validator>
      <eticket-modal :show="eticket_msg" @closemodalshow="eticket_msg = false" :row="row" @confirm="confirm"></eticket-modal>
      <ticket-print  :show="eticket_show" @toggle="eticket_toggle"  v-ref:eticketbill></ticket-print>
      <payment-code v-ref:paymentcode :payment="model.f_payment" :row="row" :money="model.f_after_discount"></payment-code>
    </div>
  </div>
  <upload :blodid="row.f_userinfo_id" v-if="config.showupload" isremark="true" fusetype="卡表收费"></upload>
</template>
<script>
  import {HttpResetClass} from 'vue-client'
  import CardService from './CardService'
  /**
   *综合业务
   *卡表收费组件
   */

    // 输入金额，换算气量
  let preamountGen = async function (self) {
    let calFee = ((self.model.f_preamount - 0)).toFixed(4)
    if (self.model.f_payment == '赠气') {
      calFee = (self.model.f_preamount - 0).toFixed(4)
    }
      // 通过金额进行划价
    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(4)
        }
        if (self.row.f_collection_type === '按金额') {
          self.dymoney = 0
        } else {
          if (self.row.f_meter_brand !== '秦川IC卡表') {
            let dymoney2 = await self.$CommonService.gasCalculate(self.model, (getGas.data.gas - 0).toFixed(4))
            self.dymoney = (getGas.data.chargenum - 0).toFixed(4) - (dymoney2.data.chargenum - 0).toFixed(4)
          }
        }
      } else {
          // 如果不支持小数,将划价出的多余非整数气量进行划价为金额
        let tempnum = Math.floor(getGas.data.gas - 0)
        let dymoney1 = await self.$CommonService.gasCalculate(self.model, (tempnum).toFixed(4))
        self.dymoney = (getGas.data.chargenum - 0).toFixed(2) - (dymoney1.data.chargenum - 0).toFixed(2)
        self.model.f_pregas = Math.floor(getGas.data.gas - 0)
      }
    }
    self.model.f_totalcost = ((self.row.f_balance - 0) >= (self.model.f_preamount - 0) ? 0 : (self.model.f_preamount - 0 - self.row.f_balance))

    self.model.chargeprice = getGas.data.chargeprice
    Object.assign(self.model, self.model, getGas.data)
    if (self.model.f_payment == '赠气') {
      self.model.f_totalcost = self.model.f_preamount
      self.model.f_collection = 0
    } else {
      self.model.f_collection = self.config.autoCollection ? self.model.f_totalcost : 0
      self.model.f_totalcost = ((self.model.f_totalcost - 0) - (self.dymoney - 0)).toFixed(4)
    }
    self.model.f_preamount = (calFee - (self.dymoney - 0)).toFixed(4)
    self.calText(getGas.data.chargeprice)
  }

  // 输入气量，换算金额
  let pregasGen = async function (self) {
    if (self.row.f_isdecimal === '是') {
      self.model.f_pregas = (self.model.f_pregas - 0).toFixed(4)
    } 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(4))
      Object.assign(self.model, self.model, getAmount.data)
      self.model.chargeprice = getAmount.data.chargeprice
      if (self.model.f_payment == '赠气') {
        self.model.f_totalcost = getAmount.data.chargenum
        self.model.f_collection = 0
      } else {
        self.model.f_collection = self.config.autoCollection ? self.model.f_totalcost : 0
        if (self.config.floor) {
          self.model.f_collection = Math.ceil(self.model.f_collection)
        }
      }
      self.calText(getAmount.data.chargeprice)
    }
  }
  // 执行保存逻辑
  let sellgasGen = async function (self) {
    try {
      self.row.cardInfo = self.cardData

      if (self.paymentModel.length === 0) {
        self.paymentModel = [{
          f_payment: self.model.f_payment[0],
          f_money: self.model.f_preamount
        }]
      }
      self.model.xiekamoney = self.model.f_preamount
      if (self.row.f_price_type == '阶梯气价' && self.row.f_is_step == '否' && self.row.f_collection_type == '按金额') {
        self.model.xiekamoney = (self.model.f_pregas * self.model.chargeprice[0].f_price)
        self.model.xiekamoney = self.model.xiekamoney.toFixed(4)
      }

      self.model.payments = self.paymentModel
      // 加入扫码盒付款码支付流水号
      self.model.f_serial_id = self.$refs.paymentcode.paymentCodeReturnData.f_out_trade_no
      let res = await CardService.sellgas(self.model, self.row)
      let localeSustainMoney = window.localStorage.getItem('sustainMoney')
      if (localeSustainMoney != null) {
        localeSustainMoney = (localeSustainMoney - 0) + (self.model.f_collection - 0)
        window.localStorage.setItem('sustainMoney', localeSustainMoney)
      }
      let param = []
      for (let row of self.resid) {
        param.push({id: row.id})
      }
      let writeid
      if (res.data && res.data.id) {
        writeid = res.data.id
      } else {
        writeid = res
      }
      let data = {
        param: param,
        f_blobid: writeid
      }

      await self.$resetpost('rs/logic/updatefiles', data)
      console.log(self.config, self.config.hasPrint && !self.$login.r.includes('不打印发票'))
      // 开始打票
      if (self.config.hasPrint && !self.$login.r.includes('不打印发票')) {
        if (self.model.f_print.indexOf('电子发票') == -1) {
          if (self.$login.r.includes('非民用纸质票据拆分')) {
            if (self.row.f_user_type === '非民用') {
              self.billData.url = 'rs/report/fmy_card_bill'
            }
          }
          if (self.config.hasBillManage) {
            // 启用发票管理，获取票据管理中的票号并存储记录
            self.row.id = res
            self.row.f_bill_type = '卡表收费'
            self.row.f_bill_style = self.model.f_print[0]
            self.print = true
          } else {
            self.row.id = res
            self.print = true
          }
        } else {
          if (self.model.f_print[0] === '电子发票') {
            self.row.id = res
            self.eticket_show = true
            // 应铜川需要卡表显示
            await self.$refs.eticketbill.openETicket([res], self.row, '是', self.invoice_is_pax, '购气收费')
          }
        }
      } else {
        self.$dispatch('success')
      }
      self.clickConfirm = false
    } catch (error) {
      console.log('捕获到异常', error)
      if (error instanceof Object) {
        self.$showAlert(error.data, 'danger', 0)
      } else {
        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)

    // 添加 “系统余额透支” 付款方式
    let i = -1
    for (const index in self.paytype) {
      if (self.paytype[index].value == '系统余额透支') {
        i = index
        break
      }
    }
    if (self.canOverdraftBalance()) {
      if (i == -1) {
        self.paytype.push({
          label: '系统余额透支',
          value: '系统余额透支'
        })
      }
    } else {
      if (i != -1) {
        self.paytype.splice(i, 1)
      }
    }

    // 默认打印格式
    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

    // 判断限购
    let limit_param = {
      f_userinfo_id: self.row.f_userinfo_id,
      f_user_id: self.row.f_user_id,
      f_stairprice_id: self.row.f_stairprice_id
    }
    let getLimit = await self.$resetpost('rs/logic/sale_getLimitGas', {data: limit_param}, {
      resolveMsg: null,
      rejectMsg: '获取限购值失败！！'
    })
    console.log('获取限购值', getLimit)
    self.hasLimit = getLimit.data.hasLimit
    if (self.hasLimit) {
      if (getLimit.data.f_limit_value || getLimit.data.f_limit_amount) {
        if (getLimit.data.f_limit_value < 0 && getLimit.data.f_limit_amount < 0) {
          self.$showAlert(`${getLimit.data.msg}`, 'warning', 3000)
          self.$dispatch('refresh')
        } else {
          if (getLimit.data.f_limit_value) {
            self.maxgas = (getLimit.data.f_limit_value - 0)
            self.limitgas = true
          }
          if (getLimit.data.f_limit_amount) {
            self.maxmoney = (getLimit.data.f_limit_amount - 0)
            self.limitmoney = true
          }
        }
      }
    }
    let nowrite_param = {
      f_userfiles_id: self.row.f_userfiles_id
    }
    let getNoWriteCard = await self.$resetpost('rs/sql/getnowritecard', {data: nowrite_param}, {
      resolveMsg: null,
      rejectMsg: '获取最近卡表收费记录失败！！'
    })
    if (getNoWriteCard.data.length > 0) {
      self.$showMessage(`三小时内存在写卡失败的记录，是否重新写卡？`, ['confirm', 'cancel']).then(async (res) => {
        if (res === 'confirm') {
          let url = 'http://127.0.0.1:8003/' + getNoWriteCard.data[0].f_cardpost
          let param = JSON.parse(getNoWriteCard.data[0].f_cardparam)
          let cardRes = await self.$resetpost(url, param, {resolveMsg: null, rejectMsg: '重新写卡失败'})
          if (cardRes.data.Err || cardRes.data.Exception) {
            self.$showAlert(`卡服务错误：${cardRes.data.Err}${cardRes.data.Exception}，请联系开发人员处理！！`, 'danger', 3000)
            self.$dispatch('refresh', self.row)
          } else {
            self.$resetpost('rs/logic/writeCardAgin', getNoWriteCard.data[0], {resolveMsg: '重新写卡成功', rejectMsg: '重新写卡失败'})
            self.$dispatch('success')
          }
        } else {
          self.$dispatch('refresh', self.row)
        }
      })
    }
  }
  export default {
    title: '卡表收费',
    data () {
      return {
        mjshow: false,
        serialShow: false,
        resid: [],  // 存放新增的f_files表中id
        config: {
          notShowFormula: false, // 不显示计算公式,默认显示
          autoCollection: true, // 自动填写收款
          showupload: true, // 显示上传
          hasPrint: true,  // 默认打票
          hasBillManage: false,  // 默认不启用发票管理
          billType: '燃气费',   // 票据类型（燃气费，其他费用，调用的发票代码不同）
          printType: '普通收据', // 收据/电子票/专用发票/国税发票
          payment: '现金缴费',
          floor: false,
          overdraftBalance: false // 是否支持系统余额透支
        },
        eticket_msg: false,
        eticket_show: false,
        invoice_is_pax: '不征税',
        is_pax: [{label: '征税', value: '征税'}, {label: '不征税', value: '不征税'}],
        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: '',
          f_banktransfer_person: '',
          f_banktransfer_date: '',
          f_privilege_id: 0,
          f_privilege_money: 0,
          f_after_discount: 0
        },
        calculatedetail: '',

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

        print: false,
        billData: {
          url: 'rs/report/card_bill',
          billnumber: ''
        },
        hasLimit: false,
        maxgas: 99999999, // 限购
        maxmoney: 99999999,
        limitmoney: false,
        limitgas: false,

        paymentModel: [], // 多笔付款方式

        mulPrint: false,
        clickConfirm: false, // 控制确认按钮只能点击一次
        // 下拉框值
        paytype: [],
        printstyle: this.$appdata.getParam('打印格式'),
        privilegeList: [{label: '无优惠', value: '0'}],
        BankTransfer: false,
        // 小数是否支持,导致划价产生的多余气量,金额
        dymoney: 0
      }
    },
    props: ['row', 'cardData'],
    async ready () {
      if (this.authArr.includes('余额写卡限定')) {
        this.paytype = [{label: '余额写卡', value: '余额写卡'}]
      } else {
        this.paytype = await this.$appdata.getParam('付款方式') ? await this.$appdata.getParam('付款方式') : []
        if (!this.$login.r.includes('免交充值付款')) {
          this.paytype = this.paytype.filter((item) => {
            return item.label != '免交'
          })
        }
      }
      // 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_userfiles_id = this.row.f_userfiles_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
      if (this.row.f_collection_type == '按金额') {
        this.model.f_preamount = ''
        this.model.f_pregas = 0
      }
      this.$els.fpregas.focus()
      asyncCardMeterCenter(this)
    },
    watch: {
      'model.f_payment.length' (val) {
        console.log('付款方式多选。。', val)
        if (val > 1 && !this.model.f_preamount) {
          this.model.f_payment = ['现金缴费']
          this.$showAlert('请先计算付款金额', 'warning', 2000)
        } else {
          this.paymentModel = []

          this.model.f_payment.forEach((res) => {
            let temp = {
              f_payment: res,
              f_money: 0
            }
            this.paymentModel.push(temp)
          })
          this.$resetValidation()

          // 获取计算优惠
          this.getPrivilegeList()
        }
      },
      'model.f_payment' (val) {
        if (val == '免交') {
          this.mjshow = true
        } else if (val == '赠气' && (this.model.f_preamount || this.model.f_preamount != '')) {
          if (this.row.f_collection_type == '按气量') {
            this.pregas()
          } else {
            this.preamount()
          }
        } else {
          this.mjshow = false
        }
        // if(this.row.f_collection_type == '按气量'){
        //   this.pregas();
        // }else{
        //   this.preamount();
        // }
      },
      'model.f_collection' (val) {
        // 获取计算优惠
        this.getPrivilegeList()
      }
    },
    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: ''})
      }
    },
    methods: {
      // 校验发票信息
      checkInvoiceMsg (flag) {
        // 校验是否超出最大透支余额
        if (this.model.f_payment == '系统余额透支') {
          const maxOverdraftBalance = -(this.$appdata.getSingleValue('最大透支余额') - 0)
          const curSysBalance = (this.row.f_sys_balance - 0) - (this.model.f_totalcost - 0)
          if (curSysBalance < maxOverdraftBalance) {
            this.$showAlert('您的系统余额将超出最大透支余额，请使用别的付款方式！', 'danger', 5000)
            return
          }
          this.model.f_sys_balance = curSysBalance
        }

        // 收款回车时, 如果确认按钮是灰色不进行任何操作
        if (flag) return
        console.log(this.model.f_print[0])
        if (this.model.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()
        }
      },
      confirm () {
        this.eticket_msg = false
        if (this.model.f_payment.length > 0 && this.model.f_payment.includes('余额写卡')) {
          if (this.model.f_collection > this.row.f_balance) {
            this.$showAlert('请注意！您的账户余额小于当前写卡金额,无法进行余额写卡,请修改后重试', 'warning', 2000)
            return
          }

          if (this.model.f_collection > 0) {
            this.$showAlert('请注意！进行余额写卡,收款不能大于0', 'warning', 1000)
            return
          }
        }
        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

            this.clickConfirm = true
            this.model.f_curbalance = this.curbalance
            this.$dispatch('no-button')
            sellgasGen(this)
          }
        })
      },
      eticket_toggle () {
        this.eticket_show = false
        this.$dispatch('success')
      },
      clean () {
        this.$info('取消操作')
        this.$dispatch('refresh', this.row)
      },
      validateBill (val) {
        this.validateOk = !val.isOk
        this.billData.bill = val.bill
      },
      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 () {
        this.dymoney = 0
        if (this.model.f_pregas && this.model.f_pregas > 0) {
          try {
            // 对气量进行验证
            if ((this.row.f_topup_ceil - 0) > 0 && (this.model.f_pregas - 0) > (this.row.f_topup_ceil - 0)) {
              this.$showAlert(`您输入的气量不能大于该表的充值上限: ${this.row.f_topup_ceil}`, 'warning', 5000)
              this.model.f_pregas = null
            } else {
              pregasGen(this)
            }
          } catch (error) {
            this.$showAlert(`发卡售气划价错误，错误类型：${error}`, 'danger', 0)
            this.$dispatch('error', '发卡售气', this.model, error)
          }
        } else {
          this.model.f_pregas = null
        }
      },
      preamount () {
        this.dymoney = 0
        this.model.f_price_id = this.row.f_price_id
        this.model.f_user_id = this.row.f_user_id
        this.model.f_userfiles_id = this.row.f_userfiles_id
        this.model.f_userinfo_id = this.row.f_userinfo_id
        try {
          preamountGen(this)
        } catch (error) {
          this.$showAlert(`发卡售气划价错误，错误类型：${error}`, 'danger', 0)
          this.$dispatch('error', '发卡售气', this.model, error)
        }
      },
      calText (val) {
        let str = ''
        let num = 0
        val.forEach((item) => {
          if (item.f_gas > 0) {
            num = num + 1
          }
          if (this.row.f_isdecimal === '是') {
            str = str + item.f_price + ' x ' + item.f_gas + '+'
          } else {
            str = str + item.f_price + ' x ' + Math.floor(item.f_gas) + '+'
          }
        })
        str = str.slice(0, str.length - 1)
        this.calculatedetail = str
        if (num > 1) {
          if (this.$login.r.find(item => item == '阶梯提示无按钮')) {
            this.$showAlert('友好提示：本次购气已跨阶梯', 'warning', 3000)
          } else {
            this.$showMessage('友好提示：本次购气已跨阶梯', ['confirm', 'cancel'])
          }
        }
      },
      close () {
        this.print = false
        this.clean()
      },
      paymentchange () {
        console.log('model.f_payment', this.model.f_payment[0])
        if (JSON.stringify(this.model.f_payment).indexOf('转账') !== -1) {
          // 进入转账筛选条件
          this.model.f_banktransfer_person = ''
          this.model.f_banktransfer_date = ''
          this.BankTransfer = true
        } else {
          this.model.f_banktransfer_person = ''
          this.model.f_banktransfer_date = ''
          this.BankTransfer = false
        }
      },
      // 根据选择的付款方式 获取优惠列表
      async getPrivilegeList () {
        // 初始化下拉选择列表
        this.privilegeList = [{label: '无优惠', value: '0'}]
        // 初始为无优惠
        this.model.f_privilege_id = '0'
        if (this.model.f_payment && this.model.f_payment.length) {
          // 查询条件
          let payments = JSON.stringify(this.model.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: '查询优惠信息失败'})
          // 查询结果放到下拉列表
          for (let p of privilege.data) {
            this.privilegeList.push({label: p.f_privilege_name, value: p.id, type: p.f_privilege_type})
          }
          this.privilegeCalculate()
        }
      },
      // 优惠计算
      async privilegeCalculate () {
        // 初始化减免金额
        this.model.f_privilege_money = 0
        this.model.f_after_discount = this.model.f_collection
        // 判断是否是自定义优惠
        if (this.model.f_privilege_id != null && parseInt(this.model.f_privilege_id)) {
          for (let p of this.privilegeList) {
            if (p.value == this.model.f_privilege_id && p.type == '自定义') {
              this.model.f_privilege_money = window.prompt('请输入你想优惠的金额')
              if (!(/^[1-9]\d*(\.\d+)?$/).test(this.model.f_privilege_money) || !(/^[1-9]\d*(\.\d+)?$/).test(this.model.f_privilege_money)) {
                this.$showMessage('金额输入格式不正确!')
                this.model.f_privilege_money = 0
                return
              }
              if ((this.model.f_privilege_money - 0) >= this.model.f_collection) {
                this.$showMessage('减免金额不能大于等于收款金额')
                this.model.f_privilege_money = 0
                return
              }
            }
          }
        }
        // 优惠方式, 收款 缺一不计算
        if (this.model.f_payment && this.model.f_payment.length && parseInt(this.model.f_privilege_id) && this.model.f_collection) {
          let c = {
            f_privilege_id: this.model.f_privilege_id,
            f_collection: this.model.f_collection,
            f_privilege_money: this.data.f_privilege_money
          }
          let privilegeData = await this.$resetpost('rs/logic/calculatePrivilege', c, {
            resolveMsg: null,
            rejectMsg: '计算优惠金额出错'
          })
          // 减免金额
          this.model.f_privilege_money = privilegeData.data.f_privilege_money
          // 减免后收款金额
          this.model.f_after_discount = privilegeData.data.f_collection
        }
      },
      // 判断当前用户是否可以使用系统余额透支
      canOverdraftBalance () {
        return this.config.overdraftBalance && this.row.f_user_type != '民用'
      }
    },
    computed: {
      authArr () {
        return this.$login.r ? this.$login.r : []
      },
      'curbalance' () {
        if (this.model.f_payment == '赠气') {
          return this.model.f_balance
        }
        if (this.model.f_preamount) {
          // if (this.row.f_collection_type === '按金额') {
          //   return ((this.model.f_collection - 0) - (this.model.f_totalcost - 0)).toFixed(4)
          // } else {
          if ((this.row.f_balance - 0) > (this.model.f_preamount - 0)) {
            return ((this.row.f_balance - 0) - (this.model.f_preamount - 0) + (this.model.f_collection - 0)).toFixed(4)
          } else {
            return ((this.model.f_collection - 0) - (this.model.f_totalcost - 0)).toFixed(4)
          }
            // return ((this.model.f_collection - 0) - (this.model.f_totalcost - 0)).toFixed(4)
          // }
        } else {
          return this.row.f_balance
        }
      },
      'invoice_show_gas' () {
        return this.row.f_collection_type === '按气量' ? '是' : '否'
      },
      'islegal' () {
        console.log('支付分离。。。', this.paymentModel.length, this.model.f_collection)
        if (this.paymentModel.length > 1 && this.model.f_collection) {
          let sum = 0
          this.paymentModel.forEach((res) => {
            sum += (res.f_money - 0)
          })
          return (this.model.f_collection - 0) === (sum - 0)
        } else {
          return true
        }
      }
    }
  }
</script>

<style>
</style>
