<template>
  <div class="flex-row">
    <div class="span" style="overflow-y: auto;">
      <validator name='v'>
        <form novalidate class="form-horizontal">
          <div class="row">
            <div class="col-sm-4">
              <label for="f_paytype" class=" font_normal_body" title="参数名称：付款方式">收款方式</label>
                <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 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="pregas()" v-model="model.f_pregas" id="fpregas"
                     v-validate:f_pregas='{required: true, dctest: [maxgas, "<=" ]}' placeholder="预购气量"
                     v-next-el='sk' >
            </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"
                     @blur="pregas()" v-model="model.f_pregas" placeholder="预购气量"
                     v-next-el='sk' disabled>
            </div>-->

            <div class="col-sm-4">
              <label for="f_preamount" class=" font_normal_body">预购金额</label>
              <input class="input_search" style="width:60%" type="text" v-model="model.f_preamount"
                     v-validate:f_preamount='{required: true, dctest: [maxmoney, "<=" ] }'
                     placeholder="预购金额" disabled>
            </div>
          </div>
          <div class="row" style="margin-top:6px;">

            <div class="col-sm-4">
              <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" v-if="hasLimit&&limitgas">
              <label class="font_normal_body">购气上限</label>
                <input class="input_search" style="width:60%" style="width:60%" type="number" v-model="maxgas"
                       v-scale="[maxgas, 2]" 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" v-if="row.f_collection_type === '按气量'"
                     class=" font_normal_body">应收金额</label>
              <label for="f_temp_amount" v-if="row.f_collection_type === '按金额'"
                     class=" font_normal_body">本次缴费</label>
              <input class="input_search" style="width:60%" type="text"
                     @blur="preamount()" v-model="model.f_totalcost"
                     v-validate:f_totalcost='{required: true, dctest: [0, ">=" ] }' placeholder="应收金额"
                     v-next-el='sk'  >
            </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"  value="0"
                     v-scale="[model.f_balance, 2]" placeholder="上期结余" disabled>
            </div>
            <div class="col-sm-4">
              <label for="f_curbalance" class="font_normal_body">本期结余</label>
              <input class="input_search" style="width:60%" type="number"  value="0"
                     v-scale="[model.f_curbalance, 2]" placeholder="本期结余" disabled>
            </div>

            <div class="col-sm-4" v-if="row.f_collection_type === '按气量'"
                 :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 class="input_search" style="width:60%" type="text" v-model="model.f_collection"
                     v-validate:f_collection='{required: true, dctest: [model.f_totalcost, ">=" ] }'
                     v-el:sk  disabled>
            </div>
            <div class="col-sm-4" v-if="row.f_collection_type === '按金额'">
              <label for="f_collection" class=" font_normal_body">&nbsp;&nbsp;&nbsp;收款&nbsp;&nbsp;&nbsp;</label>
              <input class="input_search" style="width:60%" type="text" v-model="model.f_collection"
                     v-el:sk  disabled>
            </div>
          </div>
          <div class="row" style="margin-top:5px;">
            <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-4">
              <label for="f_write_card" style="color: red" class=" font_normal_body">是否写卡</label>
              <v-select id="f_write_card"
                        v-model="model.f_write_card"
                        placeholder='是否写卡'
                        value-single
                        :value.sync="model.f_write_card"
                        :options='writecard'
                        close-on-select clear-button></v-select>
            </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" 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" v-if="!config.notShowFormula">
            <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-config='config' v-ref:printbill :bill-data='billData'  :data='row'
                    v-on:toggle="close" @printok="printok" :data='row'></print-bill>
        <div style="text-align:right;height: 25%;">
          <payment-code-button :clickable="!$v.valid || clickConfirm"
                               :payment.sync="model.f_payment" :payment-data="paytype"
                               @confirm-payment="confirm()">
          </payment-code-button>
          <button class="button_search btn-gn" @click="confirm()" :disabled='!$v.valid || clickConfirm'>确认</button>
          <button class="button_clear btn-gn" @click="clean()">取消</button>
        </div>
      </validator>
      <payment-code v-ref:paymentcode :payment="model.f_payment" :row="row" :money="model.f_collection"></payment-code>
      <upload :blodid="row.f_userinfo_id" v-if="config.showupload" :businessid="randomBusinessId" isremark="true" fusetype="无卡收费"></upload>
    </div>
  </div>
</template>
<script>
  /**
   *综合业务
   *卡表收费组件
   */
  import CardService from './CardService'
    // 输入金额，换算气量
  function stringRound(num, decimals = 2) {
    const strValue = num + 'e' + decimals
    return Math.round(Number(strValue)) / Math.pow(10, decimals)
  }
  let preamountGen = async function (self) {
    let dymoney = 0
    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(4)
        }
      } else {
        let tempnum = Math.floor(getGas.data.gas - 0)
        let dymoney1 = await self.$CommonService.gasCalculate(self.model, (tempnum).toFixed(4))
        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_preamount = calFee - (dymoney - 0)
    self.model.chargeprice = getGas.data.chargeprice
    Object.assign(self.model, self.model, getGas.data)
    self.model.f_totalcost = ((self.model.f_totalcost - 0) - (dymoney - 0)).toFixed(2)
    // self.model.f_totalcost=Math.ceil(self.model.f_totalcost)
    if(self.config.floor){
      self.model.f_totalcost=Math.ceil(self.model.f_totalcost)
    }
    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 = stringRound(getAmount.data.chargenum)
      self.model.f_totalcost = stringRound((self.row.f_balance - 0) > (getAmount.data.chargenum - 0) ? 0 : ((getAmount.data.chargenum - 0) - (self.row.f_balance - 0)))
      Object.assign(self.model, self.model, getAmount.data)
      self.model.chargeprice = getAmount.data.chargeprice
      self.model.f_collection = self.model.f_totalcost
      // 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.model.f_write_money = self.model.f_preamount
      if (self.row.f_price_type == '阶梯气价' && self.row.f_is_step == '否') {
        self.model.f_write_money = (self.model.f_pregas * self.model.chargeprice[0].f_price)
        self.model.f_write_money = self.model.f_write_money.toFixed(2)
      }
      // 加入扫码盒付款码支付流水号
      self.model.f_serial_id = self.$refs.paymentcode.paymentCodeReturnData.f_out_trade_no

      let res = await CardService.noCardSellGas(self.model, self.row, self.cardallot)
      console.log('卡表收费返回id', res, self.model)
      if (self.config.showupload) {
        let param = []
        for (let row of self.resid) {
          param.push({id: row.id})
        }
        let data = {
          param: param,
          f_blobid: res
        }
        await self.$resetpost('rs/logic/updatefiles', data)
      }
      // 开始打票
      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_url = 'http://192.168.50.77:31039/report/jmreport/shareView/787097260170534912'
            self.row.f_collection = self.model.f_collection
            self.print = true
          } else {
            self.row.id = res
            self.row.f_url = 'http://192.168.50.77:31039/report/jmreport/shareView/787097260170534912'
            self.print = true
          }
        } else {
          if (self.model.f_print[0] === '电子发票') {
            await self.$CommonService.openEticket(res, '售气收费')
            self.row.id = res
            self.print = true
          }
        }
      } 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_paper_type !== '') {
      self.model.f_print = [self.row.f_paper_type]
    }
    // 判断限购
    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
          }
        }
      }
    }
  }
  export default {
    title: '无卡收费',
    data () {
      return {
        serialShow: false,
        resid: [],  // 存放新增的f_files表中id
        config: {
          notShowFormula: false, // 不显示计算公式,默认显示
          hasPrint: true,  // 默认打票
          hasBillManage: false,  // 默认不启用发票管理
          floor: false,  // 是否取整收费
          billType: '燃气费',   // 票据类型（燃气费，其他费用，调用的发票代码不同）
          printType: '普通收据', // 收据/电子票/专用发票/国税发票
          showupload: true,
          payment: '现金缴费'
        },
        model: {
          f_purchase: 0,
          f_write_card: '不写卡',
          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,
        billData: {
          url: 'rs/report/card_bill',
          billnumber: ''
        },
        randomBusinessId: '',
        hasLimit: false,
        maxgas: 99999999, // 限购
        maxmoney: 99999999,
        limitmoney: false,
        limitgas: false,
        mulPrint: false,
        clickConfirm: false, // 控制确认按钮只能点击一次
        // 下拉框值
        paytype: this.$appdata.getParam('付款方式'),
        printstyle: this.$appdata.getParam('打印格式'),
        writecard: [{label: '写卡',value:'写卡'},{label: '不写卡',value:'不写卡'}],
        mjshow: false
      }
    },
    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_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_totalcost = ''
        this.model.f_pregas = 0
      }
      document.getElementById('fpregas').focus()
      asyncCardMeterCenter(this)
      this.getRandomId()
    },
    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: {
      getRandomId () {
        this.randomBusinessId = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
          let res = Math.random() * 16 | 0
          let v = c == 'x' ? res : (res & 0x3 | 0x8)
          return v.toString(16)
        })
      },
      confirm () {
        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)
          }
        })
      },
      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 {
            // 对气量进行验证
            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)
          }
        }
      },
      preamount () {
        if ((this.model.f_totalcost && this.model.f_totalcost > 0) || this.row.f_balance > 0) {
          try {
            preamountGen(this)
          } catch (error) {
            this.$showAlert(`发卡售气划价错误，错误类型：${error}`, 'danger', 0)
            this.$dispatch('error', '发卡售气', this.model, error)
          }
        }
      },
      calText(val) {
        let str = '';
        let total = 0; // 用于存储总金额

        val.forEach((item) => {
          const price = parseFloat(item.f_price);
          const gas = parseFloat(item.f_gas);
          const result = price * gas; // 计算每项的结果
          total += result; // 累加到总金额
          str += `${price} x ${gas} = ${result.toFixed(3)} + `; // 显示三位小数
        });

        str = str.slice(0, -2); // 去掉最后的 " + "
        str += ` = ${total.toFixed(3)}`; // 添加总和，并保留三位小数
        this.calculatedetail = str;
      },
      close () {
        this.print = false
        this.clean()
      }
    },
    watch: {
      'model.f_payment' (val) {
        if (val == '免交') {
          this.mjshow = true
        } else {
          this.mjshow = false
        }
      }
    },
    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
        }
      },
      formattedAmount() {
        // 四舍五入保留两位小数
        return (Math.round(this.model.f_preamount * 100) / 100).toFixed(2);
      }
    }
  }
</script>

<style>
</style>
