<template>
  <div class="flex-row">
    <div class="span">
      <validator name='v'>
        <form novalidate class="form-horizontal">
          <div class="row" v-if="isGas">
            <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">
              <label for="f_add_gas" class="font_normal_body">是否入累计</label>
              <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">
            <div class="col-sm-4">
              <label for="f_preamount" class=" font_normal_body">应补金额:</label>
              <input  class="input_search" style="width:60%" type="number" min = "0" v-model="model.f_preamount" placeholder="金额">
            </div>
            <div class="col-sm-4">
              <label for="f_add_gas" class="font_normal_body">是否入累计:</label>
              <v-select 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" 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>
        <print-bill :show="print" :bill-config='config' :bill-data='billData' :data='row' @toggle="close" @printok="printok"  v-ref:printbill></print-bill>
        <accept-bill :show="acceptprint" :bill-url='acceptUrl' v-on:toggle="close" :data='row' :billdata="printData" v-ref:acceptbill @closeaccept="closeAccept"></accept-bill>
        <div style="text-align:right;margin-top: 2%">
          <button class="button_search" @click="accept()" v-if="config.hasAcceptance" :disabled='!$v.valid'>受理单</button>
          <button class="button_search" @click="confirm()"  :disabled='!$v.valid' >确认</button>
          <button class="button_clear" @click="clean()" >取消</button>
        </div>
      </validator>
    </div>
  </div>
</template>
<script>
  let otherGasGen = async function (self) {
    // 划价
    let data = self.getSell()

    // 获取最后一次操作
    let getLastOper = await self.$resetpost('rs/logic/sale_getLastOper', {data: {f_userfiles_id: self.row.f_userfiles_id}}, {resolveMsg: null, rejectMsg: '获取最后一次操作失败'})
    console.log('获取最后一次的操作。。', getLastOper)

    // 验证是否可以不计入补气（这里不计入补气 == 掉气补气）
    // if (data.f_add_gas === '不计入' && getLastOper.data.ispick === '已过表') {
    //   self.$showAlert('该客户最后一次购气已过表，禁止不计入补气，请修改为计入在进行补气', 'warning', 10000)
    //   return
    // }

    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)

    // 组织划价model
    let param = {
      f_price_id: self.row.f_price_id,
      f_userfiles_id: self.row.f_userfiles_id,
      f_user_id: self.row.f_user_id,
      f_meter_type: self.row.f_meter_type
    }
    // 若是气量卡表 temp为金额  若是金额卡表 temp为气量
    if (self.isGas) {
      data.f_pregas = self.model.f_pregas
      // let fee = await self.$CommonService.gasCalculate(param, self.model.f_pregas)
      // data.f_preamount = fee.data.chargenum
    } else {
      data.f_preamount = self.model.f_preamount
      let gas = await self.$CommonService.feeCalculate(param, self.model.f_preamount)
      data.f_pregas = gas.data.gas
    }
    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: data.f_add_gas === '计入' ? (self.row.f_write_totalgas - 0) + (self.model.f_pregas - 0) : (self.row.f_write_totalgas - 0),
      f_write_totalfee: data.f_add_gas === '计入' ? (self.row.f_write_totalfee - 0) + (self.model.f_preamount - 0) : (self.row.f_write_totalfee - 0),
      f_balance_gas: 0,
      f_balance_amount: 0
    }
    if (self.row.f_meter_type === '物联网表') {
      if (self.row.f_calculation === '预付费' || (self.row.f_hascard == '是' && self.row.f_calculation == '表端结算')) {
        if (self.row.f_billing === '按气量') {
          data.f_userfiles_id.f_balance_gas = (self.row.f_balance_gas - 0) + (self.model.f_pregas - 0)
        } else {
          data.f_userfiles_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)
    }

    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
    if(!(self.row.f_hascard==null)  &&  !(self.row.f_share_times==null)  && self.row.f_meter_type =='物联网表' && self.row.f_hascard == '是' &&  self.row.f_share_times == '是'){
      data.f_times = self.row.f_times+1
    }else{
      data.f_times = self.row.cardInfo.Times + 1
    }

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

    if (self.row.f_meter_type == '机表') {
      self.$showAlert('补气成功', 'success', 2000)
      return result.data.id
    } else {
      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
        params.kzt = getLastOper.data.ispick === '未过表' && getLastOper.data.lastsell_oper === '发卡售气' ? '0' : '1'
        if(!(self.row.f_hascard==null)  &&  !(self.row.f_share_times==null)  && self.row.f_meter_type =='物联网表' && self.row.f_hascard == '是' &&  self.row.f_share_times == '是'){
          params.cs = self.row.f_times+1
        }
        console.log('获取其他补气写卡参数，，', params)
        if (data.f_add_gas === '不计入'){
          params.totalmoney = (params.totalmoney-0) - (cardParams.data.otherFee-0)
        }
        let url = (getLastOper.data.last_oper === '补卡' || getLastOper.data.last_oper === '换表')
          ? 'http://127.0.0.1:8003/WriteNewCard' : '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})
      }
    }
  }

  let readyGen = async function (self) {
    console.log('其他补气，，，', self.row)
    await self.$getConfig(self, 'OtherGas')
    console.log('其他补气config', self.config)
  }

  export default {
    title: '其他补气',
    data () {
      return {
        isGas: false,
        config: {
          hasPrint: false,  // 默认打票
          hasBillManage: false,  // 默认不启用发票管理
          billType: '燃气费',   // 票据类型（燃气费，其他费用，调用的发票代码不同）
          printType: '普通收据', // 收据/电子票/专用发票/国税发票
          payment: '现金缴费',
          hasAcceptance: false // 是否需要打印受理单
        },
        acceptprint: false,
        acceptUrl: '',
        printData: {
          reason: '',
          fillgas: '',
          fillamount: ''
        },
        model: {
          f_pregas: 0,
          f_preamount: 0,
          f_reason: '',
          f_add_gas: '不计入'
        },

        print: false,
        billData: {
          url: 'rs/report/card_bill',
          billnumber: ''
        }
      }
    },
    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.row.cardInfo = this.cardData
      console.log('卡信息', this.row.cardInfo)
      readyGen(this)
    },
    methods: {
      accept () {
        // 打印受理单
        console.log('其他补气model', this.model)
        console.log('其他补气受累单中row', this.row)
        this.printData.reason = this.model.f_comments ? `'${this.model.f_reason}'` : '' + `'${this.model.f_reason}'`
        this.printData.fillgas = `'${this.model.f_pregas}'`
        this.printData.fillamount = `'${this.model.f_preamount}'`
        console.log('受累单中printData', this.printData)
        this.acceptUrl = 'rs/report/acceptOtherGas_bill'
        this.acceptprint = true
      },
      closeAccept () {
        this.acceptprint = false
      },
      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
        }
      },
      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: this.model.f_add_gas[0],
          f_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}进行其他补气操作`,
          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
          iotTimes: row.f_iot_times,                    // 远传次数
          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
        }
        return Object.assign({}, this.$CommonService.writeCardParams(cardParams), params)
      },
      close () {
        this.print = false
        this.clean()
      },
      clean () {
        this.$info('取消操作')
        this.$dispatch('cancelclean', this.row)
      },
      printok () {
        this.$dispatch('success')
      }
    },
    computed: {
      addGas () {
        return [{label: '计入', value: '计入'}, {label: '不计入', value: '不计入'}]
      }
    }
  }
</script>

<style>
</style>
