<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" v-if="isGas">
          <label for="f_pregas" class=" col-sm-2 control-label">应补气量:</label>
          <div class="col-sm-2">
            <input  class="form-control" type="number" min = "0" v-model="model.f_pregas" placeholder="气量">
          </div>
          <label for="f_add_gas" class="col-sm-2 control-label">是否入累计:</label>
          <div class="col-sm-2">
            <v-select id="f_add_gas"
                      v-model="model.f_add_gas"
                      placeholder='请选择'
                      :value.sync="model.f_add_gas"
                      :options='addGas'
                      close-on-select clear-button>
            </v-select>
          </div>
        </div>
        <div class="row" v-if="!isGas">
          <label for="f_preamount" class=" col-sm-2 control-label">应补金额:</label>
          <div class="col-sm-2">
            <input  class="form-control" type="number" min = "0" v-model="model.f_preamount" placeholder="金额">
          </div>
        </div>
        <div class="row" style="margin-top:10px;">
          <label for="f_reason" class=" col-sm-2 control-label">备注:</label>
          <div class="col-sm-10">
            <textarea  class="form-control" rows="3" v-model="model.f_reason" placeholder="备注"></textarea>
          </div>
        </div>
      </form>
      <print-bill :show="print" v-ref:printbill v-on:toggle="close" :data='row'></print-bill>
      <div style="text-align:right;margin-top:30px;margin-right:50px;">
        <button class="btn btn-success" @click="confirm()"  title="演示系统暂不支持" :disabled="true" id='components-comOpe-othCha-确认'>确&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;认</button>
        <button class="btn btn-default" @click="clean()" style="width:80px;margin-left:20px;" id='components-comOpe-othCha-取消'>取&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;消</button>
      </div>
    </validator>
  </div>
</template>
<script>

  let otherGasGen = async function (self) {
    // 划价
    let data = self.getSell()
    // 组织划价model
    let param = {
      f_price_id: self.row.f_price_id,
      f_user_id: self.row.f_user_id,
      f_meter_type: self.row.f_meter_type
    }
    // 若是气量卡表 temp为金额  若是金额卡表 temp为气量
    if (self.isGas) {
      data.f_fillgas = self.model.f_pregas
      let fee = await self.$CommonService.gasCalculate(param, self.model.f_pregas)
      data.f_fillgas_fee = fee.data.chargenum
    } else {
      data.f_fillgas_fee = self.model.f_preamount
      let gas = await self.$CommonService.feeCalculate(param, self.model.f_preamount)
      data.f_fillgas = gas.data.gas
    }
    data.f_user_id = {
      f_user_id: self.row.f_user_id,
      version: self.row.version,
      f_meter_base: data.f_add_gas === '计入' ? (self.row.f_meter_base - 0) + (self.model.f_pregas - 0) : (self.row.f_meter_base - 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_balance_gas: 0,
      f_balance_amount: 0
    }
    if (self.row.f_meter_type === '物联网表') {
      if (self.row.f_calculation === '预付费') {
        if (self.row.f_billing === '按气量') {
          data.f_user_id.f_balance_gas = (self.row.f_balance_gas - 0) + (self.model.f_pregas - 0)
        } else {
          data.f_user_id.f_balance_amount = (self.row.f_balance_amount - 0) + (self.model.f_preamount - 0)
        }
      } else {
        data.f_userinfo_id = {
          f_userinfo_id: self.row.f_userinfo_id,
          f_balance : (self.row.f_balance - 0) + (self.model.f_preamount - 0),
          f_real_balance: (self.row.f_real_balance - 0) + (self.model.f_preamount - 0),
          version: self.row.userinfo_version
        }
      }
    }else if(self.row.f_meter_type === '机表'){
      data.f_user_id.f_balance_amount = (self.row.f_balance_amount - 0) + (self.model.f_preamount - 0)
    }

    //保存表类型
    data.f_meter_type = self.row.f_meter_type

    let result = await self.$resetpost('rs/entity/t_fillgas', data, {resolveMsg: null, rejectMsg: '补气报错！！！'})

    if (self.row.f_meter_type === '物联网表' || self.row.f_meter_type=='机表') {
      let record = {
        id: result.data.id,
        f_state: '有效'
      }
      return await self.$resetpost('rs/entity/t_record', record, {resolveMsg: '补气成功', rejectMsg: '补气修改状态失败'})
    } else {
      try {
        // 写卡操作
        let cardParams = await self.$resetpost('rs/logic/stairCard', {data: {f_card_id: self.row.f_card_id + '', f_alias: self.row.f_alias}}, {resolveMsg: null, rejectMsg: '获取写卡参数失败'})
        console.log('获取其他补气写卡参数，，', cardParams)
        // 获取写卡参数
        let params = self.getWriteCard(cardParams, self.row, data)

        let cardRes = await self.$resetpost('http://127.0.0.1:8003/WriteGasCard', params, {resolveMsg: null, rejectMsg: '补气卡服务错误'})

        // 卡服务写卡异常，业务逻辑回滚
        if (!cardParams || !result || cardRes.data.Err || cardRes.data.Exception) {
          throw new Error(`卡服务错误：${cardRes.data.Err}${cardRes.data.Exception}，请联系开发人员处理！！`)
        } else {
          let record = {
            id: result.data.id,
            f_state: '有效'
          }
          return await self.$resetpost('rs/entity/t_record', record, {resolveMsg: '补气成功', rejectMsg: '补气修改状态失败'})
        }
      } catch (error) {
        self.$showAlert(error, 'danger', 0)
        let rollback = {
          id: result.data.id
        }
        await self.$resetpost('rs/logic/otherGasRollback', {data: rollback}, {rejectMsg: '其他补气回滚出错', resolveMsg: null})
      }
    }
  }

  export default {
    title: '其他补气',
    data () {
      return {
        isGas: false,
        print: false,
        model: {
          f_pregas: 0,
          f_preamount: 0,
          f_reason: '',
          f_add_gas: '不计入'
        }
      }
    },
    props: ['row'],
    ready () {
      console.log('其他补气，，，', this.row)
      this.isGas = this.row.f_meter_type === '气量卡表' || (this.row.f_calculation === '预付费' && this.row.f_billing === '按气量')
    },
    methods: {
      confirm () {
        otherGasGen(this).then((res) => {
          this.$dispatch('success')
        })
      },
      getSell () {
        return {
          f_balance: this.row.f_balance,
          f_curbalance: this.row.f_balance,
          f_card_id: this.row.f_card_id,
          f_reason: this.model.f_reason,
          f_add_gas: this.model.f_add_gas[0],
          f_fillgas_type: '其他补气',
          f_fillgas_state: '有效',
          f_user_id: this.row.f_user_id,
          f_userinfo_id: this.row.f_userinfo_id,
          f_user_name: this.row.f_user_name,
          f_operat_type: '其他补气',
          f_describe: `${this.$login.f.name}对用户${this.row.f_user_name}进行其他补气操作`,
          f_state: '未知',
          f_operator: this.$login.f.name,
          f_filiale: this.$login.f.f_fengongsi,
          f_outlets: this.$login.f.f_parentname,
          f_filialeids: this.$login.f.f_orgids,
          f_orgstr: this.$login.f.orgpathstr
        }
      },
      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: '0',                                          // 补卡次数，从补卡表里通过表编号获得
          ql: data.f_fillgas,                            // 预购气量
          cs: row.cardInfo.Times + 1,                                     // 求购气次数，先开户为1
          money: data.f_fillgas_fee,                            // 购气金额
          klx: row.f_coding
        }
        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>
