<template>
  <div
    class="print-wrap"
    v-show="true"
  >
    <div
      id="printMe"
      ref="printMe"
      v-if="elementStyle"
      :style="[elementStyle.canvas,defaultTemplate==='horizen'?{width:elementStyle.canvas.height,height:elementStyle.canvas.width}:{}]"
    >
      <div
        v-if="currentTicket"
        :style="[{ position: 'relative',width: elementStyle.canvas.width,height:elementStyle.canvas.height},defaultTemplate==='horizen'?{transform:elementStyle.canvas.reverse?'translateX(50%) rotate(90deg)':'translateX(-100%) rotate(-90deg)', transformOrigin:elementStyle.canvas.reverse?'0 0':'100% 0'}:{ transform:elementStyle.canvas.reverse?'rotate(180deg)':''}]">
        <div
          class="el sign"
          :style="elementStyle.sign">
          窗
        </div>

        <span
          v-if="projectName!=='mazu'"
          class="el"
          :style="elementStyle.num">
          - NO.{{ isNaN(currentTicket.index)? 1 : currentTicket.index + 1 }} -
        </span>
        <span
          v-else
          class="el"
          :style="elementStyle.num">
          - NO.{{ isNaN(currentTicket.id)? '00000000' : currentTicket.id.toString().padStart(8,'0') }} -
        </span>

        <!-- 是否使用打印价格 -->
        <!--
        <span
          class="el"
          v-if="!currentTicket.is_otaorder"
          :style="elementStyle.price">
          <i style="font-size:0.8em; font-style:normal">{{ elementStyle.price&&elementStyle.price.format }}</i> ¥ {{ currentTicket.is_print_price_active ? currentTicket.print_price*currentTicket.check_num : currentTicket.price }} <span v-if="showUnit">元</span>
        </span>

        <span
          class="el"
          v-if="!currentTicket.is_otaorder"
          :style="elementStyle.singlePrice">
          <i style="font-size:0.8em; font-style:normal">{{ elementStyle.singlePrice&&elementStyle.singlePrice.format }}</i> ¥ {{ currentTicket.is_print_price_active ? currentTicket.print_price : $NP.divide(currentTicket.price, currentTicket.check_num) }} <span v-if="showUnit">元</span>
        </span>
         -->

        <!-- 三河古镇定制:线上订单也打印价格 -->
        <template v-if="'三河古镇' === scenicName">
          <span
            class="el"
            :style="elementStyle.price">
            <i style="font-size:0.8em; font-style:normal">{{ elementStyle.price&&elementStyle.price.format }}</i> ¥ {{ currentTicket.is_print_price_active ? currentTicket.print_price*currentTicket.check_num : currentTicket.price }} <span v-if="showUnit">元</span>
          </span>

          <span
            class="el"
            :style="elementStyle.singlePrice">
            <i style="font-size:0.8em; font-style:normal">{{ elementStyle.singlePrice&&elementStyle.singlePrice.format }}</i> ¥ {{ currentTicket.is_print_price_active ? currentTicket.print_price : $NP.divide(currentTicket.price, currentTicket.check_num) }} <span v-if="showUnit">元</span>
          </span>
        </template>
        <!-- 其余景区线上订单不打印价格 -->
        <template v-else>
          <span
            class="el"
            v-if="!currentTicket.is_otaorder"
            :style="elementStyle.price">
            <i style="font-size:0.8em; font-style:normal">{{ elementStyle.price&&elementStyle.price.format }}</i> ¥ {{ currentTicket.is_print_price_active ? currentTicket.print_price*currentTicket.check_num : currentTicket.price }} <span v-if="showUnit">元</span>
          </span>

          <span
            class="el"
            v-if="!currentTicket.is_otaorder"
            :style="elementStyle.singlePrice">
            <i style="font-size:0.8em; font-style:normal">{{ elementStyle.singlePrice&&elementStyle.singlePrice.format }}</i> ¥ {{ currentTicket.is_print_price_active ? currentTicket.print_price : $NP.divide(currentTicket.price, currentTicket.check_num) }} <span v-if="showUnit">元</span>
          </span>
        </template>

        <div :style="elementStyle.orderId">
          {{ elementStyle.orderId&&elementStyle.orderId.format || '订单号：' }}{{ currentTicket.order_no }}
        </div>

        <div
          :style="elementStyle.seller"
          v-if="currentTicket.manager_name">
          售票员：{{ currentTicket.manager_name }}
        </div>

        <div
          :style="elementStyle.guestName"
          v-if="(currentTicket.buyer_name||currentTicket.guestName)">
          {{ elementStyle.guestName.format&&elementStyle.guestName.format||'游客：' }} {{ currentTicket.guestName || currentTicket.buyer_name }}
          <span v-if="currentTicket.guestIdentify && elementStyle.guestName.showId">（{{ currentTicket.guestIdentify.replace(/^(.{6})(?:\d+)(.{4})$/,"$1******$2") }}）</span>
        </div>

        <div
          :style="elementStyle.agency"
          v-if="currentTicket.travel_agency_name">
          {{ elementStyle.agency&&elementStyle.agency.format||'旅行社：' }} {{ currentTicket.travel_agency_name }}
        </div>

        <div :style="elementStyle.ticketId">
          {{ elementStyle.ticketId&&elementStyle.ticketId.format || '票号：' }}{{ currentTicket.qrcode }}
          <!-- {{ elementStyle.ticketId&&elementStyle.ticketId.format || '票号：' }}{{ '大陈岛景区' !== scenicName ? currentTicket.qrcode : currentTicket.id }} -->
        </div>
        <!-- 大陈岛定制的打印连续序列号 -->
        <div
          :style="elementStyle.ticketSeqId"
          v-if="'大陈岛景区' === scenicName">
          {{ elementStyle.ticketSeqId&&elementStyle.ticketSeqId.format || '序列号：' }}{{ currentTicket.id }}
        </div>
        <div
          :style="elementStyle.createTime"
          v-if="currentTicket.create_time">
          {{ elementStyle.createTime&&elementStyle.createTime.format || '出票时间：' }}{{ currentTicket.create_time }}
        </div>

        <div :style="elementStyle.scenics">
          {{ scenics }}
        </div>

        <div :style="elementStyle.scenic">
          <div :style="((elementStyle.scenic.direction==='inline'|| !elementStyle.scenic.direction)?{}:{display: 'flex','flex-direction': 'column'})">
            <template v-if="elementStyle.scenic.number==='0'">
              <span
                style="margin-right:5px"
                v-for="(item,index) in currentTicket.ticket_scenic"
                :key="index">
                {{ item.scenic_name }} {{ item.check_limit_times }}次<span v-if="index!==(currentTicket.ticket_scenic.length-1)">,</span>
              </span>
            </template>
            <template v-else>
              <span
                style="margin-right:5px"
                v-for="(item,index) in currentTicket.ticket_scenic.slice(0,elementStyle.scenic.number||2)"
                :key="index">
                {{ item.scenic_name }} {{ item.check_limit_times }}次<span v-if="elementStyle.scenic.number>currentTicket.ticket_scenic.length?index!==(currentTicket.ticket_scenic.length-1):index!==(elementStyle.scenic.number||2)-1">,</span>
              </span>

              <span v-if="elementStyle.scenic.number<currentTicket.ticket_scenic.length">...(多景点门票)</span>
            </template>
          </div>
        </div>

        <!-- <table :style="elementStyle.info">
          <tr>
            <td width="40%">
              订单号:
            </td>
            <td></td>
          </tr>
          <tr>
            <td>票号:</td>
            <td>{{ currentTicket.qrcode }}</td>
          </tr>
          <tr v-if="currentTicket.ticket_scenic && currentTicket.ticket_scenic.length>0">
            <td>{{ currentTicket.ticket_scenic[0].scenic_name }}</td>
            <td>
              可检 {{ currentTicket.ticket_scenic[0].check_limit_times }} 次
              单次可过人数: {{ currentTicket.ticket_scenic[0].single_pass_times }} 人 <br>
              <span v-if="currentTicket.ticket_scenic.length>1">
                （多景点门票）
              </span>
            </td>
          </tr>
        </table> -->

        <div :style="elementStyle.ticketTitle">
          {{ elementStyle.ticketTitle&&elementStyle.ticketTitle.format || '' }}{{ currentTicket.tname }}
        </div>

        <div
          class="img"
          :style="[elementStyle.qrcode,{backgroundImage:`url(${qrImg})`}]">
        </div>

        <!--
        <div
          v-if="currentTicket.invoiceQrcode"
          class="img-wrap"
          :style="[elementStyle.invoiceQrcode,{display:currentTicket.invoiceQrcode?'block':'none'}]">
          <div
            class="img"
            :style="{backgroundImage:`url(${fpImg})`,height:'100%'}">
          </div>

          <div v-if="elementStyle.invoiceQrcode">
            {{ elementStyle.invoiceQrcode&&elementStyle.invoiceQrcode.format }}
          </div>
        </div>
         -->
        <!-- 不需要再设置display，否则它会覆盖elementStyle里设置的display -->
        <div
          v-if="currentTicket.invoiceQrcode"
          class="img-wrap"
          :style="[elementStyle.invoiceQrcode]">
          <div
            class="img"
            :style="{backgroundImage:`url(${fpImg})`,height:'100%'}">
          </div>

          <div v-if="elementStyle.invoiceQrcode">
            {{ elementStyle.invoiceQrcode&&elementStyle.invoiceQrcode.format }}
          </div>
        </div>

        <!--
        <div
          v-if="currentTicket.allInvoiceQrcode"
          class="img-wrap"
          :style="[elementStyle.allInvoiceQrcode,{display:currentTicket.allInvoiceQrcode?'block':'none'}]">
          <div
            class="img"
            :style="{backgroundImage:`url(${afpImg})`,height:'100%'}">
          </div>

          <div v-if="elementStyle.allInvoiceQrcode">
            {{ elementStyle.allInvoiceQrcode.format }}
          </div>
        </div>
        -->

        <!-- 不需要再设置display，否则它会覆盖elementStyle里设置的display -->
        <div
          v-if="currentTicket.allInvoiceQrcode"
          class="img-wrap"
          :style="[elementStyle.allInvoiceQrcode]">
          <div
            class="img"
            :style="{backgroundImage:`url(${afpImg})`,height:'100%'}">
          </div>

          <div v-if="elementStyle.allInvoiceQrcode">
            {{ elementStyle.allInvoiceQrcode.format }}
          </div>
        </div>

        <div :style="elementStyle.des">
          <span v-if="currentTicket.is_need_playtime">
            {{ elementStyle.des&&elementStyle.des.format||'游玩日期：' }}{{ currentTicket.payDateBegin | formatDate }} <br>
          </span>
          <span v-else>
            有效日期: {{ currentTicket.payDateBegin | formatDate }} 至 {{ currentTicket.play_date_end | formatDate }}<br>
          </span>
        </div>
        <div
          :style="elementStyle.orderRemark"
          v-if="currentTicket.remark">
          {{ elementStyle.orderRemark&&elementStyle.orderRemark.format||'订单备注：' }}{{ currentTicket.remark }}
        </div>
        <div
          :style="elementStyle.performName"
          v-if="currentTicket.perform_name">
          <!-- {{ elementStyle.performName&&elementStyle.performName.format||'节目：' }}{{ currentTicket.perform_name }} -->
          <!-- 草房子这个景点不显示后面的"草房子剧场" -->
          {{ elementStyle.performName&&elementStyle.performName.format||'节目：' }}{{ '草房子' === scenicName ? '' : currentTicket.perform_name }}
        </div>

        <div
          :style="elementStyle.batch"
          v-if="currentTicket.batch_config_name">
          {{ elementStyle.batch&&elementStyle.batch.format||'场次：' }}{{ currentTicket.batch_config_name }}
        </div>

        <div
          :style="elementStyle.serialNumber"
          v-if="currentTicket.serial_number">
          {{ elementStyle.serialNumber&&elementStyle.serialNumber.format||'场次内序号：' }}{{ currentTicket.serial_number }}
        </div>

        <div
          :style="elementStyle.queueSerialNumber"
          v-if="currentTicket.queue_info">
          <span>{{ elementStyle.queueSerialNumber&&elementStyle.queueSerialNumber.format||'排队序列号：：' }}</span>
          <span> {{ currentTicket.queue_info.queue_serial_number }}</span>
        </div>

        <div
          :style="elementStyle.schedule"
          v-if="currentTicket.schedule_config_name">
          {{ elementStyle.schedule&&elementStyle.schedule.format||'班次：' }}{{ currentTicket.schedule_config_name }}
        </div>

        <div
          :style="elementStyle.scheduleSerialNumber"
          v-if="currentTicket.schedule_serial_number">
          {{ elementStyle.scheduleSerialNumber&&elementStyle.scheduleSerialNumber.format||'班次内序号：' }}{{ currentTicket.schedule_serial_number }}
        </div>
        <div
          :style="elementStyle.areaName"
          v-if="currentTicket.seat_area_name">
          {{ elementStyle.areaName&&elementStyle.areaName.format||'区域：' }}{{ currentTicket.seat_area_name }}
        </div>

        <div
          :style="elementStyle.pricePlan"
          v-if="currentTicket.ticket_price_plan_name">
          {{ elementStyle.pricePlan&&elementStyle.pricePlan.format||'价格方案：' }}{{ currentTicket.ticket_price_plan_name }}
        </div>
        <div
          :style="elementStyle.seatNameNew"
          v-if="currentTicket.seat_name_new">
          {{ elementStyle.seatNameNew&&elementStyle.seatNameNew.format||'A区' }}{{ currentTicket.seat_name_new }}
        </div>

        <div
          :style="elementStyle.rowTag"
          v-if="currentTicket.seat_row_tag">
          {{ currentTicket.seat_row_tag }}{{ elementStyle.rowTag&&elementStyle.rowTag.format||'排' }}
        </div>

        <div
          :style="elementStyle.seatName"
          v-if="currentTicket.seat_name">
          {{ currentTicket.seat_name }}{{ elementStyle.seatName&&elementStyle.seatName.format||'座' }}
        </div>

        <div
          :style="elementStyle.batch"
          v-if="currentTicket.batch_config_name">
          {{ elementStyle.batch&&elementStyle.batch.format||'场次：' }}{{ currentTicket.batch_config_name }}
        </div>

        <div
          :style="elementStyle.schedule"
          v-if="currentTicket.schedule_config_name">
          {{ elementStyle.schedule&&elementStyle.schedule.format||'班次：' }}{{ currentTicket.schedule_config_name }}
        </div>

        <div
          :style="elementStyle.areaName"
          v-if="currentTicket.seat_area_name">
          {{ elementStyle.areaName&&elementStyle.areaName.format||'区域：' }}{{ currentTicket.seat_area_name }}
        </div>

        <div :style="elementStyle.checkNum">
          {{ elementStyle.checkNum&&elementStyle.checkNum.format||'检票人数：' }}{{ currentTicket.person_number }} 人
        </div>

        <div :style="elementStyle.remark">
          {{ elementStyle.remark&&elementStyle.remark.format||'' }}<span
            style="white-space: pre-wrap;"
            v-html="elementStyle.canvas.remark.replace(/\n/g,'<br>')">
          </span>
        </div>

        <div :style="elementStyle.fixedText">
          {{ elementStyle.fixedText&&elementStyle.fixedText.format||'备注2：' }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import QRCode from 'qrcode'

export default {
  computed: {
    elementStyle () {
      let style = {}
      if (this.customStyle) {
        console.log(this.customStyle)
        this.customStyle.elements.forEach(i => {
          style[i.type] = i.style
        })
        style.canvas = this.customStyle.canvas
      }
      return this.customStyle ? style : null
    },
    scenics () {
      if (this.currentTicket) {
        const scenics = this.currentTicket.ticket_scenic.map(i => i.scenic_name)
        return scenics.join(' - ')
      } else {
        return ''
      }
    },
    printTemplate () {
      return this.$store.state.app.printTemplate
    },
    showUnit () {
      return this.scenicName !== '狼山景区' && this.scenicName !== '军山景区'
    },
    scenicName () {
      return this.$localStore.get('scenicName') || this.$store.state.user.scenicName
    }
  },
  data () {
    return {
      projectName: process.env.VUE_APP_PROJECT,
      qrImg: '',
      fpImg: '',
      afpImg: '',
      customStyle: null,
      defaultTemplate: ''
    }
  },
  props: {
    preview: { // 仅预览时，不打印
      type: Boolean,
      default: false
    },
    currentTicket: {
      type: Object,
      default: () => {}
    }
  },
  methods: {
    startPrint () {
      console.log('currentTicket', this.currentTicket)
      const webview = document.querySelector('#printWebview')
      let printDoc = this.$refs.printMe.outerHTML
      // if (this.preview) {
      console.log(printDoc)
      // return
      // }
      // webview.openDevTools()
      webview.send('webview-print-render', printDoc)
    },
    sendPrinter (style) {
      if (style) {
        this.customStyle = JSON.parse(JSON.stringify(style))
        this.defaultTemplate = this.customStyle.theme

        this.$nextTick(() => {
          this.startPrint()
        })
      } else {
        this.startPrint()
      }
    }
  },
  watch: {
    printTemplate: {
      handler (val) {
        if (val) {
          this.defaultTemplate = val.canvas && val.canvas.direction
          // console.log(this.defaultTemplate)
          this.customStyle = val
        }
      },
      deep: true,
      immediate: true
    },
    currentTicket: {
      handler (val) {
        if (!val) return
        let target
        if (val.print_model_id !== 0) {
          target = this.$store.state.app.printTemplateList.find(i => i.id === val.print_model_id)
        } else {
          let id = this.$localStore.get('defaultTemplate')
          target = this.$store.state.app.printTemplateList.find(i => i.id === id)
        }
        this.$store.commit('SET_PRINT_TEMPLATE', target ? JSON.parse(target.content) : this.printTemplate)
        this.$nextTick(async () => {
          var opts = {
            errorCorrectionLevel: 'H',
            type: 'image/png',
            quality: 1,
            color: {
              dark: '#000000ff', // Blue dots
              light: '#0000' // Transparent background
            }
          }

          if (this.currentTicket.qrcode) {
            this.qrImg = await QRCode.toDataURL(this.currentTicket.qrcode, opts)
          }

          if (this.currentTicket.invoiceQrcode) {
            this.fpImg = await QRCode.toDataURL(this.currentTicket.invoiceQrcode, opts)
          }

          if (this.currentTicket.allInvoiceQrcode) {
            this.afpImg = await QRCode.toDataURL(this.currentTicket.allInvoiceQrcode, opts)
          }
          console.warn(this.currentTicket)
          if (this.preview) return

          setTimeout(() => {
            this.sendPrinter()
          }, 100)
        })
      },
      immediate: true
    }
  }
}
</script>

<style scoped>
.img{
  height: 100%; background: no-repeat center center /contain;
}
</style>
