<template>
    <div class="auto">
        <validator name='v'>
            <form novalidate class="form-horizontal">
                <div class="row">
                    <div class="col-sm-4 form-group">
                        <label class="font_normal_body" title="参数名称：付款方式">收款方式</label>

                        <v-select v-model="f_payment"
                                  placeholder='请选择'
                                  style="width:60%"
                                  :value.sync="model.f_payment"
                                  :options='paytype'
                                  close-on-select clear-button></v-select>

                    </div>
                    <div class="col-sm-4 form-group">
                        <label for="f_print" class="font_normal_body">打印格式</label>

                        <v-select id="print"
                                  v-model="f_print"
                                  style="width:60%"
                                  placeholder='请选择'
                                  :value.sync="model.f_print"
                                  :options='printstyle'
                                  close-on-select clear-button>
                        </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 form-group">
                        <label class="font_normal_body">剩余金额</label>
                        <input class="input_search" style="width:60%" type="number" v-model="data.f_balance" readonly>
                    </div>
                </div>

                <div class="row">


                    <div class="col-sm-8">
                        <label for="f_paper_account" class="font_normal_body ">&nbsp;&nbsp;&nbsp;备注&nbsp;&nbsp;&nbsp;</label>
                        <input class="input_search" style="width:80%"  v-model="model.f_comments">
                    </div>
                    <div class="col-sm-4 form-group" v-if="!config.overBalance"
                         :class="[$v.f_refund_fee.required || $v.f_refund_fee.dctest ? 'has-error' : 'has-success']">
                        <label class="font_normal_body">退费金额</label>
                        <input class="input_search" style="width:60%" type="number" v-model="model.f_refund_fee"
                               v-validate:f_refund_fee='{required: true,  dctest: [data.f_balance, "<=" ]}' placeholder="退费金额">
                    </div>
                  <div class="col-sm-4 form-group" v-if="config.overBalance"
                       :class="[$v.f_refund_fee.required || $v.f_refund_fee.dctest ? 'has-error' : 'has-success']">
                    <label class="font_normal_body">退费金额</label>
                    <input class="input_search" style="width:60%" type="number" v-model="model.f_refund_fee"
                           v-validate:f_refund_fee='{required: true,  dctest: [0, ">=" ]}' placeholder="退费金额">
                  </div>
                </div>
            </form>
            <div style="text-align:right;">
                <button class="button_search btn-gn" @click="confirm()" :disabled='!$v.valid'>确认</button>
                <button class="button_clear btn-gn" @click="clean()">取消</button>
            </div>
        </validator>
        <validate-bill v-if="hasValidateBill" :data="model" @validate-bill="validateBill"></validate-bill>
        <!--<print-bill :show="print" :bill-manager='config.hasBillManage' v-ref:printbill :bill-url='billUrl' v-on:toggle="clean" @printok="printok" :data='printModel'></print-bill>-->
        <print-bill :show="print" :bill-config='config' :bill-data='billData' v-on:toggle="clean" @printok="printok" :data='printModel'  v-ref:printbill></print-bill>
    </div>

    <upload :blodid="data.f_userinfo_id" :businessid="randomBusinessId" isremark="true" fusetype="退费管理"></upload>
</template>


<script>
    let readyGen = async function (self) {
      await self.$getConfig(self, 'MachineTRefund')
      console.log('机表退费config', self.config)
        // 默认打印格式
      self.blodid = self.data.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.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,  // 默认不启用发票管理
            overBalance: false,   // 为true时退费金额可以大于余额
            printType: '普通收据', // 收据/电子票/专用发票/国税发票
            payment: '现金缴费',
            billType: '燃气费'
          },
          model: {
            f_refund_fee: '',
            f_add_gas: '计入',
            f_comments: '',
            f_payment: '',
            f_print: ''
          },
          addGas: [{label: '计入', value: '计入'}, {label: '不计入', value: '不计入'}],
          blodid: '',
          hasValidateBill: false,
          randomBusinessId: '',
          resid: [],  // 存放新增的f_files表中id
          validateOk: false,

          printModel: {},
          print: false,
          billUrl: '',
          billData: {
            url: 'rs/report/refund_sell',
            bill: ''
          },

                // 下拉框值
          paytype: this.$appdata.getParam('付款方式'),
          printstyle: this.$appdata.getParam('打印格式')
        }
      },
      props: ['data'],
      ready () {
            /* if (this.data.f_billing === '按气量') {
                this.$showAlert('按气量缴费的机表退费功能尚未开放！！', 'warning', 3000)
                this.$dispatch('refresh')
            } else { */
        readyGen(this)
           /* } */
        this.getRandomId()
      },
      events: {
        // 删除Resid数组元素
        'delResid' (val) {
          this.resid.$remove({id: val, f_biobid: ''})
          // this.resid.splice(this.resid.indexOf({id:val,f_biobid:''}),1);
        },
        // 增加Resid数组元素
        'resid' (val) {
          this.resid.push({id: val, f_biobid: ''})
        }
      },
      methods: {
        getRandomId () {
          this.randomBusinessId = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            let res = Math.random() * 16 | 0
            let v = c == 'x' ? res : (res & 0x3 | 0x8)
            return v.toString(16)
          })
        },
        async confirm () {
          let param = {
            f_user_id: this.data.f_user_id,
            f_userfiles_id: this.data.f_userfiles_id,
            version: this.data.version,
            f_refund_fee: this.model.f_refund_fee,
            f_comments: this.model.f_comments,
            f_payment: this.model.f_payment[0],
            f_print: this.model.f_print[0],
            f_price_id: this.data.f_price_id,
            f_add_gas: this.model.f_add_gas,
            f_total_fee: parseFloat(this.data.f_total_fee) - parseFloat(this.model.f_refund_fee),
            f_stairprice_id: this.data.f_stairprice_id,
            operInfo: {
              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
            }
          }
          if (this.model.f_add_gas !== '计入') {
            param.f_total_fee = this.data.f_total_fee
          }
          let res = await this.$resetpost('rs/logic/machineRefund', {data: param}, {warnMsg: `确定要对用户${this.data.f_user_name}进行退费吗？`, resolveMsg: '退费成功！！', rejectMsg: '退费失败！！请重试！！'})
          console.log('机表退费返回的数据==========>', res)
          let param1 = []
          for (let row of this.resid) {
            param1.push({id: row.id})
          }
          let data = {
            param: param1,
            f_blobid: res.data.id
          }
          await this.$resetpost('rs/logic/updatefiles', data)
          if (this.model.f_print.indexOf('电子发票') == -1 && this.config.hasPrint && !this.$login.r.includes('不打印发票')) {
            console.log('this.config.hasBillManage', this.config.hasBillManage)
            if (this.config.hasBillManage) {
                        // 启用发票管理，获取票据管理中的票号并存储记录
              this.printModel.id = res.data.id
              this.printModel.f_bill_type = '退费'
              this.printModel.f_bill_style = this.model.f_print[0]
                        // this.billUrl = 'rs/report/refund_sell'
              this.print = true
            } else {
              this.printModel.id = res.data.id
                        // this.billUrl = 'rs/report/refund_sell'
              this.print = true
            }
          } else if (this.config.printType === '国税发票') {
                    // TODO
            this.$dispatch('success')
          } else if (this.config.printType === '电子发票') {
                    // TODO
            this.$dispatch('success')
          } else {
            this.$dispatch('success')
          }
        },
        clean () {
          this.$dispatch('refresh')
        },
        printok () {
          this.$dispatch('success')
        },
        validateBill (val) {
          this.validateOk = !val.isOk
          this.billData.bill = val.bill
        }
      }
    }
</script>
