<script>
import PrintBill from './PrintBill.vue'
import OpenInvoice from './OpenInvoice.vue'
import { getConfigByNameAsync } from '@vue2-client/services/api/common'
export default {
  name: 'BillPrint',
  components: { OpenInvoice, PrintBill },
  data () {
    return {}
  },
  props: {
    autoPrint: {
      type: Boolean,
      default: false
    },
    serviceName: {
      type: String,
      default: process.env.VUE_APP_SYSTEM_NAME
    },
  },
  methods: {
    async print ({ id, billUrl, operator, billType, billStyle, autoPrint, reprint = '正常' }) {
      // 获取票据格式
      // {
      //   "value": [
      //   {
      //     "label": "普通收据",
      //     "value": "普通收据"
      //   },
      //   {
      //     "label": "电子发票",
      //     "invoice": true,
      //     "value": "电子发票"
      //   }
      // ]
      // }
      getConfigByNameAsync('打印格式Dic', this.serviceName).then(async res => {
        // 判断当前 billStyle 是否是电子票
        const isInvoice = res.value.find(item => item.value === billStyle && item.invoice)
        if (isInvoice) {
          // todo 电子票功能暂未实现
          // this.$refs.invoice.print({
          //   reprint: '正常',
          //   billUrl: billUrl,
          //   operator: operator,
          //   condition: id
          // })
        } else {
          // 如果没有 billurl 通过 billtype 获取链接
          if (!billUrl) {
            if (billType) {
              // 获取 类型对应的配置
              await getConfigByNameAsync('票据类型Url映射Config', this.serviceName).then(res => {
                if (res[billType]) {
                  billUrl = res[billType]
                  this.$refs['print-bill'].print({
                    reprint: reprint,
                    condition: id,
                    billUrl,
                    operator
                  })
                } else {
                  this.$message.error(`未找到${billType}对应的票据映射，请检查`)
                }
              })
            } else {
              this.$message.error('未找到票据格式，请检查')
            }
          } else {
            await this.$refs['print-bill'].print({
              reprint: reprint,
              condition: id,
              billUrl,
              operator
            })
          }
        }
      })
    },
    printOk () {
      console.log('打印成功')
      this.$emit('ok')
    }
  }
}
</script>

<template>
  <div>
    <print-bill :serviceName="serviceName" ref="print-bill" @ok="printOk" :autoPrint="autoPrint"/>
    <open-invoice :serviceName="serviceName" ref="invoice" @ok="printOk" :autoPrint="autoPrint"/>
  </div>
</template>

<style scoped>

</style>
