<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>
</template>
<script>
import {HttpResetClass} from 'vue-client'

export default {
  title: '电子发票',
  data () {
    return {
      eticket_src: '',
      return_msg: '收到开票请求，正在查询开票状态，请稍后',
      show: true
    }
  },
  props: ['show'],
  ready () {
  },
  methods: {
    cancel () {
      console.log('电子哈哈哈，你走了没')
      this.eticket_src = ''
      this.return_msg = '正在查询中，请稍后'
      this.$dispatch('toggle')
    },
    //* 公用保存信息接口
    async save_msg (obj) {
      let model = {
        id: obj.f_eticket_id,
        f_bill_code: obj.f_bill_code ? obj.f_bill_code : undefined,
        f_bill_number: obj.f_bill_number ? obj.f_bill_number : undefined,
        f_jym: obj.f_jym ? obj.f_jym : undefined,
        f_bill_url: obj.f_bill_url ? obj.f_bill_url : undefined,
        f_red_url: obj.f_red_url ? obj.f_red_url : undefined,
        f_bill_state: obj.f_bill_state,
        f_sign_result: obj.f_sign_result ? obj.f_sign_result : undefined,
        f_sign_time: obj.f_sign_time ? obj.f_sign_time : undefined
      }
      await this.$resetpost('rs/entity/t_eticket', model, {resolveMsg: null, rejectMsg: '保存发票记录失败'})
      this.$dispatch('search')
    },
    async openETicket (sellId, row, show_gas, is_pax, type) {
      try {
        let model = {
          id: sellId,
          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_filialeids: this.$login.f.f_orgids,
          f_buy_name: row.f_paper_name,
          f_pay_id: row.f_taxpayer_id,
          f_buy_address: row.f_address_phone,
          f_mail_push: row.f_email,
          f_buy_openbank: row.f_paper_account,
          invoice_show_gas: show_gas === '是',
          is_pax: is_pax === '征税'
        }
        console.log('组织开票数据并保存', model)
        // TODO 组织开票数据并保存
        let ticket_id = await this.$resetpost('rs/logic/combineData_new', model, {resolveMsg: null, rejectMsg: '保存开票信息失败'})
        return this.openEticketGen(ticket_id.data)
      } catch (error) {
        this.$showAlert(`电子发票开票失败！！请到发票管理重新开票。错误原因: ${JSON.stringify(error)}。`, 'danger', 0)
      }
    },
    async openCustETicket (custModel, invoice_is_pax) {
      try {
        let model = Object.assign({
          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_filialeids: this.$login.f.f_orgids,
          f_buy_name: custModel.f_paper_name,
          f_pay_id: custModel.f_taxpayer_id,
          f_buy_address: custModel.f_address_phone,
          f_mail_push: custModel.f_email,
          f_buy_openbank: custModel.f_paper_account,
          invoice_show_gas: !!(custModel.amount && custModel.price),
          detail_price: {amount: custModel.amount, price: custModel.price, name: custModel.name, money: custModel.money},
          is_pax: invoice_is_pax === '征税'
        }, custModel)
        // TODO 组织开票数据并保存
        let ticket_id = await this.$resetpost('rs/logic/TCcombineCustData', model, {resolveMsg: null, rejectMsg: '保存开票信息失败'})
        return this.openEticketGen(ticket_id.data)
      } catch (error) {
        this.$showAlert(`电子发票开票失败！！请到发票管理重新开票。错误原因: ${JSON.stringify(error)}。`, 'danger', 0)
      }
    },
    /**
     * src赋值 外部调用
     *  */
    watch_ch (src) {
      this.eticket_src = src
    },
    /**
     * 电票查询 外部调用
     * */
    fp_search (row, ticket_id) {
      // 通过收费记录id查询
      let http = new HttpResetClass()
      http.load('POST', '/invoice/rs/logic/GXQueryInvoice', {eticket_id: ticket_id}, {
        resolveMsg: null,
        rejectMsg: null
      }).then((req) => {
        if (req.data.code !== 'E0000') {
          this.$showAlert('电子票查询出错,暂无错误信息.请联系管理员', 'danger', 5000)
          return
        }
        req = req.data
        let model
        if (req && req.code === 'E0000') {
          if (req.data.status === '2') {
            model = {
              id: ticket_id,
              f_bill_code: req.data.invoiceCode,
              f_bill_number: req.data.invoiceNo,
              f_jym: req.data.checkCode,
              f_bill_url: req.data.pdfUrl,
              f_sign_result: req.data.statusMsg,
              f_bill_state: '开票成功'
            }
            this.eticket_src = req.data.pdfUrl
          } else if (req && !['2', '20', '21', 2, 20, 21].includes(req.data.status)) {
            model = {
              id: row.id,
              f_bill_state: '开票失败',
              f_sign_result: req.data.statusMsg
            }
            this.return_msg = ' 开票失败。' + req.data.statusMsg
          } else {
            model = {
              id: ticket_id,
              f_bill_state: '等待查询',
              f_sign_result: req.data.statusMsg
            }
            this.return_msg = '请稍后再试。' + req.data.statusMsg
          }
          this.$resetpost('rs/entity/t_eticket', model, {resolveMsg: null, rejectMsg: '保存发票记录失败'}).then(
            res => this.$dispatch('search')
          )
        } else {
          this.save_msg({
            f_eticket_id: ticket_id,
            f_sign_result: '查询超时请再次尝试。',
            f_bill_state: '查询失败'
          })
          this.return_msg = '发票已经开具,查询发票状态超时,请前往发票管理重新尝试'
        }
      }
      )
    },
    /** 冲红
     * */
    async rushRedInvoice (ticket_id) {
      try {
          // 否则正常打票
        let time = 0
        let result = await this.$resetpost('/invoice/rs/logic/GXGetInvoice', {eticket_id: ticket_id}, {
          resolveMsg: null,
          rejectMsg: '发票冲红失败!!'
        })
        result = result.data
        if (result && result.code === 'E0000') {
          // TODO 开票成功 保存发票详情
          await this.save_msg({
            f_eticket_id: ticket_id,
            f_bill_state: '等待查询'
          })
        // TODO 开票成功 进行查询
          let interval = await setInterval(() => {
          // 2秒一轮回
            let http = new HttpResetClass()
            http.load('POST', '/invoice/rs/logic/GXQueryInvoice', {eticket_id: ticket_id}, {
              resolveMsg: null,
              rejectMsg: null
            }).then(req => {
              if (req.data.code !== 'E0000') {
                clearInterval(interval)
                this.save_msg({
                  f_eticket_id: ticket_id,
                  f_sign_result: '查询超时请再次尝试。',
                  f_bill_state: '查询失败'
                })
                this.$showAlert('电子票查询出错,暂无错误信息,请前往发票管理重新尝试', 'danger', 5000)
                return
              }
              req = req.data
              if (req && req.code === 'E0000' && req.data.status === '2') {
              // 组织数据
                clearInterval(interval)
              // TODO 成功后保存发票详情
                this.save_msg({
                  f_eticket_id: ticket_id,
                  f_bill_code: req.data.invoiceCode,
                  f_bill_number: req.data.invoiceNo,
                  f_jym: req.data.checkCode,
                  f_bill_url: req.data.pdfUrl,
                  f_sign_result: req.data.statusMsg,
                  f_bill_state: '冲红'
                })
                this.eticket_src = req.data.pdfUrl
              } else if (req && !['2', '20', '21', 2, 20, 21].includes(req.data.status)) {
                clearInterval(interval)
              // TODO 失败后保存发票详情
                this.save_msg({
                  f_eticket_id: ticket_id,
                  f_sign_result: req.data.statusMsg,
                  f_bill_state: '开票失败'
                })
                this.return_msg = '电子票查询出错,错误【' + req.data.statusMsg + '】,错误代码【' + req.code + '】,请前往发票管理重新尝试'
              } else {
                if (time == 80) {
                // 三十秒后无效
                // TODO 查询失败后保存发票详情
                  this.save_msg({
                    f_eticket_id: ticket_id,
                    f_sign_result: '查询超时请再次尝试。',
                    f_bill_state: '等待查询'
                  })
                  this.return_msg = '发票已经开具,查询发票状态超时,请前往发票管理重新尝试'
                  clearInterval(interval)
                }
                time = time + 1
              }
            })
          }, 1 * 2000)
        } else if (result) {
        // TODO 查询失败后保存发票详情
          await this.save_msg({
            f_eticket_id: ticket_id,
            f_sign_result: result.data.statusMsg,
            f_bill_state: '冲红失败'
          })
          this.return_msg = '电子票冲红出错,错误【' + result.statusMsg + '】,错误代码【' + result.code + '】,请前往发票管理重新尝试'
        } else {
          await this.save_msg({
            f_eticket_id: ticket_id,
            f_sign_result: '电子票冲红出错,需要查询日志。',
            f_bill_state: '冲红失败'
          })
          this.$showAlert('电子票冲红出错,暂无错误信息,请前往发票管理重新尝试', 'danger', 5000)
        }
      } catch (error) {
        await this.save_msg({
          f_eticket_id: ticket_id,
          f_return_msg: '冲红失败,需要查询日志。',
          f_bill_state: '冲红失败'
        })
        this.$showAlert('电子票冲红出现异常，请联系管理员！！！', 'warning', 5000)
      }
    },
    /**
     *
     * @param id 收费id
     * @param ticket_id 票据信息 id
     * @returns {Promise<void>}  如果查到返回url
     */
    async openEticketGen (ticket_id) {
      try {
        // 否则正常打票
        // await this.$resetpost('/rs/logic/updateSearil', {id: ticket_id}, {
        //   resolveMsg: null,
        //   rejectMsg: '更新流水号失败!!'
        // })
        let time = 0
        let result = await this.$resetpost('/invoice/rs/logic/GXGetInvoice', {eticket_id: ticket_id}, {
          resolveMsg: null,
          rejectMsg: '发票打印失败!!'
        })
        result = result.data
        if (result && result.code === 'E0000') {
          // TODO 开票成功 保存发票详情
          await this.save_msg({
            f_eticket_id: ticket_id,
            f_bill_state: '等待查询'
          })
          // TODO 开票成功 进行查询
          let interval = await setInterval(() => {
            // 2秒一轮回
            let http = new HttpResetClass()
            http.load('POST', '/invoice/rs/logic/GXQueryInvoice', {eticket_id: ticket_id}, {
              resolveMsg: null,
              rejectMsg: null
            }).then(req => {
              if (req.data.code !== 'E0000') {
                clearInterval(interval)
                this.save_msg({
                  f_eticket_id: ticket_id,
                  f_sign_result: '查询超时请再次尝试。',
                  f_bill_state: '查询失败'
                })
                this.$showAlert('电子票查询出错,暂无错误信息,请前往发票管理重新尝试', 'danger', 5000)
                return
              }
              req = req.data
              console.log(req, '查出什么玩意了', time)
              if (req && req.code === 'E0000' && req.data.status === '2') {
                // 组织数据
                clearInterval(interval)
                // TODO 成功后保存发票详情
                this.save_msg({
                  f_eticket_id: ticket_id,
                  f_bill_code: req.data.invoiceCode,
                  f_bill_number: req.data.invoiceNo,
                  f_jym: req.data.checkCode,
                  f_bill_url: req.data.pdfUrl,
                  f_sign_result: req.data.statusMsg,
                  f_bill_state: '开票成功'
                })
                this.eticket_src = req.data.pdfUrl
              } else if (req && !['2', '20', '21', 2, 20, 21].includes(req.data.status)) {
                clearInterval(interval)
                // TODO 失败后保存发票详情
                this.save_msg({
                  f_eticket_id: ticket_id,
                  f_sign_result: req.data.statusMsg,
                  f_bill_state: '开票失败'
                })
                this.return_msg = '电子票查询出错,错误【' + req.data.statusMsg + '】,错误代码【' + req.code + '】,请前往发票管理重新尝试'
              } else {
                if (time == 50) {
                  // 三十秒后无效
                  // TODO 查询失败后保存发票详情
                  this.save_msg({
                    f_eticket_id: ticket_id,
                    f_sign_result: '查询超时请再次尝试。',
                    f_bill_state: '查询失败'
                  })
                  this.return_msg = '发票已经开具,查询发票状态超时,请前往发票管理重新尝试'
                  clearInterval(interval)
                }
                time = time + 1
              }
            })
          }, 1 * 2000)
        } else if (result) {
          // TODO 查询失败后保存发票详情
          await this.save_msg({
            f_eticket_id: ticket_id,
            f_sign_result: result.data.statusMsg,
            f_bill_state: '开票失败'
          })
          this.return_msg = '电子票开票出错,错误【' + result.data.statusMsg + '】,错误代码【' + result.data.code + '】,请前往发票管理重新尝试'
        } else {
          await this.save_msg({
            f_eticket_id: ticket_id,
            f_sign_result: '开票失败,需要查询日志。',
            f_bill_state: '开票失败'
          })
          this.$showAlert('电子票开票出错,暂无错误信息,请前往发票管理重新尝试', 'danger', 5000)
        }
      } catch (error) {
        await this.save_msg({
          f_eticket_id: ticket_id,
          f_return_msg: '开票失败,需要查询日志。',
          f_bill_state: '开票失败'
        })
        this.$showAlert('电子发票打印出现异常，请联系管理员！！！', 'warning', 5000)
      }
    }
  },
  watch: {},
  events: {}
}
</script>
<style>
</style>
