<template>
  <div class="auto form-horizontal">
    <modal :show.sync="show&&!billConfig.autoPrint" 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">
        <validator name='v'>
          <form class="form-horizontal select-overspread">
            <div class="row" style="display: flex;justify-content: center;" id='normal-bill-js' v-if="bill.data">
              {{{bill.data}}}
            </div>
            <div v-else class="text-center">
              <p>正在加载数据，请稍候...</p>
            </div>
          </form>
        </validator>
      </article>
      <footer slot="modal-footer" class="modal-footer">
        <div v-if="billConfig.hasBillManage">
          <div class="col-sm-2">
            <span><strong>发票号:{{ model.f_using_number }}</strong></span>
          </div>
        </div>
        <button type="button" class="btn btn-success" @click='printDirect' @keyup.enter="printDirect" v-el:confirmbutton :disabled="!dataLoaded">打印</button>
        <report-print-thermal id='report-print-component' :id="'normal-bill-js'" top='5mm' left='5mm' width='90%' height='80%' :notrepeat="true" :showbtn="false" v-ref:reportprintjs></report-print-thermal>
        <button type="button" class="btn btn-default" @click='cancel()' v-if="!billConfig.hasBillManage">取消</button>
      </footer>
    </modal>
  </div>
</template>
<script>
import {DataModel} from 'vue-client'
import reportPrintThermal from './reportPrintThermal.vue'

let getBillData = async function (self, val) {
  console.log('开始获取账单数据:', self)
  let temp = {
    reprint: "'正常'",
    operator: `'${self.$login.f.name}'`,
    condition: self.data.id
  }
  if (self.data.fillgasid) {
    temp.condition = `"${self.data.fillgasid}"`
  }
  console.log('查询参数:', temp)
  console.log('数据URL:', self.billData.url)

  try {
    self.bill = new DataModel(self.billData.url, temp)
    await self.bill.search(self.data.id)
    console.log('账单数据获取成功:', self.bill)

    // 检查bill.data是否存在
    if (!self.bill.data) {
      console.error('账单数据为空')
      return false
    } else {
      console.log('账单数据长度:', self.bill.data.length)
      // 获取发票号
      self.model.f_using_number = self.billData.number
      console.log('发票号:', self.model.f_using_number)
      return true
    }
  } catch (error) {
    console.error('获取账单数据失败:', error)
    throw error
  }
}

export default {
  title: '收费发票',
  components: {
    reportPrintThermal
  },
  data () {
    return {
      model: {
        f_using_number: null
      },
      bill: {},
      messShow: false,
      dataLoaded: false, // 数据是否已加载
      isLoading: false,  // 是否正在加载数据
      renderComplete: false // DOM渲染是否完成
    }
  },
  props: ['show', 'data', 'billData', 'billConfig'],
  ready () {
    console.log('PrintBillJS组件初始化:', this.billConfig, this.billData)
  },
  methods: {
    // 确认按钮获得焦点
    confirmbuttonfocus () {
      this.$nextTick(() => {
        this.$els.confirmbutton.focus()
      })
    },
    cancel () {
      this.$dispatch('toggle')
    },
    // 手动获取账单数据
    getbill () {
      console.log('手动获取账单数据')
      if (this.$refs.reportprintjs) {
        this.$refs.reportprintjs.isPrint = true
      } else {
        console.error('reportprintjs引用不存在')
      }

      if (this.isLoading) {
        console.log('数据正在加载中，请稍候')
        return
      }

      this.isLoading = true
      this.renderComplete = false
      getBillData(this, true).then((success) => {
        this.isLoading = false
        if (success) {
          this.dataLoaded = true
          console.log('账单数据加载完成')

          // 确保DOM已更新
          this.$nextTick(() => {
            setTimeout(() => {
              this.renderComplete = true
              this.$emit('ready')
            }, 300)
          })
        } else {
          console.error('账单数据加载失败')
          this.$emit('error', new Error('账单数据为空'))
        }
      }).catch((error) => {
        this.isLoading = false
        console.error('获取账单数据出错:', error)
        this.$emit('error', error)
      })
    },
    // 直接打印
    async printDirect () {
      console.log('直接打印')
      await this.processPrint(false)
    },
    // 选择打印机打印
    async printWithDialog () {
      console.log('选择打印机打印')
      await this.processPrint(true)
    },
    // 处理打印流程
    async processPrint (selectPrinter) {
      console.log('开始处理打印流程')

      // 如果正在加载数据，等待加载完成
      if (this.isLoading) {
        console.log('数据正在加载中，请稍候')
        return
      }

      // 确保数据已加载
      if (!this.dataLoaded || !this.bill.data) {
        console.log('数据尚未加载，先加载数据')
        try {
          this.isLoading = true
          this.renderComplete = false
          const success = await getBillData(this, true)
          this.isLoading = false

          if (!success) {
            console.error('打印前获取数据失败: 数据为空')
            this.$dispatch('error', '发票打印', this.data, new Error('账单数据为空'))
            return
          }

          this.dataLoaded = true

          // 等待DOM渲染完成
          await new Promise(resolve => {
            this.$nextTick(() => {
              setTimeout(() => {
                this.renderComplete = true
                resolve()
              }, 1000) // 增加延迟时间确保渲染完成
            })
          })
        } catch (error) {
          this.isLoading = false
          console.error('打印前获取数据失败:', error)
          this.$dispatch('error', '发票打印', this.data, error)
          return
        }
      }

      // 确保打印内容存在
      const printElement = document.getElementById('normal-bill-js')
      if (!printElement) {
        console.error('打印内容元素不存在')
        this.$dispatch('error', '发票打印', this.data, new Error('打印内容元素不存在'))
        return
      }

      if (!printElement.innerHTML || printElement.innerHTML.trim() === '') {
        console.error('打印内容为空')
        this.$dispatch('error', '发票打印', this.data, new Error('打印内容为空'))
        return
      }

      // 强制显示打印内容（确保可见性）
      printElement.style.display = 'block'
      printElement.style.visibility = 'visible'

      console.log('打印内容已准备好:', printElement.innerHTML.substring(0, 100) + '...')

      try {
        // 更新系统发票
        if (this.billConfig.hasBillManage) {
          if (this.data.f_bill_type != '清算单') {
            console.log('开始更新系统发票')
            await this.$CommonService.openPaperBill(this.data.id, this.data.f_bill_type, this.billConfig.billType, this.billData.bill, '正常')
            console.log('系统发票更新完成')
          }
        } else {
          console.log('开始更新票据补打')
          await this.$resetpost('rs/logic/sale_billReprint', {data: this.data}, {
            resolveMsg: null,
            rejectMsg: '票据补打出错！！',
            newly: true
          })
          console.log('票据补打更新完成')
        }

        // 确保打印组件引用存在
        if (!this.$refs.reportprintjs) {
          console.error('打印组件引用不存在')
          this.$dispatch('error', '发票打印', this.data, new Error('打印组件引用不存在'))
          return
        }

        console.log('开始执行打印')
        // 执行打印前再次等待一小段时间确保内容完全渲染
        await new Promise(resolve => setTimeout(resolve, 500))

        // 执行打印
        if (selectPrinter) {
          this.$refs.reportprintjs.printWithDialog()
        } else {
          this.$refs.reportprintjs.printDirect()
        }
      } catch (error) {
        console.error('打印处理出错:', error)
        this.$dispatch('error', '发票打印', this.data, error)
      }
    },

    // 手动触发打印内容的渲染
    renderPrintContent () {
      if (!this.dataLoaded || !this.bill.data) {
        console.error('数据未加载，无法渲染打印内容')
        return false
      }

      const printElement = document.getElementById('normal-bill-js')
      if (!printElement) {
        console.error('打印元素不存在')
        return false
      }

      // 强制更新DOM
      this.$nextTick(() => {
        console.log('强制更新打印内容DOM')
        // 此处不需要实际修改内容，只是触发DOM更新
        this.renderComplete = true
      })

      return true
    }
  },
  watch: {
    'show' (val) {
      console.log('show值变化:', val)
      if (val) {
        this.dataLoaded = false // 重置数据加载状态
        this.renderComplete = false // 重置渲染状态
        this.isLoading = true   // 设置加载状态

        getBillData(this, val).then((success) => {
          this.isLoading = false
          if (success) {
            console.log('监听到show变化，数据获取成功')
            this.dataLoaded = true

            // 确保DOM已更新
            this.$nextTick(() => {
              // 增加延迟确保DOM完全渲染
              setTimeout(() => {
                this.renderComplete = true
                console.log('DOM渲染完成')

                // 检查打印内容是否存在
                const printElement = document.getElementById('normal-bill-js')
                if (printElement && printElement.innerHTML) {
                  console.log('打印内容已准备好，长度:', printElement.innerHTML.length)
                } else {
                  console.error('打印内容不存在或为空')
                }

                if (this.billConfig.autoPrint) {
                  console.log('配置为自动打印，开始打印')
                  // 延迟打印以确保DOM完全渲染
                  setTimeout(() => {
                    this.printDirect()
                  }, 500)
                }
                this.confirmbuttonfocus()
              }, 500)
            })
          } else {
            console.error('监听到show变化，但数据获取为空')
            this.$emit('error', new Error('账单数据为空'))
          }
        }).catch((error) => {
          this.isLoading = false
          console.error('监听到show变化，但数据获取失败:', error)
          this.$emit('error', error)
        })
      }
    }
  },
  events: {
    'print' () {
      console.log('接收到print事件')
      // 对票据明细进行更新或插入操作
      this.$dispatch('printok', '发票打印', this.data)
    },
    'print-success' () {
      console.log('接收到print-success事件')
      this.$dispatch('printok', '发票打印', this.data)
    },
    'print-error' () {
      console.error('接收到print-error事件')
      this.$dispatch('error', '发票打印', this.data, null)
    }
  }
}
</script>
<style>
</style>
