<template>
  <div class="auto">
    <validator name='v'>
      <form novalidate class="form-horizontal">
        <div  class="row">
          <div class="col-sm-4 form-group">
            <label class="font_normal_body">&nbsp;操作&nbsp;</label>
            <input v-show="false" v-model="model.f_operat_type"
                   v-validate:f_operat_type='{required: true}'>
            <v-select v-if="this.row.f_collection_type==='按金额'" :value.sync="model.f_operat_type"
                      :options='operator_type' placeholder='请选择'
                      selected="赠费"
                      style="width:60%"
                      close-on-select></v-select>
            <v-select v-if="this.row.f_collection_type==='按气量'" :value.sync="model.f_operat_type"
                      :options='operator_type2' placeholder='请选择'
                      selected="赠气"
                      style="width:60%"
                      close-on-select></v-select>
          </div>
          <div class="col-sm-4 form-group">
            <label class="font_normal_body" title="参数值:计入/不计入，计入:更新档案结余及累购，不计入:只保存记录不对档案进行操作">计入累购</label>
            <input v-show="false" v-model="model.f_add_gas" v-validate:f_operat_type='{required: true}'>
            <v-select :value.sync="model.f_add_gas" value-single
                      :options='addGas' placeholder='请选择'
                      selected="是否计入累购"
                      style="width:60%"
                      close-on-select></v-select>
          </div>
          <div  class="col-sm-4 form-group"
               :class="[$v.f_preamount.required || $v.f_preamount.dctest ? 'has-error' : 'has-success']">
            <label class="font_normal_body">&nbsp;金额&nbsp;</label>

            <input class="input_search" type="number" v-model="model.f_preamount" style="width:60%"
                   @blur="preamount()"
                   v-validate:f_preamount='{required: true,  dctest: [0, ">" ]}' placeholder="金额">
          </div>
          <div  class="col-sm-4 form-group"
               :class="[$v.f_pregas.required || $v.f_pregas.dctest ? 'has-error' : 'has-success']">
            <label class="font_normal_body">&nbsp;气量&nbsp;</label>
            <input class="input_search" type="number" v-model="model.f_pregas" style="width:60%"
                   @blur="pregas()"
                   v-validate:f_pregas='{required: true,  dctest: [0, ">" ]}' placeholder="气量">
          </div>

        </div>

        <div class="row">
          <div class="col-sm-12">
            <label for="f_paper_account" class="font_normal_body ">&nbsp;备注&nbsp;</label>
            <input class="input_search" style="width:87%" rows="1" v-model="model.f_comments"></input>
          </div>
        </div>
      </form>
      <div style="text-align:right;">
        <strong style="font-size: large" v-if="!config.notShowFormula">计算公式:{{calculatedetail ? calculatedetail : ' 暂无'}}</strong><br/>
        <button class="btn button_search btn-gn" @click="confirm()" :disabled='!$v.valid'>确认</button>
        <button class="btn button_clear btn-gn" @click="clean()">取消</button>
      </div>
    </validator>
    <!--<validate-bill v-if="hasValidateBill" :data="model" @validate-bill="validateBill"></validate-bill>-->
    <!--<print-bill :show="print" :bill-manager='config.hasBillManage' v-ref:printbill :bill-url='billUrl' v-on:toggle="clean" @printok="printok" :data='printModel'></print-bill>-->
    <!--<print-bill :show="print" :bill-config='config' :bill-data='billData' v-on:toggle="clean" @printok="printok" :data='printModel'  v-ref:printbill></print-bill>-->
  </div>
  <upload :blodid="row.f_userinfo_id"  v-ref:upload    :isremark="true" fusetype="赠气"></upload>

</template>


<script>
  import Vue from 'vue'

  let preamountGen = async function (self) {
    let calFee = self.model.f_preamount
    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)
        }
        self.dymoney = 0
      } else {
        // 如果不支持小数,将划价出的多余非整数气量进行划价为金额
        let tempnum = Math.floor(getGas.data.gas - 0)
        if (getGas.data.gas > tempnum) {  // getGas.data.gas-tempnum-0
          let dymoney1 = await self.$CommonService.gasCalculate(self.model, (tempnum).toFixed(4))
          if (dymoney1.data.money) {
            self.dymoney = (getGas.data.money - 0).toFixed(2) - (dymoney1.data.money - 0).toFixed(2)
          }
        } else {
          self.dymoney = 0
        }
        self.model.f_pregas = Math.floor(getGas.data.gas - 0)
      }
    }
    // 不划气量,归零
    if (self.config.priceCalculation) {
      self.model.f_pregas = 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 - 0)).toFixed(4))

    self.model.chargeprice = getGas.data.chargeprice
    Object.assign(self.model, self.model, getGas.data)
    self.model.f_totalcost = ((self.model.f_totalcost - 0) - (self.dymoney - 0)).toFixed(2)
    if (self.config.floor) {
      self.model.f_totalcost = Math.ceil(self.model.f_totalcost)
    }
    self.model.f_collection = self.model.f_totalcost
    self.model.f_preamount = ((getGas.data.chargenum - 0) - (self.dymoney - 0))
    if (self.model.f_payment == '赠气') {
      self.model.f_totalcost = self.model.f_preamount
      self.model.f_collection = 0
    }
    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.config.floor) {
        self.model.f_totalcost = Math.ceil(self.model.f_totalcost)
      }
      self.model.f_collection = self.model.f_totalcost
      if (self.model.f_payment == '赠气') {
        self.model.f_totalcost = getAmount.data.chargenum
        self.model.f_collection = 0
      }
      self.calText(getAmount.data.chargeprice)
    }
  }
export default {
    title: '赠气赠费',
    data () {
      return {
        blodid: '',
        showupload: false,
        config: {
          notShowFormula: false, // 不显示计算公式,默认显示
          priceCalculation: false, // 划气量控制
          showupload: true,  // 默认显示附件上传组件
          hasPrint: false,  // 默认打票
          floor: true,  // 是否取整收费
          hasBillManage: false,  // 默认不启用发票管理
          billType: '燃气费',   // 票据类型（燃气费，其他费用，调用的发票代码不同）
          printType: '普通收据', // 收据/电子票/专用发票/国税发票
          payment: '',
          overdraftBalance: false // 是否支持系统余额透支
        },
        maxgas: 99999999, // 限购
        maxmoney: 99999999,
        calculatedetail: '',
        operator_type: [{label: '赠费', value: '物联网赠费'}, {label: '政府补贴', value: '政府补贴'}],
        operator_type2: [{label: '赠气', value: '物联网赠气'}, {label: '政府补贴', value: '政府补贴'}],
        model: {
          f_operat_type: '',
          f_pregas: 0,
          f_preamount: 0,

          f_comments: ''
        }

      }
    },
    props: ['row'],
    ready () {
      // this.blodid = this.row.f_userinfo_id
      if (this.row.f_collection_type === '按气量') {
        this.model.f_operat_type = ['物联网赠气']
      } else {
        this.model.f_operat_type = ['物联网赠费']
      }
      this.model.f_price_id = this.row.f_price_id
      this.model.f_add_gas = '计入'
      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
      this.model.f_preamount = ''
      this.model.f_pregas = ''
    },
    methods: {
      pregas () {
        this.dymoney = 0
        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)
          }
        } else {
          this.model.f_pregas = null
        }
      },
      preamount () {
        if (this.model.f_preamount && this.model.f_preamount > 0) {
          try {
            preamountGen(this)
          } catch (error) {
            this.$showAlert(`发卡售气划价错误，错误类型：${error}`, 'danger', 0)
            this.$dispatch('error', '发卡售气', this.model, error)
          }
        } else {
          this.model.f_preamount = null
        }
      },
      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
      },
      async confirm () {
        let param = {
          fillgas: {
            f_userfiles_id: this.row.f_userfiles_id,
            f_userinfo_id: this.row.f_userinfo_id,
            f_user_id: this.row.f_user_id,
            f_user_name: this.row.f_user_name,
            f_user_type: this.row.f_user_type,
            f_gasproperties: this.row.f_gasproperties,
            f_meter_type: this.row.f_meter_type,
            f_pregas: this.model.f_pregas,
            f_add_gas: this.model.f_add_gas,
            f_address: this.row.f_address,
            f_meter_brand: this.row.f_meter_brand,
            f_preamount: this.model.f_preamount,
            f_type: this.model.f_operat_type[0],
            f_comments: this.model.f_comments,
            f_billing: this.row.f_billing,
            f_operator: Vue.$login.f.name,
            f_operatorid: Vue.$login.f.id,
            f_orgid: Vue.$login.f.orgid,
            f_orgname: Vue.$login.f.orgs,
            f_depid: Vue.$login.f.depids,
            f_depname: Vue.$login.f.deps,
            f_card_id: this.row.f_card_id,
            f_balance: this.row.f_balance_amount,
            f_operat_type: this.model.f_operat_type[0],
            f_describe: `${this.$login.f.name}对用户${this.row.f_user_name}进行${this.model.f_operat_type}操作`,
            f_state: '有效'
            // f_table_state:'有效'
          }
        }
        console.log(param)
        this.$resetpost('rs/logic/fedWithgas', {data: param}, {warnMsg: `确定要对用户${this.row.f_user_name}进行${this.model.f_operat_type}吗？`, resolveMsg: `${this.model.f_operat_type}成功！！`, rejectMsg: `${this.model.f_operat_type}失败！！请重试！！`}).then((res) => {
          this.clean()
        })
      },
      clean () {
        this.$dispatch('refresh')
      }
    },
    computed:{
      addGas () {
        return [{label: '计入', value: '计入'}, {label: '不计入', value: '不计入'}]
      }
    }
  }
</script>
