<template>
  <div class="auto">
    <validator name='v'>
      <form novalidate class="form-horizontal">
        <div class="row" style="margin-top:10px;" v-if="config.isPickTable">

          <div class="col-sm-3" :class="[$v.pick.required ? 'select-error' : '']">
            <label class=" font_normal_body">是否接表</label>
              <input type="text" v-show="false" v-model="$refs.pick.selectedItems"
                     v-validate:pick='{required: true }'>
              <v-select v-model="f_ispick_table"
                        placeholder='请选择'
                        :value.sync="model.f_ispick_table"
                        :options='pickTables'
                        :value-single="true"
                        close-on-select clear-button v-ref:pick></v-select>
          </div>
        </div>

        <div class="row" style="margin-top:10px;">
          <label class="radio-inline col-sm-3">
            <input type="radio" value="IC卡丢失或损坏" v-model="model.f_type" class="magic-radio" checked id="type_two">
            <label for="type_two">IC卡丢失或损坏</label>
            <!-- <strong>IC卡丢失或损坏</strong> -->
          </label>
          <label class="radio-inline col-sm-4" v-if="row.f_meter_type !== '机表'">
            <input type="radio" value="IC卡信息错乱" v-model="model.f_type" class="magic-radio" id="type_three">
            <label for="type_three">IC卡信息错乱</label>
            <!-- <strong>IC卡信息错乱</strong> -->
          </label>
          <label class="radio-inline col-sm-3" v-if="row.f_meter_type !== '机表'">
            <input type="radio" value="其他" v-model="model.f_type" class="magic-radio" id="type_four">
            <label for="type_four">其他</label>
            <!-- <strong>其他</strong> -->
          </label>
        </div>

        <div class="row" style="margin-top:30px;"  v-if='lose'>
          <div class="col-sm-3">
            <label class=" font_normal_body">付款方式</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-3" :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 class="col-sm-3">
            <label class=" font_normal_body">&nbsp;&nbsp;&nbsp;卡费&nbsp;&nbsp;&nbsp;</label>
              <input class="input_search" style="width:60%" type="number" v-model="model.f_cardfees">
          </div>
        </div>
        <div class="row" style="margin-top:10px;" v-if="model.f_type === '其他'" :class="[$v.f_reason.required ? 'has-error' : 'has-success']">
          <label for="f_reason" class=" font_normal_body">补卡原因</label>
            <input class="input_search" style="width:60%" v-model="model.f_reason" v-validate:f_reason='{required: true }'
                       placeholder="补卡原因" />
        </div>
      </form>
      <accept-bill :show="acceptprint" :bill-url='acceptUrl' v-on:toggle="close" :data='row' :billdata="printData" @closeaccept="closeAccept" v-ref:acceptbill></accept-bill>
      <validate-bill v-if="hasValidateBill && lose" :data="model" @validate-bill="validateBill"></validate-bill>
      <print-bill :show="print" :bill-config='config' :bill-data='billData' v-on:toggle="close" @printok="printok"  :data='row' v-ref:printbill></print-bill>
      <div style="text-align:right;height:auto;margin-top:30px;margin-right:50px;">
        <button class="button_clear" @click="accept()" v-if="config.hasAcceptance">受理单</button>
        <button class="button_search" @click="confirm()"  :disabled='!$v.valid || validateOk'>确认</button>
        <button class="button_clear" @click="clean()" >取消</button>
      </div>
    </validator>
  </div>
</template>
<script>
  /**
   *综合业务
   *补卡管理组件
   */

   let asyncReplaceManage = async function(self){
    await self.$getConfig(self,'ReplaceCardManage')
    console.log('补卡config', self.config)
    self.model.f_print = self.config.printType instanceof Array ? self.config.printType : [self.config.printType]
    self.model.f_payment = [self.config.payment]
    if (self.config.isPickTable) {
      self.model.f_ispick_table = '已过表'
    }

    self.model.f_use_type = self.config.billType
    self.model.f_bill_type = self.model.f_print
    self.hasValidateBill = self.config.hasBillManage

    self.fillcardChange(self.model.f_type)
   }


  export default {
    title: '补卡管理',
    data () {
      return {
        config: {
          hasPrint : true,  //默认打票
          hasBillManage : false,  //默认不启用发票管理
          billType: '其他费用',   // 票据类型（燃气费，其他费用，调用的发票代码不同）
          printType: '普通收据', // 收据/电子票/专用发票/国税发票
          payment: '现金缴费',
          hasAcceptance: false, // 是否需要打印受理单
          isPickTable: false // 是否添加接表判断（对于那些对次数严格限制的表）
        },
        model: {
          f_reason: '',
          f_type: 'IC卡丢失或损坏',
          f_cardfees: '',
          f_payment: [],
          f_print: [],
          f_replace_time: ''
        },
        printData:{
          reason: '',
          cardfee: ''
        },
        cardallot: null,
        lose: false,

        print: false,
        billData: {
          url: 'rs/report/replace_sell',
          bill: ''
        },
        paytype: this.$appdata.getParam('付款方式') ? this.$appdata.getParam('付款方式') : [],
        pickTables: [{label: '已过表', value: '已过表'}, {label: '未过表', value: '未过表'}],
        // 启用发票管理需要对票号进行验证
        hasValidateBill: false,
        validateOk: false,

        acceptprint: false,
        acceptUrl: ''
      }
    },
    props: ['row', 'cardData'],
    ready () {
      asyncReplaceManage(this).then(()=>{
        this.$emit(ready())
      }).catch((error)=>{
        this.$emit('error',error)
      })
    },
    watch: {
      'model.f_type' (val) {
        this.fillcardChange(val)
      }
    },
    methods: {
      confirm () {
        this.$dispatch('no-button')
        // 判断是否接表提示
        if (this.config.isPickTable) {
          this.$showMessage(`您确定客户${this.model.f_ispick_table}了吗？`, ['confirm', 'cancel']).then((res) => {
            if (res === 'confirm') {
              this.writeCard()
            }
          })
        } else {
          this.writeCard()
        }
      },
      // 写卡保存数据 迁至此处
      writeCard () {
        this.row.cardInfo = this.cardData
        this.$CardService.replaceCard(this.model, this.row).then((res) => {
              console.log('补卡返回。。', res)
              if(this.config.hasPrint && this.lose){
                if(this.config.hasBillManage){
                  this.row.id = res.data.id
                  this.row.f_bill_type = '补卡'
                  this.row.f_bill_style = this.model.f_print[0]
                  this.print = true
                } else{
                  console.log('不保存打票记录')
                  this.row.id = res.data.id
                  this.print = true
                }
              }else {
                console.log("我没走打票")
                this.$dispatch('success', '补卡管理', this.row, res)
              }
            }
          ).catch(
          (error) => {
            if (error.status === 603) {
              this.$error('重复提交')
              return
            }
            this.$dispatch('error', '补卡管理', this.row, error)
          }
        )
      },
      closeAccept () {
        this.acceptprint = false
      },
      accept () {
        // 打印受理单
        console.log('受累单中model',this.model)
        this.printData.reason = this.model.f_comments? `'${this.model.f_reason}'` : `'${this.model.f_type}'`
        this.printData.cardfee = this.model.f_cardfees ? `'${this.model.f_cardfees}'` : `'${0}'`
        console.log('受累单中printData',this.printData)
        this.acceptUrl = 'rs/report/acceptcard_bill'
        this.acceptprint = true
      },
      clean () {
        this.$dispatch('refresh')
      },
      close () {
        this.print = false
        this.acceptprint = false
        this.clean()
      },
      validateBill (val) {
        this.validateOk = !val.isOk
        this.billData.bill = val.bill
      },
      printok () {
        // 收据打完，判断是否还有其他票据进行请求 TODO
        this.$dispatch('success')
      },
      fillcardChange (val) {
        if (val === 'IC卡丢失或损坏') {
          this.lose = true
          this.model.f_cardfees = this.$appdata.getSingleValue('默认卡费')
        } else {
          this.lose = false
        }
      }
    }
  }
</script>

<style>
</style>
