<template>
  <div class="auto">
    <validator name='v'>
      <form novalidate class="form-horizontal">
        <div class="row" style="margin-top:5px;" 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:5px;">
          <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:10px;"  v-if='lose'>
          <div class="col-sm-4" :class="[$v.payment.required ? 'has-error' : '']">
            <label class=" font_normal_body" title="参数名称：付款方式">收款方式</label>
            <input type="text" v-show="false" v-model="$refs.payment.selectedItems"  v-validate:payment='{required: true }'>
            <v-select v-model="model.f_payment"
                      placeholder='请选择'
                      :value.sync="model.f_payment"
                      :options='paytype'
                      v-ref:payment
                      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="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-4" :class="[$v.f_cardfees.required ? 'has-error' : '']">
            <label class=" font_normal_body">补&emsp;卡&emsp;费</label>
            <input class="input_search" style="width:60%" v-validate:f_cardfees='{required: true }' type="number" v-model="model.f_cardfees">
          </div>
        </div>
        <div class="row" style="margin-top:5px;">
          <div class="col-sm-4" :class="[$v.f_fill_type.required ? 'select-error' : '']">
            <label for="f_print" title="参数名称:补卡种类" class="font_normal_body">补卡种类</label>
            <input type="text" v-show="false" v-model="model.f_fill_type"  v-validate:f_fill_type='{required: true }'>
            <v-select v-model="model.f_fill_type"
                      placeholder='请选择'
                      :value.sync="model.f_fill_type"
                      :options='filltypes'
                      v-ref:f_fill_type
                      close-on-select clear-button>
            </v-select>
          </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>-->



        <div class="row" style="margin-top:5px;">
          <label for="f_comments" class="font_normal_body">备&emsp;&emsp;注</label>
          <input class="input_search" style="width:87%" v-model="model.f_comments" 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>
      <ticket-print  :show="eticket_show" @toggle="eticket_toggle"  v-ref:eticketbill></ticket-print>
      <modal :show.sync="eticket_msg" v-ref:modal large backdrop="false" :width="900">
        <header slot="modal-header" class="modal-header">
          <button type="button" class="close" @click="eticket_msg = false"><span>&times;</span></button>
          <h4 class="modal-title">发票信息</h4>
        </header>
        <article slot="modal-body" class="modal-body">
          <div class="auto select-overspread form-horizontal">
            <div class="row auto">
              <div class="col-sm-6 form-group form-input-group" :class="[!row.f_paper_name ? 'has-error' : '']">
                <label class="control-label">开票名称:</label>
                <input class="form-control col-sm-2" :disabled="true"
                       v-model="row.f_paper_name" placeholder="开票名称">
              </div>
              <div class="col-sm-6 form-group form-input-group">
                <nobr class="col-sm-4"><label class="control-label">是否征税:</label></nobr>
                <v-select v-model="invoice_is_pax"
                          placeholder='请选择'
                          :value.sync="invoice_is_pax"
                          close-on-select
                          :width="60"
                          :value-single="true"
                          :search="false"
                          :options='is_pax' clear-button>
                </v-select>
              </div>
              <div class="col-sm-12 form-group form-input-group">
                <label class="control-label">开户行及账号:</label>
                <input class="form-control col-sm-2" :disabled="true"
                       v-model="row.f_paper_account" placeholder="购方开户行及账号">
              </div>
              <div class="col-sm-12 form-group form-input-group" >
                <label class="control-label">纳税人识别号:</label>
                <input class="form-control col-sm-2" :disabled="true"
                       v-model="row.f_taxpayer_id" placeholder="纳税人识别号">
              </div>
              <div class="col-sm-12 form-group form-input-group" :class="[!row.f_address_phone ? 'has-error' : '']">
                <label class="control-label">开票地址电话:</label>
                <input class="form-control col-sm-2" :disabled="true"
                       v-model="row.f_address_phone" placeholder="开票地址">
              </div>
              <div class="col-sm-12 form-group form-input-group">
                <label class="control-label">邮箱推送:</label>
                <input class="form-control col-sm-2" :disabled="true"
                       v-model="row.f_email" placeholder="邮箱推送">
              </div>
            </div>
          </div>
        </article>
        <footer slot="modal-footer" class="modal-footer">
          <button type="button" class="btn button_search"
                  :disabled="!(row.f_paper_name&&row.f_address_phone)"
                  @click='confirm'>确认收费
          </button>
        </footer>
      </modal>
      <div style="text-align:right;height:auto;margin-top:30px;margin-right:50px;">
        <button class="button_clear" @click="accept()" v-if="config.hasAcceptance">受理单</button>
        <payment-code-button :clickable="!$v.valid || validateOk"
                             :payment.sync="model.f_payment" :payment-data="paytype"
                             @confirm-payment="confirm()">
        </payment-code-button>
        <button class="button_search" @click="checkInvoiceMsg()"  :disabled='!$v.valid || validateOk'>确认</button>
        <button class="button_clear" @click="clean()" >取消</button>
      </div>
    </validator>

    <payment-code v-ref:paymentcode :payment="model.f_payment" :row="row" :money="model.f_cardfees"></payment-code>
  </div>
  <upload :blodid="row.f_userinfo_id" v-if="config.showupload" isremark="true" fusetype="补卡"></upload>

</template>
<script>
import XML from '../../plugins/ObjTree'
import {HttpResetClass} from 'vue-client'
/**
 *综合业务
 *补卡管理组件
 */

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_fill_type = [self.config.filltype]
  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: {
        showupload: false, // 控制附件显示
        hasPrint: true,  // 默认打票
        hasBillManage: false,  // 默认不启用发票管理
        billType: '其他费用',   // 票据类型（燃气费，其他费用，调用的发票代码不同）
        printType: '普通收据', // 收据/电子票/专用发票/国税发票
        payment: '现金缴费',
        filltype: '原卡补卡',
        hasAcceptance: false, // 是否需要打印受理单
        isPickTable: false // 是否添加接表判断（对于那些对次数严格限制的表）
      },
      resid: [],  // 存放新增的f_files表中id
      eticket_msg: false,
      eticket_show: false,
      invoice_is_pax: '征税',
      is_pax: [{label: '征税', value: '征税'}, {label: '不征税', value: '不征税'}],
      model: {
        f_comments: '',
        f_type: 'IC卡丢失或损坏',
        f_cardfees: '',
        f_payment: [],
        f_print: [],
        f_fill_type: [],
        f_replace_time: ''
      },
      printData: {
        reason: '',
        cardfee: ''
      },
      cardallot: null,
      lose: false,
      f_payment: [],
      f_ispick_table: '',
      print: false,
      billData: {
        url: 'rs/report/replace_sell',
        bill: ''
      },
      paytype: this.$appdata.getParam('付款方式') ? this.$appdata.getParam('付款方式') : [],
      printstyle: this.$appdata.getParam('打印格式') ? this.$appdata.getParam('打印格式') : [],
      pickTables: [{label: '已过表', value: '已过表'}, {label: '未过表', value: '未过表'}],
      // 启用发票管理需要对票号进行验证
      hasValidateBill: false,
      validateOk: false,

      acceptprint: false,
      acceptUrl: '',
      filltypes: this.$appdata.getParam('补卡种类') ? this.$appdata.getParam('补卡种类') : []
    }
  },
  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: {
    // 校验发票信息
    checkInvoiceMsg () {
      if (this.model.f_print[0] === '电子发票') {
        if (!this.row.f_taxpayer_id) {
          this.row.f_taxpayer_id = this.row.f_idnumber
        }
        if (!this.row.f_paper_name) {
          this.row.f_paper_name = this.row.f_user_name
        }
        if (!this.row.f_address_phone) {
          this.row.f_address_phone = this.row.f_address + ' ' + this.row.f_user_phone
        }
        if(!this.row.f_email){
          this.row.f_email = this.row.f_email
        }
        this.eticket_msg = true
      } else {
        this.confirm()
      }
    },
    eticket_toggle () {
      this.eticket_show = false
      this.$dispatch('success')
    },
    confirm () {
      this.eticket_msg = false
      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 if (this.row.f_meter_type.indexOf('卡表') === -1) {
        this.writeCard()
      } else {
        this.$showMessage(`请确保你已经插入了IC卡`, ['confirm', 'cancel']).then((res) => {
          if (res === 'confirm') {
            this.writeCard()
          }
        })
      }
    },
    // 写卡保存数据 迁至此处'
    async writeCard () {
      // 如果是付款码支付则显示界面扫用户付款码收钱
      if (this.model.f_type == 'IC卡丢失或损坏' && this.model.f_cardfees - 0 > 0) {
        // 先调用付款码支付组件流程
        let ss = await this.$refs.paymentcode.flowPath()
        this.$refs.paymentcode.paymentCodeShow = false
        console.log('付款码操作返回', ss)
        if (!ss.result) return
      }
      // 加入扫码盒付款码支付流水号
      this.model.f_serial_id = this.$refs.paymentcode.paymentCodeReturnData.f_out_trade_no
      this.row.cardInfo = this.cardData
      this.$CardService.replaceCard(this.model, this.row).then(async (res) => {
          if (this.config.showupload) {
            let param = []
            for (let row of this.resid) {
              param.push({id: row.id})
            }
            let data = {
              param: param,
              f_blobid: res.data.id
            }
            let http = new HttpResetClass()
            await http.load('POST', 'rs/logic/updatefiles', data, {resolveMsg: null, rejectMsg: '补卡上传附件失败！！'})

          }
          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 if (this.model.f_print[0] === '电子发票') {
              this.row.id = res.data.id
              this.eticket_show = true
              await this.$refs.eticketbill.openETicket([res.data.id], this.row, '是', this.invoice_is_pax, '补卡费')
            } 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.model.f_cardfees = 0
        this.lose = false
      }
    }
  },
  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: ''})
    }
  }
}
</script>

<style>
</style>
