<template>
  <div class="flex-row">
    <div class="span">
      <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>
              <v-select v-if="this.row.f_collection_type==='按金额'" :value.sync="model.f_operat_type"
                        :options='operator_type' placeholder='请选择'
                        :value-single="true"
                        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='请选择'
                        :value-single="true"
                        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" :class="[$v.f_pregas.dctest ? 'has-error' : 'has-success']">
              <label class="font_normal_body">赠气</label>
              <input class="input_search" style="width:60%" type="number" @blur="pregas"
                     v-validate:f_pregas='{ dctest: [0, ">" ]}' v-model="model.f_pregas" placeholder="赠气量" v-ref:f_pregas>
            </div>
            <div class="col-sm-4" :class="[$v.f_preamount.dctest ? 'has-error' : 'has-success']">
              <label for="f_preamount" class=" font_normal_body">金额:</label>
              <input  class="input_search" style="width:60%" type="number" v-model="model.f_preamount" placeholder="金额"
                      @blur="preamount()"
                      v-validate:f_preamount='{ dctest: [0, ">" ]}'>
            </div>
          </div>
          <div class="row" style="margin-top:10px;">
            <label for="f_reason" class=" font_normal_body">备&emsp;&emsp;注</label>
            <input  class="input_search" style="width:55%" rows="1" v-model="model.f_reason" placeholder="备注">
          </div>
        </form>
        <div style="text-align:right;margin-top: 2%">

          <button class="button_search" @click="confirm()"  :disabled='!$v.valid' >确认</button>
          <button class="button_clear" @click="clean()" >取消</button>
        </div>
      </validator>
    </div>
  </div>
  <upload :blodid="row.f_userinfo_id"  isremark="true" fusetype="赠气"></upload>
</template>
<script>
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)
    }
    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)
  }

  let otherGasGen = async function (self) {
    let data = self.getSell()
    data.f_total_gas = data.f_add_gas === '计入' ? (self.row.f_total_gas - 0) + (self.model.f_pregas - 0) : (self.row.f_total_gas - 0)
    data.f_total_fee = data.f_add_gas === '计入' ? (self.row.f_total_fee - 0) + (self.model.f_preamount - 0) : (self.row.f_total_fee - 0)
    data.f_pregas = self.model.f_pregas
    data.f_preamount = self.model.f_preamount
    data.f_userfiles_id = {
      f_userfiles_id: self.row.f_userfiles_id,
      f_user_id: self.row.f_user_id,
      version: self.row.version,
      f_times: self.row.cardInfo.Times + 1,
      f_total_gas: data.f_add_gas === '计入' ? (self.row.f_total_gas - 0) + (self.model.f_pregas - 0) : (self.row.f_total_gas - 0),
      f_total_fee: data.f_add_gas === '计入' ? (self.row.f_total_fee - 0) + (self.model.f_preamount - 0) : (self.row.f_total_fee - 0),
      f_write_totalgas: (self.row.f_write_totalgas - 0) + (self.model.f_pregas - 0),
      f_write_totalfee: (self.row.f_write_totalfee - 0) + (self.model.f_preamount - 0),
      f_balance_gas: 0,
      f_balance_amount: 0
    }

    let cardId = self.row.f_card_id
    if (self.row.f_tag && self.row.f_tag !== 'null') {
      // 截取用户编号后四位
      data.f_userfiles_id.f_card_id = cardId = self.row.f_tag + self.row.f_card_id
      data.f_userfiles_id.f_tag = null
    }

    // 保存表类型
    data.f_meter_type = self.row.f_meter_type
    data.f_times = self.row.cardInfo.Times + 1

    let result = await self.$resetpost('rs/logic/fedWithgaIc', data, {resolveMsg: null, rejectMsg: '补气报错！！！'})
    try {
        // 写卡操作
      let cardParams = await self.$resetpost('rs/logic/stairCard', {data: {f_card_id: cardId + '', f_alias: self.row.f_alias, f_user_id: self.row.f_user_id}}, {resolveMsg: null, rejectMsg: '获取写卡参数失败'})
        // 获取写卡参数
      let params = self.getWriteCard(cardParams, self.row, data)
      params.kh = cardId
      console.log('获取其他补气写卡参数，，', params)
      let url = 'http://127.0.0.1:8003/WriteGasCard'
      let cardRes = await self.$resetpost(url, params, {resolveMsg: null, rejectMsg: '补气卡服务错误'})

        // 卡服务写卡异常，业务逻辑回滚
      if (!cardParams || !result || cardRes.data.Err || cardRes.data.Exception) {
        throw new Error(`卡服务错误：${cardRes.data.Err}${cardRes.data.Exception}，请联系开发人员处理！！`)
      } else {
        await self.$CommonService.updatePassword(self.row, cardRes)
        self.$showAlert('赠气成功', 'success', 2000)
        return result.data.id
      }
    } catch (error) {
      self.$showAlert(error, 'danger', 0)
      let rollback = {
        id: result.data.id,
        f_card_id: self.row.f_card_id
      }
      if (self.row.f_tag) {
        rollback.f_tag = self.row.f_tag
      }
      await self.$resetpost('rs/logic/otherGasRollback', {data: rollback}, {rejectMsg: '赠气回滚出错', resolveMsg: null})
    }
  }

  export default {
    title: '卡表赠气赠费',
    data () {
      return {
        operator_type: [{label: '赠费', value: '卡表赠费'}, {label: '政府补贴', value: '政府补贴'}],
        operator_type2: [{label: '赠气', value: '卡表赠气'}, {label: '政府补贴', value: '政府补贴'}],
        isGas: false,
        acceptprint: false,
        acceptUrl: '',
        printData: {
          reason: '',
          fillgas: '',
          fillamount: ''
        },
        config: {
          floor: false
        },
        model: {
          f_pregas: 0,
          f_preamount: 0,
          f_reason: '',
          f_operat_type: ''
          // f_add_gas: '不计入'
        },
        print: false
      }
    },
    props: ['row', 'cardData'],
    ready () {
      this.isGas = this.row.f_meter_type === '气量卡表' || this.row.f_collection_type == '按气量' || (this.row.f_calculation === '预付费' && this.row.f_billing === '按气量')
      this.model.f_operat_type = this.isGas ? '卡表赠气' : '卡表赠费'
      this.row.cardInfo = this.cardData
      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
      console.log('卡信息', this.row.cardInfo)
    },
    methods: {
      confirm () {
        otherGasGen(this).then((res) => {
          this.$dispatch('success')
        })
      },
      pregas () {
        // 对气量进行验证
        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 {
          try {
            pregasGen(this)
          } catch (error) {
            this.$showAlert(`赠气划价错误，错误类型：${error}`, 'danger', 0)
            this.$dispatch('error', '发卡售气', this.model, error)
          }
        }
      },
      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
        }
      },
      getSell () {
        return {
          f_balance: this.row.f_balance,
          f_curbalance: this.row.f_balance,
          f_card_id: this.row.f_card_id,
          f_comments: this.model.f_reason,
          f_add_gas: '计入',
          f_type: this.model.f_operat_type,
          f_user_id: this.row.f_user_id,
          f_userfiles_id: this.row.f_userfiles_id,
          f_userinfo_id: this.row.f_userinfo_id,
          f_user_name: this.row.f_user_name,
          f_user_type: this.row.f_user_type,
          f_gasproperties: this.row.f_gasproperties,
          f_address: this.row.f_address,
          f_meter_brand: this.row.f_meter_brand,
          f_operat_type: '其他补气',
          f_describe: `${this.$login.f.name}对客户${this.row.f_user_name}进行${this.model.f_operat_type}操作`,
          f_state: '有效',
          f_operator: this.$login.f.name,
          f_operatorid: this.$login.f.id,
          f_orgid: this.$login.f.orgid,
          f_orgname: this.$login.f.orgs,
          f_depid: this.$login.f.depids,
          f_depname: this.$login.f.deps,
          f_zoneid: this.$login.f.zoneid,
          f_zones: this.$login.f.zones
        }
      },
      getWriteCard (cardParams, row, data) {
        let params = {
          factory: row.f_alias,                                // 气表厂家
          kh: row.f_card_id,                                   // 卡号
          kmm: row.f_card_password,                            // 卡密码，写卡后返回新密码, 不论补卡还是先开户都没有密码
          bjql: row.f_police_gas,                              // 报警气量,t_gasbrand表中
          czsx: row.f_topup_ceil,                              // 充值上线，t_gasbrand表中
          tzed: row.f_overdr_lines,                            // 透支额度，t_gasbrand表中
          bkcs: row.f_fillcard_times,                                          // 补卡次数，从补卡表里通过表编号获得
          ql: data.f_pregas,                            // 预购气量
          cs: row.cardInfo.Times + 1,                                     // 求购气次数，先开户为1
          money: data.f_preamount,                            // 购气金额
          klx: row.f_coding,
          kzt: '1',
          dqdm: row.f_area_code,
          meterid: row.f_meternumber ? row.f_meternumber : 0                  // 表号
          // meternumber: row.f_meternumber ? row.f_meternumber : 0
        }
        params.ljgql = parseFloat(((row.f_write_totalgas - 0) + (this.model.f_pregas - 0)).toFixed(2))
        params.ljgqje = parseFloat(((row.f_write_totalfee - 0) + (this.model.f_preamount - 0)).toFixed(2))
        return Object.assign({}, this.$CommonService.writeCardParams(cardParams), params)
      },
      close () {
        this.print = false
        this.clean()
      },
      clean () {
        this.$info('取消操作')
        this.$dispatch('cancelclean', this.row)
      }
    },
    computed: {
      addGas () {
        return [{label: '计入', value: '计入'}, {label: '不计入', value: '不计入'}]
      }
    }
  }
</script>

<style>
</style>
