<template>
  <div class="auto">
    <modal :show.sync="show" v-ref:modal large backdrop="false" style="overflow-y: auto !important;">
      <header slot="modal-header" class="modal-header" style="text-align: center;">
        <h4 class="modal-title">{{data.type}}票据补打</h4>
      </header>
      <article slot="modal-body" class="modal-body">
        <validator name='v'>
          <form class="form-horizontal  select-overspread">
            <div class="row" style="display: flex;justify-content: center;" id='reissue-bill'>
              {{{bill.data}}}
            </div>
            <div class="row" v-if="config.hasBillManage">
              <div v-if="!messShow">
                <!--<span><strong>发票号:{{model.f_using_number}}</strong></span>-->
                <div v-if="model.f_rprint_type === 'new'">
                  <div class="form-group form-input-group col-sm-4">
                    <label class="control-label col-sm-2">新票号:</label>
                    <div class="col-sm-2">
                      <input type="text" class="form-control col-sm-2" v-model="model.newNumber.number" readonly>
                    </div>
                  </div>
                </div>
                <div v-if="model.f_rprint_type === 'old'">
                  <div class="form-group form-input-group col-sm-4">
                    <label class="control-label col-sm-2">原票号:</label>
                    <div class="col-sm-2">
                      <input type="text" class="form-control col-sm-2" v-model="model.oldNumber.number" readonly>
                    </div>
                  </div>
                </div>

              </div>
            </div>
            <div class="row" v-if="config.hasBillManage" style="margin-top: 1%">
              <div class="form-group form-input-group col-sm-4">
                <label class="col-sm-2 control-label">补打类型:</label>
                <div class="col-sm-2">
                  <v-select
                    v-model="model.f_rprint_type"
                    placeholder='请选择'
                    :value.sync="model.f_rprint_type"
                    :options='rprinttype'
                    :value-single="true"
                    :disabled="isOnlyNew"
                    @change="printTypeChane"
                    close-on-select clear-button>
                  </v-select>
                </div>
              </div>
              <div v-if="isOnlyNew">

                <div class="form-group form-input-group col-sm-4" :class="[$v.billtype.required ? 'has-error' : 'has-success']">
                  <label class="col-sm-2 control-label">票据类型</label>
                  <div class="col-sm-2" >
                    <v-select :value.sync="model.f_bill_type"
                              v-model="model.f_bill_type"
                              :options='printtypes'
                              placeholder='请选择'
                              v-model="model.f_bill_type"
                              @change="useTypeChange"
                              :value-single="true"
                              close-on-select v-ref:billtype>
                    </v-select>
                    <input type="text" v-show="false" v-model="$refs.billtype.selectedItems" v-validate:billtype='{required: true }'>
                  </div>
                </div>

                <div class="form-group form-input-group col-sm-4" :class="[$v.usetype.required ? 'select-error' : '']">
                  <label class="col-sm-2 control-label">使用类型</label>
                  <div class="col-sm-2" >
                    <v-select :value.sync="model.f_use_type"
                              v-model="model.f_use_type"
                              :options='usetypes'
                              placeholder='请选择'
                              v-model="model.f_use_type"
                              @change="useTypeChange"
                              :value-single="true"
                              close-on-select v-ref:usetype>
                    </v-select>
                    <input type="text" v-show="false" v-model="$refs.usetype.selectedItems" v-validate:usetype='{required: true }'>
                  </div>
                </div>

              </div>



            </div>
            <div class="row" style="margin-top: 1%">
              <div class="form-group form-input-group col-sm-12">
                <label for="f_cause" class=" col-sm-2 control-label">补打原因:</label>
                <div class="col-sm-10">
              <textarea class="form-control" v-model="model.f_cause" rows="1" placeholder="补打原因"></textarea>
                </div>
              </div>
            </div>
          </form>
        </validator>
      </article>
      <footer slot="modal-footer" class="modal-footer">
        <button type="button" class="btn btn-success" @click='print(true)' :disabled="!$v.valid">选择打印机打印</button>
        <button type="button" class="btn btn-success" @click='print()' :disabled="!$v.valid">打印</button>
        <report-print id='reissue-bill' top='5mm' left='5mm'  width='90%'  height='80%' :notrepeat="false" :showbtn="false" v-ref:reportprint></report-print>
        <button class="btn btn-default" @click="clean()">取消</button>
      </footer>
    </modal>
  </div>
</template>
<script>
  /**
   *票据补打
   */

  import { DataModel } from 'vue-client'

  let readyGen = async function (self) {
    await self.$getConfig(self, 'ReissueBill')
    console.log('补打业务config', self.config)
    await getBillData(self)
  }

  let getBillGen = async function (self) {
    // 判断发票管理是否启用
    if (self.config.hasBillManage) {
      if (self.model.f_rprint_type === 'old') {
        await getOld(self)
      } else {
        await getNew(self)
      }
    }
  }

  let getOld = async function (self) {
    let param = {
      id: self.data.id,
      type: self.data.type
    }
    let getOld = await self.$resetpost('rs/logic/sale_getOldBillNumber', param, {resolveMsg: null, rejectMsg: null})
    console.log('获取原始票号', getOld)
    // 验证原始票号是否存在
    if (getOld.data.id && getOld.data.number) {
      self.model.oldNumber.number = getOld.data.number
      self.model.oldNumber.id = getOld.data.id
    } else {
      self.$showAlert('此次正常操作时没有出票，只能使用新票号进行补打', 'warning', 2000)
      self.model.f_rprint_type = 'new'
      self.isOnlyNew = true
    }
  }

  let getNew = async function (self) {
    // 获取原来收费记录使用的发票类型
    let param = {
      id: self.data.id,
      type: self.data.type
    }
    let oldUseType = await self.$resetpost('rs/logic/sale_getOldUseType', param, {resolveMsg: null, rejectMsg: '获取原始票据信息出错！！'})
    console.log('获取原始票据信息。。。', oldUseType)

    let newparam = {
      f_bill_user: self.$login.f.name, // 票据使用人
      f_filialeids: self.$login.f.orgid // 所属分公司
    }

    if (oldUseType.data.billtype && oldUseType.data.f_use_type) {
      newparam.f_bill_type = oldUseType.data.billtype
      newparam.f_use_type = oldUseType.data.f_use_type
    } else {
      if (self.model.f_use_type && self.model.f_bill_type) {
        newparam.f_bill_type = self.model.f_bill_type
        newparam.f_use_type = self.model.f_use_type
      } else {
        self.isOnlyNew = true
        // self.model.f_bill_type = '普通收据'
        self.$showAlert('请选择票据使用类型', 'warning', 2000)
        return
      }
    }
    let getNew
  try {
    getNew = await self.$resetpost('rs/logic/sale_getNewBillNumber', newparam, {resolveMsg: null, rejectMsg: null})
  } catch (e) {
    self.model.newNumber.number = ''
    self.model.newNumber.id = ''
    self.$showAlert('未获取到发票号', 'warning', 2000)
    return
  }
    console.log('获取新票号', getNew)
    self.model.newNumber.number = getNew.data.number
    self.model.newNumber.id = getNew.data.id
  }

  /**
   * ready执行过程
   */
  let getBillData = async function (self) {
    // 显示票据
    self.bill = new DataModel(self.data.billUrl, {reprint: "'补打'", operator: `'${self.$login.f.name}'`})
    await self.bill.search(self.data.id)
    // self.bill.data = '我是补打发票'
    await getBillGen(self)
  }

  export default {
    title: '票据补打',
    data () {
      return {
        config: {
          hasBillManage: false  // 默认不启用发票管理
        },
        bill: Object,
        model: {
          oldNumber: {
            number: '',
            id: ''
          },
          newNumber: {
            number: '',
            id: ''
          },
          f_end_number: null,
          f_cause: null,
          f_rprint_type: 'new'
        },
        messShow: false,

        isOnlyNew: false,
        rprinttype: [{label: '原票号补打', value: 'old'}, {label: '新票号补打', value: 'new'}],
        usetypes: this.$appdata.getParam('发票使用类型'),
        printtypes: this.$appdata.getParam('分配票据格式')
      }
    },
    props: ['show', 'data', 'billUrl'],
    ready () {
      readyGen(this)
    },
    methods: {
      printTypeChane () {
        if (this.model.f_rprint_type === 'new') {
          getNew(this)
        } else {
          getOld(this)
        }
      },

      useTypeChange () {
        if (this.model.f_rprint_type === 'new') {
          getNew(this)
        }
      },
      clean () {
        this.$dispatch('cancel', '票据补打', this.row)
      },
      async print (select) {
        if (this.config.hasBillManage && !this.model.newNumber.number) {
          this.$showMessage('当前没有票号')
          return
        }
        // 进行补打
        try {
          if ((this.data.id+" ").includes('(')) {
            this.data.id = this.data.id.replace('(', '')
            this.data.id = this.data.id.replace(')', '')
            this.data.id = this.data.id.split(',')[0]
          }
          let param = {
            items: '*',
            tablename: 't_billdetail',
            condition: ` 1=1 and f_charge_id = '${this.data.id}' and f_type = '${this.data.f_bill_type}'`,
            orderitem: 'id'
          }
          let res = await this.$resetpost('rs/sql/singleTable_OrderBy', {data: param}, {resolveMsg: null, rejectMsg: '获取补票数据出错！！'})
          if (res.data.length > 0) {
            let confirm = await this.$showMessage(`这是第${res.data.length + 1}次打印,确认要补打票据吗?`, ['confirm', 'cancel'])
            if (confirm === 'confirm') {
              console.log('开具收据的参数：', this.data.id, this.data.f_bill_type)
              if (this.config.hasBillManage) {
                await this.$CommonService.reissuePaperBill(this.data.id, this.data.f_bill_type, this.model)
              } else {
                this.data.f_cause = this.model.f_cause
                await this.$resetpost('rs/logic/sale_billReprint', {data: this.data}, {resolveMsg: null, rejectMsg: '票据补打出错！！'})
              }
              console.log('开始打印、、', select)
              if (select) {
                this.$refs.reportprint.print(true)
              } else {
                this.$refs.reportprint.print()
              }
            }
          } else {
            console.log('开具收据的参数：', this.data.id, this.data.f_bill_type)
            if (this.config.hasBillManage) {
              await this.$CommonService.reissuePaperBill(this.data.id, this.data.f_bill_type, this.model)
            } else {
              this.data.f_cause = this.model.f_cause
              await this.$resetpost('rs/logic/sale_billReprint', {data: this.data}, {resolveMsg: null, rejectMsg: '票据补打出错！！'})
            }
            console.log('开始打印、、', select)
            if (select) {
              this.$refs.reportprint.print(true)
            } else {
              this.$refs.reportprint.print()
            }
          }
        } catch (error) {
          this.$dispatch('refresh')
        }
      }
    },
    events: {
      'print' () {
        console.log('发送补打成功事件')
        this.$dispatch('reissue-success')
      },
      'print-error' () {
        this.$showAlert('打印失败，若有需要，请补打发票', 'error', 3)
        this.$dispatch('error', '票据补打', this.data, null)
      }
    }
  }
</script>

<style>
</style>
