<template>
  <div class="auto form-horizontal">
    <modal :show.sync="show" v-ref:modal large backdrop="false">
      <header slot="modal-header" class="modal-header">
        <h3 style="color:black" class="modal-title">收费电子发票</h3>
      </header>
      <article slot="modal-body" class="modal-body">
        <div class="row" style="display: flex;justify-content: center;" v-if="!eticket_src">
          {{ return_msg }}
        </div>
        <iframe :src="eticket_src" v-if="eticket_src" width="100%" height="500px">
        </iframe>
      </article>
      <footer slot="modal-footer" class="modal-footer">
        <button type="button" class="btn btn-default" @click="cancel">{{ '关闭' }}</button>
      </footer>
    </modal>
  </div>
  <print-bill :show="print" :bill-config='config' :bill-data='billData' :data='row' @toggle="close" @printok="printok"  v-ref:printbill></print-bill>
</template>
<script>
import {HttpResetClass} from 'vue-client'
import Vue from 'vue'

export default {
  title: '电子发票',
  data () {
    return {
      eticket_src: '',
      return_msg: '正在开票中，请稍后',
      show: true,
      print: false,
      billData: {
        url: '',
        billnumber: ''
      },
      config: {
        priceCalculation: false, // 划气量控制
        showupload: true,  // 默认不显示附件上传组件
        hasPrint: true,  // 默认打票
        hasBillManage: false,  // 默认不启用发票管理
        billType: '燃气费',   // 票据类型（燃气费，其他费用，调用的发票代码不同）
        printType: '普通收据', // 收据/电子票/专用发票/国税发票
        payment: '现金缴费'
      },
      row: {}
    }
  },
  props: ['show'],
  ready () {
  },
  methods: {
    cancel () {
      console.log('电子哈哈哈，你走了没')
      this.show = !this.show
      this.eticket_src = ''
      this.return_msg = '正在开票中，请稍后'
      this.$dispatch('toggle')
    },
    /**
     * src赋值 外部调用
     *  */
    watch_ch (src) {
      this.eticket_src = src
    },
    // 正常收费开票
    async openEticket (sellid, row, type) {
      try {
        let data = {
          id: sellid,
          hsbs: row.f_whether_pay == '征税' ? 1 : 0,
          f_whether_pay: row.invoice_is_pax ? row.invoice_is_pax.toString() : '征税',
          bz: row.f_eticket_reason ? row.f_eticket_reason : null,
          f_charge_type: type,
          f_dept_id: this.$login.f.depids,
          f_operator: this.$login.f.name,
          f_orgid: this.$login.f.orgid,
          f_orgname: this.$login.f.orgs,
          f_depname: this.$login.f.deps,
          f_operatorid: this.$login.f.id,
          f_buy_name: row.f_paper_name,
          f_pay_id: row.f_taxpayer_id,
          f_buy_address: row.f_address_phone,
          f_buy_openbank: row.f_paper_account
        }
        let getEticket = await Vue.resetpost('rs/logic/combineData', data, {resolveMsg: null, rejectMsg: '组织发票数据出错'})
        // 请求电子票
        console.log('getEtocket', getEticket)
        // 请求失败继续请求, 最多三次
        let res = ''
        for (let i = 0; i < 3; i++) {
          try {
            res = await Vue.resetpost('rs/logic/openEticket', {id: getEticket.data.eticketid}, {resolveMsg: '开票成功', rejectMsg: null})
          } catch (error) {
            console.log(i + '次开票失败', error)
            if (i == 2) Vue.showAlert(`电子发票开票失败！！请到发票管理重新开票。错误原因: ${JSON.stringify(error)}。`, 'danger', 0)
          }
          if (res.data.code == 200 && res.data.f_bill_url != '') {
            break
          }
        }
        console.log(res)
        if (res.data.code == 200 && res.data.f_bill_url != '') {
          this.show = false
          this.billData.url = this.getBillUrl(type)
          this.row.id = sellid
          this.row.f_bill_type = type
          this.print = true
        } else {
          this.show = !this.show
        }
        console.log('返回发票地址', res.data.f_bill_url)
      } catch (error) {
        console.log('电子发票开票失败', JSON.stringify(error))
        Vue.showAlert(`电子发票开票失败！！请到发票管理重新开票。错误原因: ${JSON.stringify(error)}。`, 'danger', 0)
      }
    },
    // 冲红开票
    async redOpenEticket (row) {
      this.show = !this.show
      console.log('resdata', row)
      row.f_dept_id = this.$login.f.depids
      row.f_operator = this.$login.f.name
      row.f_orgid = this.$login.f.orgid
      row.f_orgname = this.$login.f.orgs
      row.f_depname = this.$login.f.deps
      row.f_operatorid = this.$login.f.id
      let result = await Vue.resetpost('rs/logic/correctEticket', {data: row}, {resolveMsg: null, rejectMsg: '组织冲红数据失败'})
      try {
        if (result) {
          console.log('res', result)
          let rest = await Vue.resetpost('rs/logic/redEticket', {data: {eticket_id: result.data.eticket_id, org_eticket_id: result.data.f_red_info_code}}, {resolveMsg: '', rejectMsg: '冲红失败'})
          console.log('???', rest)
          if (rest.data.status == 200 && rest.data.f_bill_url != '') {
            this.eticket_src = rest.data.f_bill_url != '' ? rest.data.f_bill_url : rest.data.msg
          } else {
            let rollback = {
              id: result.data.eticket_id, // 此id为冲红记录id
              f_eticket_id: row.f_eticket_id // 为原发票id
            }
            await Vue.resetpost('rs/logic/rollBackEticket', {data: rollback}, {resolveMsg: '', rejectMsg: '冲红异常请求异常回滚失败'})
            this.return_msg = `冲红失败，原因:${rest.data.msg}`
          }
          console.log('返回发票地址', this.eticket_src, this.return_msg)
        }
      } catch (e) {
        console.log('异常处理一下,需要删除冲红记录，修改原发票桩体')
        let rollback = {
          id: result.data.eticket_id, // 此id为冲红记录id
          f_eticket_id: row.f_eticket_id // 为原发票id
        }
        await Vue.resetpost('rs/logic/rollBackEticket', {data: rollback}, {resolveMsg: '', rejectMsg: '冲红异常请求异常回滚失败'})
      }
    },
    getBillUrl (type) {
      let name = ''
      // 根据type数据 选择调用的Logic
      if (type === '换表费') {
        console.log('看看row..', this.row)
        name = 'rs/report/change_meter'
      } else if (type === '机表收费') {
        name = 'rs/report/machine_bill'
      } else if (type === '物联网收费') {
        name = 'rs/report/iot_bill'
      } else if (type === '超用收费') {
        name = 'rs/report/overuse_bill'
      } else if (type === '其他收费') {
        name = 'rs/report/otherCharge_bill'
      } else if (type === '补卡费') {
        name = 'rs/report/replace_sell'
      } else if (type === '发卡售气') {
        name = 'rs/report/sendCard_bill'
      } else if (type === '卡表收费') {
        name = 'rs/report/card_bill'
      } else if (type === '预存缴费') {
        name = 'rs/report/pre_sell'
      }
      return name
    },
    printok () {
      this.$dispatch('success')
    },
    close () {
      this.print = false
      this.clean()
    },
    clean () {
      this.$dispatch('refresh', this.row)
    }
  },
  watch: {},
  events: {}
}
</script>
<style>
</style>
