<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" style="margin-top:5px;">
          <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">
            <label for="f_print" class="control-label col-sm-2">打印格式:</label>
            <div class="col-sm-2">
              <v-select id="print"
                        v-model="f_print"
                        placeholder='请选择'
                        :value.sync="model.f_print"
                        :options='printstyle'
                        close-on-select clear-button>
              </v-select>
            </div>
          </div>
          <div class="form-group form-input-group col-sm-4" v-if="model.f_payment[0].includes('POS')">
            <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" style="margin-top:5px;">

          <div class="form-group form-input-group col-sm-4" v-if="(row.f_balance_gas - 0) < 0">
            <label for="f_balance_gas" class="control-label col-sm-2">超用气量:</label>
            <input type="text" class="form-control col-sm-2" v-model="(0 - row.f_balance_gas)" disabled>
          </div>

          <div class="form-group form-input-group col-sm-4" v-if="(row.f_balance_amount - 0) < 0">
            <label for="f_balance_amount" class="control-label col-sm-2">超用金额:</label>
            <input type="text" class="form-control col-sm-2" v-model="(0 - row.f_balance_amount)" disabled>
          </div>

          <div class="col-sm-4 form-input-group" v-if="showGas" :class="[$v.f_pregas.required || $v.f_pregas.dctest ? 'has-error' : 'has-success']">
            <label for="f_pregas" class="control-label">预购气量:</label>
            <input id="f_pregas" class="form-control col-sm-2" type="number" v-model="model.f_pregas"
                   @blur="pregas" v-validate:f_pregas='{required: true, dctest: [(0 - row.f_balance_gas) < 0 ? 0 : (0 - row.f_balance_gas), ">" ]}' v-scale="[model.f_pregas, 2]">
          </div>

          <div class="col-sm-4 form-input-group" :class="[$v.f_preamount.required || $v.f_preamount.dctest ? 'has-error' : 'has-success']">
            <label for="f_preamount" class="control-label">预购金额:</label>
            <input id="f_preamount" class="form-control col-sm-2" type="number" v-model="model.f_preamount"
                   v-validate:f_preamount='{required: true, dctest: [(0 - row.f_balance_amount) < 0 ? 0 : (0 - row.f_balance_amount) , ">" ]}' v-scale="[model.f_preamount, 2]" :disabled="showGas">
          </div>
        </div>
        <div class="row" style="margin-top:5px;">
          <div class="col-sm-12 form-input-group">
            <label for="f_curbalance" class="col-sm-2 control-label">备注:</label>
            <textarea class="form-control" rows="3" v-model="model.f_comments" ></textarea>
          </div>
        </div>
        <div class="row" style="margin-top:5px;" v-if="showGas">
          <div class="col-sm-4 col-sm-offset-8">
            <strong>计算公式:{{calculatedetail ? calculatedetail : ' 暂无'}}</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" @click="confirm()" :disabled='!$v.valid&&!(model.message)'>确认</button>
        <button class="btn btn-default" @click="clean()" style="width:80px;margin-left:20px;">取消</button>
      </div>
    </validator>
  </div>
</template>
<script>
  /**
   *综合业务
   *物联网表收费组件
   */

  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)
    }
    self.model.f_user_id = self.row.f_user_id
    let getAmount = await self.$CommonService.gasCalculate(self.model, self.model.f_pregas)
    self.model.f_preamount = getAmount.data.chargenum
    Object.assign(self.model, self.model, getAmount.data)
    self.model.chargeprice = getAmount.data.chargeprice
    self.calText(getAmount.data.chargeprice)
  }

  let IOTChargeGen = async function (self) {

    try {
      let res = await self.$resetpost('rs/logic/sale_IOTCharge_logic', {data: self.model}, {warnMsg: `确定对用户${self.row.f_user_name}进行缴费吗？`, resolveMsg: '物联网收费成功！！', rejectMsg: '物联网收费出错!!!'})
      console.log('物联网收费返回。。。', res)
      // 开始打票
      console.log('开始打票', self.config)
      if (self.config.hasPrint) {
        console.log('self.config.printType', self.config.printType)
        if (self.config.printType === '普通收据') {
          console.log('self.config.hasBillManage', self.config.hasBillManage)
          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.row.f_preamount = self.model.f_preamount
            self.billUrl = 'rs/report/pre_sell'
            self.print = true
          } else {
            self.row.id = res.data.id
            console.log('self.row.id', self.row.id, res.data.id)
            self.row.f_bill_type = '物联网收费'
            self.row.f_bill_style = self.model.f_print[0]
            self.row.f_preamount = self.model.f_preamount
            self.billUrl = 'rs/report/pre_sell'
            self.print = true
          }
        } else if (self.config.printType === '国税发票') {
          // TODO
        } else if (self.config.printType === '电子发票') {
          // TODO
        }
      } else {
        self.$dispatch('success')
      }
    } catch (error) {
      if (error.status !== 301) {
        self.$showAlert(error, 'danger', 0)
      }
      self.$dispatch('refresh')
    }

  }

  export default {
    title: '物联网表收费',
    data () {
      return {
        config: {
          hasPrint : true,  //默认打票
          hasBillManage :false,  //默认不启用发票管理
          printType: '普通收据' // 收据/电子票/专用发票/国税发票
        },
        model: {
          f_payment: '现金缴费',
          f_pregas: 0,
          f_preamount: 0,
          f_print: [],
          f_comments: ''
        },
        showGas: false,
        calculatedetail: '',
        print: false,
        billUrl: '',
        // 下拉框值
        paytype: this.$appdata.getParam('付款方式'),
        printstyle: this.$appdata.getParam('打印格式')
      }
    },
    props: ['row'],
    ready () {
      if (this.row.f_calculation === '预付费') {
        this.showGas = this.row.f_billing === '按气量'
      } else {
        this.showGas = false
      }
      this.model.f_print = [this.config.printType]
    },
    methods: {
      confirm () {
        console.log('model and row', this.model, this.row)

        this.model.f_userinfo_id = this.row.f_userinfo_id
        this.model.f_user_id = this.row.f_user_id
        this.model.f_payment = this.model.f_payment[0]
        this.model.f_print = this.model.f_print[0]
        this.model.f_operator = this.$login.f.name,
        this.model.f_filiale = this.$login.f.f_fengongsi,
        this.model.f_outlets = this.$login.f.f_parentname,
        this.model.f_filialeids = this.$login.f.f_orgids,
        this.model.f_orgstr = this.$login.f.orgpathstr
        IOTChargeGen(this)
      },
      clean () {
        this.$info('取消操作')
        this.$dispatch('refresh', this.row)
      },
      close () {
        this.print = false
        this.clean()
      },
      printok () {
        this.$dispatch('success')
      },
      pregas () {
        if (this.model.f_pregas && this.model.f_pregas > 0 && this.model.f_pregas - (0 - this.row.f_balance_gas) >= 0) {
          try {
            pregasGen(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
      }
    }
  }
</script>
