<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>
          <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>
          <div class="row" style="margin-top:6px;">
            <div class="col-sm-4" :class="[$v.printstyle.required ? 'has-error' : '']">
              <label for="f_print" class="font_normal_body">打印格式</label>
              <input type="text" v-show="false" v-model="$refs.printstyle.selectedItems"
                     v-validate:printstyle='{required: true }'>
              <v-select id="print"
                        v-model="f_print"
                        placeholder='请选择'
                        :multiple="mulPrint"
                        :value.sync="model.f_print"
                        :options='printstyle'
                        close-on-select clear-button v-ref:printstyle>
              </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>
        <validate-bill v-if="hasValidateBill" :data="model" @validate-bill="validateBill"></validate-bill>
        <print-bill :show="print" :bill-config='config' :bill-data='billData' :data='row' @toggle="printCancel"
                    @printok="printok" v-ref:printbill></print-bill>
        <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 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)
    if (self.isGas) {
      data.f_pregas = self.model.f_pregas
    } else {
      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_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)
        // 开始打票
        console.log('开始打票', self.config)
        self.$showAlert('赠气成功', 'success', 2000)
        if (self.config.hasPrint) {
          if (self.model.f_print.indexOf('电子发票') == -1) {
            if (self.config.hasBillManage) {
              // 启用发票管理，获取票据管理中的票号并存储记录
              self.row.id = result.data.id
              self.row.f_bill_type = data.f_type
              self.row.f_bill_style = self.model.f_print[0]
              self.print = true
            } else {
              self.row.id = result.data.id
              self.print = true
            }
          } else if (self.config.printType === '国税发票') {
            // TODO
          } else if (self.model.f_print[0] === '电子发票') {
            // TODO
          }
        } else {
          self.$dispatch('success')
        }
      }
    } 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 asyncShowCardTableGas = async function (self) {
    await self.$getConfig(self, 'CardChangeFill')
    console.log('换表发卡config', self.config)
    self.model.f_print = self.config.printType instanceof Array ? self.config.printType : [self.config.printType]
    self.mulPrint = self.config.printType instanceof Array

    self.model.f_use_type = self.config.billType
    self.model.f_bill_type = self.model.f_print
    self.hasValidateBill = self.config.hasBillManage
  }
  export default {
    title: '卡表赠气赠费',
    data () {
      return {
        isGas: false,
        acceptprint: false,
        resid: [],
        acceptUrl: '',
        config:{
          hasPrint: false,
          hasBillManage: true,
          billType: '燃气费',
          printType: '普通收据'
        },
        printData: {
          reason: '',
          fillgas: '',
          fillamount: ''
        },
        model: {
          f_pregas: 0,
          f_preamount: 0,
          f_reason: '',
          // f_add_gas: '不计入'
          f_print: []
        },

        hasValidateBill: true,
        validateOk: false,

        billData: {
          url: 'rs/report/fill_gas_send_bill',
          bill: ''
        },
        print: false,
        mulPrint: false,
        printstyle: this.$appdata.getParam('打印格式') ? this.$appdata.getParam('打印格式') : [],
      }
    },
    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
      asyncShowCardTableGas(this)
      console.log('卡信息', this.row.cardInfo)
    },
    methods: {
      validateBill (val) {
        this.validateOk = !val.isOk
        this.billData.bill = val.bill
      },

      printok () {
        this.$dispatch('success')
      },
      confirm () {
        otherGasGen(this).then((res) => {
        })
      },
      printCancel () {
        this.$dispatch('refresh')
      },
      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: '计入',
          f_type: this.model.f_pregas != 0 ? '卡表赠气' : '卡表赠费',
          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_pregas != 0 ? '卡表赠气' : '卡表赠费'}操作`,
          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
        }
        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>
