<template>
  <div class="flex-row">
    <div class="span" style="overflow-y: auto;">
      <validator name='v'>
        <form novalidate class="form-horizontal">
          <div class="row">
            <div class="col-sm-4">
              <label class=" font_normal_body">调价补差</label>
              <v-select v-model="f_compensation_type"
                        placeholder='请选择'
                        :value-single="true"
                        :value.sync="model.f_compensation_type"
                        :options='compensationTypes'
                        close-on-select clear-button></v-select>
            </div>
            <div class="col-sm-4">
              <label class=" font_normal_body" title="参数名称：付款方式">收款方式</label>
              <v-select v-model="f_payment"
                        placeholder='请选择'
                        :value.sync="model.f_payment"
                        :options='paytype'
                        close-on-select clear-button></v-select>
            </div>
            <div class="col-sm-4" :class="[$v.printstyle.required ? 'select-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:6px;">
            <div class="col-sm-8">
              <label for="f_comments" class="font_normal_body">&nbsp;&nbsp;&nbsp;备注&nbsp;&nbsp;&nbsp;</label>
              <input class="input_search" style="width:80%" v-model="model.f_comments" rows="1" placeholder="备注">
            </div>
            <div class="col-sm-4" :class="[$v.f_collection.required  || $v.f_collection.dctest ? 'has-error' : 'has-success']">
              <label for="f_collection" class="font_normal_body" v-if="model.f_compensation_type == '调价补费'">应补金额</label>
              <label for="f_collection" class="font_normal_body" v-else>应退金额</label>
              <input id="f_collection" class="input_search" style="width:60%" type="number" v-model="model.f_collection"
                     readonly
                     v-scale="[model.f_collection, 4]" v-validate:f_collection='{required: true, dctest: [(model.f_collection - 0), ">=" ] }' placeholder="补费金额">
            </div>

          </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="close" @printok="printok"  v-ref:printbill></print-bill>
        <div style="text-align:right; height: 25%">
          <strong style="font-size: large" >计算公式:{{calculatedetail ? calculatedetail : ' 暂无'}}</strong><br/>
<!--          <payment-code-button :clickable="!$v.valid || clickConfirm"-->
<!--                               :payment.sync="model.f_payment" :payment-data="paytype"-->
<!--                               @confirm-payment="confirm()">-->
<!--          </payment-code-button>-->
          <button class="button_search btn-gn" type="submit" @click="confirm()" :disabled='!$v.valid || clickConfirm'>确认</button>
          <button class="button_clear btn-gn" @click="clean()">取消</button>
        </div>
      </validator>
    </div>
  </div>
  <payment-code v-ref:paymentcode :payment="model.f_payment" :row="row" :money="model.f_collection"></payment-code>
  <upload :blodid="blodid" v-if="config.showupload" isremark="true" fusetype="调价补差"></upload>
</template>
<script>
  import {HttpResetClass} from 'vue-client'

  /**
   *综合业务
   *卡表收费组件
   */

  let compensationChargeGen = async function (self) {
    try {
      if (self.paymentModel.length === 0) {
        self.paymentModel = [{
          f_payment: self.model.f_payment[0],
          f_money: self.model.f_preamount
        }]
      }
      self.model.payments = self.paymentModel

      let param = Object.assign({}, {}, self.model)
      param.f_payment = self.model.f_payment.toString()
      param.f_print = self.model.f_print.toString()
      // 加入扫码盒付款码支付流水号
      param.f_serial_id = self.$refs.paymentcode.paymentCodeReturnData.f_out_trade_no
      let res = await self.$resetpost('rs/logic/sale_compensationJB_logic', {data: param}, {
        warnMsg: `确定对客户${self.row.f_user_name}进行调价补差吗？`,
        resolveMsg: '调价补差成功！！',
        rejectMsg: '调价补差出错!!!'
      })
      // 开始打票
      console.log('开始打票', self.config)
      if (self.config.hasPrint) {
        if (self.config.printType != '电子发票') {
          if (self.config.hasBillManage) {
            // 启用发票管理，获取票据管理中的票号并存储记录
            self.row.id = res.data.id
            self.row.f_bill_type = '调价补差'
            self.row.f_bill_style = self.model.f_print[0]
            self.print = true
          } else {
            self.row.id = res.data.id
            self.print = true
          }
        } else if (self.config.printType === '国税发票') {
          // TODO
        } else if (self.config.printType === '电子发票') {
          // TODO
        }
      } else {
        self.$dispatch('success')
      }
    } catch (error) {
      if (error.status === 301) {
        self.$dispatch('refresh')
      } else {
        if (error) {
          self.$showAlert(error, 'danger', 0)
        }
      }

      self.$dispatch('refresh')
    }
  }
  let asyncCardMeterCenter = async function (self) {
    await self.$getConfig(self, 'IotCompensation')
    console.log('卡表收费config', self.config)
    self.blodid = self.row.f_userinfo_id
    // 默认打印格式
    self.model.f_print = self.config.printType instanceof Array ? self.config.printType : [self.config.printType]
    self.model.f_payment = [self.config.payment]
    self.mulPrint = self.config.printType instanceof Array
    let http = new HttpResetClass()
    let getSurplus = await http.load('POST', 'rs/sql/singleTable_OrderBy',
      {data: {items: "f_user_id,f_userfiles_id,f_userinfo_id,f_type,sum(f_surplus_fee) as 'f_surplus_fee'",
        tablename: 't_surplus_detail',
        condition: `f_userfiles_id = '${self.row.f_userfiles_id}' and f_state='有效' and f_whether_pay = '否' GROUP BY f_user_id,f_userfiles_id,f_userinfo_id,f_type`,
        orderitem: 'f_userfiles_id'}},
      {resolveMsg: null, rejectMsg: null})
    if (getSurplus.data.length > 0) {
      self.row.f_surplus_id = getSurplus.data[0].id
      self.model.f_collection = getSurplus.data[0].f_surplus_fee
    }
    self.model.f_price = getSurplus.data[0].f_price
    // 获取当前票号用
    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 {
        config: {
          // 控制附件显示
          showupload: false,
          hasPrint: false,  // 默认打票
          hasBillManage: false,  // 默认不启用发票管理
          billType: '燃气费',   // 票据类型（燃气费，其他费用，调用的发票代码不同）
          printType: '普通收据', // 收据/电子票/专用发票/国税发票
          payment: '现金缴费'
        },
        model: {
          f_compensation_type: '调价补费',
          f_print: '',
          f_payment: '',
          f_collection: ''
        },
        blodid: '',
        // 启用发票管理需要对票号进行验证
        hasValidateBill: false,
        validateOk: false,
        print: false,
        billData: {
          url: 'rs/report/compensation_bill',
          billnumber: ''
        },
        paymentModel: [],
        mulPrint: false,
        clickConfirm: false, // 控制确认按钮只能点击一次
        // 下拉框值
        paytype: this.$appdata.getParam('付款方式'),
        printstyle: this.$appdata.getParam('打印格式'),
        compensationTypes: [{label: '调价补费', value: '调价补费'}, {label: '调价退费', value: '调价退费'}]
      }
    },
    props: ['row'],
    ready () {
      asyncCardMeterCenter(this)
    },
    watch: {
      'model.f_payment.length' (val) {
        console.log('付款方式多选。。', val)
        if (val > 1 && !this.model.f_preamount) {
          this.model.f_payment = ['现金缴费']
          this.$showAlert('请先计算付款金额', 'warning', 2000)
        } else {
          this.paymentModel = []

          this.model.f_payment.forEach((res) => {
            let temp = {
              f_payment: res,
              f_money: 0
            }
            this.paymentModel.push(temp)
          })
          this.$resetValidation()
        }
      }
    },
    methods: {
      async confirm () {
        this.clickConfirm = true
        this.$dispatch('no-button')
        this.model.f_userinfo_id = this.row.f_userinfo_id
        this.model.f_userfiles_id = this.row.f_userfiles_id
        this.model.f_surplus_id = this.row.f_surplus_id
        this.model.f_user_id = this.row.f_user_id
        this.model.f_total_fee = (this.row.f_total_fee - 0)
        this.model.f_total_gas = (this.row.f_total_gas - 0)
        this.model.f_balance = this.row.f_balance - 0
        this.model.f_curbalance = this.row.f_curbalance - 0
        this.model.f_user_name = this.row.f_user_name
        this.model.f_user_type = this.row.f_user_type
        this.model.f_meter_type = this.row.f_meter_type
        this.model.f_price_id = this.row.f_price_id
        this.model.f_meter_brand = this.row.f_meter_brand
        this.model.f_meter_style = this.row.f_meter_style
        this.model.f_stairprice_id = this.row.f_stairprice_id
        this.model.f_gasproperties = this.row.f_gasproperties
        this.model.f_address = this.row.f_address
        this.model.f_collection = (this.model.f_compensation_type == '调价补费' ? this.model.f_collection : (0 - this.model.f_collection))
        this.model.f_times = this.row.f_times
        this.model.f_type = this.model.f_compensation_type
        this.model.f_state = '有效'
        this.model.f_operat_type = this.model.f_compensation_type
        this.model.f_describe = `${this.$login.f.name}对${this.row.f_user_name}进行${this.model.f_compensation_type}操作`
        this.model.f_operator = this.$login.f.name
        this.model.f_operatorid = this.$login.f.id
        this.model.f_orgid = this.$login.f.orgid
        this.model.f_orgname = this.$login.f.orgs
        this.model.f_depid = this.$login.f.depids
        this.model.f_depname = this.$login.f.deps
        // 先调用付款码支付组件流程
        let ss = await this.$refs.paymentcode.flowPath()
        console.log('付款码操作返回', ss)
        if (!ss.result) return
        compensationChargeGen(this)
      },
      clean () {
        this.$info('取消操作')
        this.$dispatch('refresh', this.row)
      },
      validateBill (val) {
        this.validateOk = !val.isOk
        this.billData.bill = val.bill
      },
      printok () {
        // 收据打完，判断是否还有其他票据进行请求
        for (let i = 0; i < this.model.f_print.length; i++) {
          if (this.model.f_print[i] === '电子发票') {
            this.$CommonService.openEticket(this.row.id, '售气收费')
          }
        }
        this.$dispatch('success')
      },
      close () {
        this.print = false
        this.clean()
      }
    }
  }
</script>

<style>
</style>
