<template>
  <div class="form-wrap">
    <el-form
      class="search-box"
      ref="form"
      :model="form"
      :inline="true"
      label-width="100px"
    >
      <div class="block-title">
        查询条件
      </div>
      <el-form-item
        label="起始时间"
        prop="startDate"
      >
        <el-date-picker
          v-model="form.startDate"
          type="datetime"
          placeholder="选择日期时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item
        label="截止时间"
        prop="endDate"
      >
        <el-date-picker
          default-time="23:59:59"
          v-model="form.endDate"
          type="datetime"
          placeholder="选择日期时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item
        label="订单号"
        prop="keyWords1">
        <el-input v-model="form.keyWords1"></el-input>
      </el-form-item>
      <el-form-item
        label="渠道名"
        prop="keyWords2">
        <el-input v-model="form.keyWords2"></el-input>
      </el-form-item>
      <el-form-item
        label="流水号"
        prop="keyWords3">
        <el-input v-model="form.keyWords3"></el-input>
      </el-form-item>
      <el-form-item
        label="开票方"
        prop="keyWords4">
        <el-input v-model="form.keyWords4"></el-input>
      </el-form-item>
      <el-form-item
        label="购买方"
        prop="keyWords5">
        <el-input v-model="form.keyWords5"></el-input>
      </el-form-item>
      <el-form-item
        label="操作人"
        prop="keyWords6">
        <el-select v-model="form.keyWords6">
          <el-option
            label="全部"
            value=""></el-option>
          <el-option
            v-for="item in salesList"
            :key="item.id"
            :label="item.nickName"
            :value="item.nickName">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="状态"
        prop="keyWords8">
        <el-select v-model="form.keyWords8">
          <el-option
            label="全部"
            value=""></el-option>
          <el-option
            label="未开票"
            :value="0"></el-option>
          <el-option
            label="已开票"
            :value="1"></el-option>
          <el-option
            label="开票失败"
            :value="2"></el-option>
          <el-option
            label="开票中"
            :value="3"></el-option>
        </el-select>
      </el-form-item>
      <div class="btn-wrap">
        <el-button
          @click="reset"
        >
          重置
        </el-button>
        <el-button
          :disabled="loading"
          type="primary"
          @click="getListInvoiceRecord(true)"
        >
          搜索
        </el-button>
      </div>
    </el-form>

    <div class="table-box">
      <!-- <div class="block-title">
        统计信息
      </div> -->
      <el-table
        stripe
        border
        v-loading="loading"
        :data="tableData">
        <el-table-column
          prop="typ"
          label="类型"
        >
          <template slot-scope="prop">
            {{ prop.row.type==='TICKET'?'门票':'会员' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="orderNo"
          label="订单号"
        >
        </el-table-column>
        <el-table-column
          prop="channel_name"
          label="渠道名"
        >
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
        >
          <template slot-scope="prop">
            {{ prop.row.createTime | formatTime }}
          </template>
        </el-table-column>
        <el-table-column
          prop="transaction_no"
          label="流水号"
        >
        </el-table-column>
        <el-table-column
          prop="price"
          label="金额(元)"
        >
        </el-table-column>
        <el-table-column
          prop="invoice_time"
          label="开票时间"
        >
          <template slot-scope="prop">
            <span v-if="prop.row.invoice_time">
              {{ prop.row.invoice_time | formatTime }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="invoice_seller"
          label="开票方"
        >
        </el-table-column>
        <el-table-column
          prop="invoiceBuyer"
          label="购买方"
        >
        </el-table-column>
        <el-table-column
          prop="invoiceBuyerEmail"
          label="购买人邮箱"
        >
        </el-table-column>
        <el-table-column
          prop="invoiceBuyerPhone"
          label="购买人电话"
        >
        </el-table-column>
        <el-table-column
          prop="invoiceBuyerTaxNum"
          label="购买方税号"
        >
        </el-table-column>
        <el-table-column
          prop="invoiceBuyerAddress"
          label="购买方地址"
        >
        </el-table-column>
        <el-table-column
          prop="invoiceBuyerBankAccount"
          label="购买方银行开户行及账号"
        >
        </el-table-column>
        <el-table-column
          prop="remark"
          label="备注"
        >
        </el-table-column>
        <el-table-column
          prop="manager_name"
          label="操作人"
        >
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态"
        >
          <template slot-scope="prop">
            {{ statusMap[prop.row.status] }}
          </template>
        </el-table-column>
        <el-table-column
          prop="err_info"
          label="错误信息"
        >
        </el-table-column>
        <el-table-column
          prop="qrcode_url"
          label="二维码地址"
          width="100"
          fixed="right"
        >
          <template slot-scope="prop">
            <el-button
              v-if="prop.row.qrcode_url"
              type="text"
              size="small"
              @click="showQrCode(prop.row.qrcode_url)">
              查看
            </el-button>
            <el-button
              v-if="prop.row.qrcode_url"
              type="text"
              size="small"
              @click="printMyQrCode(prop.row.qrcode_url)">
              打印
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          prop="downloadUrl"
          label="下载地址"
          width="80"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.downloadUrl"
              type="text"
              size="small"
              @click="downloadPDF(scope.row.downloadUrl)"
            >
              下载
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          prop="tickets"
          label="门票详情"
          width="80"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="showTickets(scope.row)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        :current-page.sync="form.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="form.pageSize"
        @size-change="handleSizeChange"
        @current-change="getListInvoiceRecord()"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog
      width="400px"
      title="开票二维码"
      :visible.sync="visible"
      @close="visible=false">
      <div
        class="img-wrap"
        style="display:block">
        <div
          class="img"
          :style="{backgroundImage:`url(${qrImg})`,height:'100%'}">
        </div>
      </div>
    </el-dialog>

    <el-dialog
      title="开票"
      :visible.sync="visible1"
      width="80%"
      @close="visible1=false">
      <el-table
        :data="currentOrder.recordDetailLists"
      >
        <el-table-column
          prop="ticketNo"
          label="票号"
        >
        </el-table-column>

        <el-table-column
          prop="tname"
          label="票种"
        >
        </el-table-column>

        <el-table-column
          width="80"
          label="票价(￥)"
        >
          <template slot-scope="scope">
            {{ scope.row.price/scope.row.checkNum }}
          </template>
        </el-table-column>
        <el-table-column
          prop="guestName"
          label="游客姓名"
        >
        </el-table-column>
        <el-table-column
          prop="guestIdentifyType"
          label="证件类型"
        >
          <template slot-scope="scope">
            {{ papersType[scope.row.guestIdentifyType] }}
          </template>
        </el-table-column>
        <el-table-column
          prop="guestIdentify"
          label="证件号码"
        >
        </el-table-column>

        <el-table-column
          width="100"
          prop="checkNum"
          label="检票人数"
        >
        </el-table-column>

        <el-table-column
          width="100"
          prop="payDateBegin"
          label="游玩时间"
        >
          <template slot-scope="scope">
            {{ scope.row.isNeedPlaytime?scope.row.payDateBegin:'无限制' }}
          </template>
        </el-table-column>
        <el-table-column
          width="80"
          label="取票状态"
        >
          <template slot-scope="scope">
            <el-tag :type="scope.row.isPrint?'success':'info'">
              {{ scope.row.isPrint?'已取票':'未取票' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          width="80"
          label="状态"
        >
          <template slot-scope="scope">
            <OrderStatusTag :value="scope.row.status"></OrderStatusTag>
          </template>
        </el-table-column>
        <el-table-column
          width="80"
          label="是否已开票"
        >
          <template slot-scope="scope">
            {{ scope.row.is_invoice_picked===1?'已开':'未开' }}
          </template>
        </el-table-column>
        <el-table-column
          width="80"
          prop="price"
          label="小计"
        >
        </el-table-column>
      </el-table>
    </el-dialog>

    <div
      id="printMyQrCode"
      class="img-wrap img-wrap1"
      style="display:block">
      <div
        class="img"
        :style="{backgroundImage:`url(${qrImg})`,height:'100%'}">
      </div>
    </div>
  </div>
</template>

<script>
import { listInvoiceRecord } from '@/api/ticketType'
import { papersType } from '@/assets/staticData'
import moment from 'moment'
// import axios from 'axios'
import QRCode from 'qrcode'

export default {
  name: 'invoiceRecord',
  computed: {
    salesList () {
      return this.$store.state.user.salesList
    }
  },
  data () {
    return {
      form: {
        startDate: new Date(moment().startOf('day').valueOf()),
        endDate: new Date(moment().endOf('day').valueOf()),
        keyWords1: '', // 订单号
        keyWords2: '', // 渠道名
        keyWords3: '', // 流水号
        keyWords4: '', // 开票方
        keyWords5: '', // 购买方
        keyWords6: '', // 操作人(id)
        keyWords8: '', // 状态
        pageNum: 1,
        pageSize: 10
      },
      tableData: [],
      total: 0,
      loading: false,
      visible: false,
      qrImg: '',
      visible1: false,
      currentOrder: {},
      papersType,
      statusMap: {
        '0': '未开票',
        '1': '已开票',
        '2': '开票失败',
        '3': '开票中'
      }
    }
  },
  created () {
    const searchParams = JSON.parse(sessionStorage.getItem('统计表-开票记录-查询条件'))
    if (searchParams) {
    // 如果存在查询条件，则设置到组件的数据中
      this.form = searchParams // 记住上次搜索条件
    }
    this.getListInvoiceRecord()
  },
  methods: {
    reset () {
      this.$refs.form.resetFields()
    },
    handleSizeChange (size) {
      this.form.pageSize = size
      this.getListInvoiceRecord()
    },
    getListInvoiceRecord (goFirst) {
      this.loading = true
      goFirst && (this.form.pageNum = 1)
      listInvoiceRecord(this.form).then(res => {
        this.total = res?.data.total
        this.tableData = res?.data.list
      }).finally(() => {
        this.loading = false
        sessionStorage.setItem('统计表-开票记录-查询条件', JSON.stringify(this.form)) // 下次记住
      })
    },
    printMyQrCode (qrcode) {
      this.$nextTick(async () => {
        var opts = {
          errorCorrectionLevel: 'H',
          type: 'image/png',
          quality: 1,
          color: {
            dark: '#000000ff', // Blue dots
            light: '#0000' // Transparent background
          }
        }
        this.qrImg = await QRCode.toDataURL(qrcode, opts)
        setTimeout(() => {
          const webview = document.querySelector('#printSmallTicketWebview')
          let printDoc = document.querySelector('#printMyQrCode').outerHTML
          webview.send('webview-print-render', printDoc)
        }, 1000)
      })
    },
    showQrCode (qrcode) {
      this.visible = true
      this.$nextTick(async () => {
        var opts = {
          errorCorrectionLevel: 'H',
          type: 'image/png',
          quality: 1,
          color: {
            dark: '#000000ff', // Blue dots
            light: '#0000' // Transparent background
          }
        }
        this.qrImg = await QRCode.toDataURL(qrcode, opts)
      })
    },
    showTickets (record) {
      this.currentOrder = record
      this.visible1 = true
    },
    downloadPDF (url) {
      // return axios.get(url, {
      //   responseType: 'arraybuffer'
      // }).then(res => {
      //   const blob = new Blob([res.data], { type: 'application/pdf' })
      //   const link = document.createElement('a')
      //   link.href = window.URL.createObjectURL(blob)
      //   link.download = url.split('/').pop()
      //   link.click()
      // }).catch(e => {
      //   this.$message.error(`${url}下载失败：${e}`)
      // })

      // 实际文件下载文件可能会有各种格式 pdf ofd 甚至没有文件类型 出于兼容考虑 改为浏览器下载
      const { shell } = require('electron')

      let str = url
      if (!url.startsWith('http')) {
        str = 'https://' + str
      }
      shell.openExternal(str)
    }
  }
}
</script>

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

.img-wrap1{
  visibility: hidden;
}
</style>
