<template>
  <div id="invoice_batch_printing" v-loading="loading" element-loading-text="拼命加载中......请稍等">
    <el-container>
      <el-form ref="form" style="width: 100%;">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item>
              <el-select
                  v-model="search.invoiceCategory"
                  placeholder="请选择发票种类"
                  style="width: 100%;"
              >
                <el-option
                    v-for="item in invoiceCategoryOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-select
                  v-model="search.invoiceState"
                  clearable
                  placeholder="请选择发票状态"
                  style="width: 100%;"
              >
                <el-option
                    v-for="item in invoiceStateOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-date-picker
                  v-model="search.dateRange"
                  type="daterange"
                  unlink-panels
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  style="width: 100%;"
              >
                <template slot="prepend">开票日期</template>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <div>
              <el-button @click="handleSearch" type="primary" icon="el-icon-search">搜索</el-button>
              <el-button @click="handleResetSearch">重置</el-button>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item>
              <el-input v-model="search.invoiceCode" clearable placeholder="请输入...">
                <template slot="prepend">发票代码</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-input v-model="search.invoiceNumber" clearable placeholder="请输入...">
                <template slot="prepend">发票号码</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-input v-model="search.entName" clearable placeholder="请输入...">
                <template slot="prepend">客户名称</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-container>
    <div>
      <el-button @click="pdfPrint" type="primary" icon="el-icon-printer">打印发票</el-button>
    </div>
    <br/>
    <el-container>
      <el-table
          :data="search.resultList"
          v-on:selection-change="selectData"
          border
          stripe
          :height="tableHeight"
          style="width: 100%">
        <el-table-column type="selection" align="center" width="55"></el-table-column>
        <el-table-column
            type="index"
            :index="pageIndex"
            align="center"
            label="序号"
            width="50"
        ></el-table-column>
        <el-table-column
            prop="invoiceType"
            label="发票类型"
            width="100"
            align="center"
            :formatter="fmtInvoiceType"
        ></el-table-column>
        <el-table-column
            prop="invoiceCategory"
            label="发票种类"
            width="160"
            align="center"
            :formatter="fmtInvoiceCategory"
        ></el-table-column>
        <el-table-column prop="invoiceCode" label="发票代码" width="120" show-overflow-tooltip></el-table-column>
        <el-table-column
            prop="invoiceNumber"
            label="发票号码"
            width="120"
            show-overflow-tooltip
        ></el-table-column>
        <el-table-column prop="invoiceStatusMemo" label="发票状态" width="120"></el-table-column>
        <el-table-column prop="invoiceDate" label="开票日期" width="120" show-overflow-tooltip></el-table-column>
        <el-table-column prop="customerName" label="名称" width="240" show-overflow-tooltip></el-table-column>
        <el-table-column
            prop="customerEntTaxId"
            label="纳税人识别号"
            width="180"
            show-overflow-tooltip
        ></el-table-column>
        <el-table-column prop="totalAmount" label="合计金额" width="100" show-overflow-tooltip></el-table-column>
        <el-table-column prop="totalTaxes" label="合计税额" width="100" show-overflow-tooltip></el-table-column>
        <el-table-column
            prop="totalAmountTaxes"
            label="价税合计"
            width="100"
            show-overflow-tooltip
        ></el-table-column>
        <el-table-column prop="invoicePerson" label="开票人" width="100" show-overflow-tooltip></el-table-column>
        <el-table-column
            prop="interactTypeDetail"
            label="电子邮件"
            width="180"
            show-overflow-tooltip
        ></el-table-column>
      </el-table>
    </el-container>
    <br/>
    <el-row type="flex" :gutter="20">
      <el-col :span="12"></el-col>
      <el-col :span="12">
        <div style="text-align: right;">
          <el-pagination
              layout="total, sizes, prev, pager, next"
              :current-page="search.resultPagination.currentPage"
              :page-sizes="search.resultPagination.pageSizes"
              :page-size="search.resultPagination.pageSize"
              :total="search.resultPagination.total"
              @size-change="handleSearchResultSizeChange"
              @current-change="handleSearchResultCurrentChange"
          ></el-pagination>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { invoiceQuery } from "@/api/invoice"
import DateHelper from "@/utils/date"
import cache from '@/utils/cache'
import {AxiosRequestData} from "@/data/axios_request"

// 发票种类列表
const invoiceCategoryOptions = [
  {
    value: 1,
    label: '增值税普通电子发票'
  },
  {
    value: 2,
    label: '增值税电子专用发票'
  },
  // {
  //   value: 3,
  //   label: '增值税普通纸质发票'
  // },
  // {
  //   value: 4,
  //   label: '增值税专用纸质发票'
  // }
]

// 发票状态列表
const invoiceStateOptions = [
  {
    value: 1,
    label: '开票中'
  },
  {
    value: 2,
    label: '开具失败'
  },
  {
    value: 3,
    label: '正数开具成功'
  },
  {
    value: 4,
    label: '负数开具成功'
  },
  {
    value: 5,
    label: '正数已作废'
  },
  {
    value: 6,
    label: '负数已作废'
  },
  {
    value: 7,
    label: '正数已红冲'
  }
]

const invoiceTypeOptions = [
  {
    value: 0,
    label: '蓝字发票'
  },
  {
    value: 1,
    label: '红字发票'
  }
]

/**
 * 获取发票种类文本；
 * @param {Number} intKey 发票类别的数字标识
 */
function GetInvoiceCategoryLabel(intKey) {
  let result = intKey
  for (const item of invoiceCategoryOptions) {
    if (item.value === intKey) {
      result = item.label
      break
    }
  }
  return result
}

export default {
  name: 'invoice_batch_printing',
  data() {
    return {
      loading: false,
      invoiceCategoryOptions: invoiceCategoryOptions,
      invoiceStateOptions: invoiceStateOptions,
      search: {
        entName: '',
        invoiceState: '',
        dateRange: [
          DateHelper.LocalCurrentMonthStart(),
          DateHelper.LocalCurrentMonthEnd(),
        ],
        invoiceCode: "",
        invoiceNumber: "",
        invoiceCategory: 1,
        resultList: [],
        resultMultipleSelection: [],
        resultPagination: {
          currentPage: 1,
          pageSizes: [10, 30, 50, 100],
          pageSize: 10,
          total: 0,
        },
      },
      tableHeight: "",
      show: true,
      pdfList: [],
      src: '',
      loadedRatio: 0,
      page: 1,
      numPages: 0,
      rotate: 0,
      token: '',
      entTaxId: '',
      pdfUrl: '',
      isShowPrint: false,
      selectNumber: 0
    }
  },
  created() {
    this.tableHeight = window.innerHeight - 250
    this.callInvoiceQuery(
        this.search.resultPagination.currentPage,
        this.search.resultPagination.pageSize
    )
    this.token = cache.getToken()
    let company = JSON.parse(cache.getSession('company'))
    this.entTaxId = company.entTaxId
  },
  mounted() {
    this.tableHeight = window.innerHeight - 250
    window.onresize = () => {
      return (() => {
        this.tableHeight = window.innerHeight - 250
      })()
    }
  },
  methods: {
    pageIndex(index) {
      let currentPage = this.search.resultPagination.currentPage; //当前页码，具体看组件取值
      let pageSize = this.search.resultPagination.pageSize; //每页条数，具体是组件取值
      return index + 1 + (currentPage - 1) * pageSize;
    },
    fmtInvoiceType(row, column, cellValue) {
      let result = cellValue;
      for (const item of invoiceTypeOptions) {
        if (item.value === cellValue) {
          result = item.label;
          break;
        }
      }
      return result;
    },
    fmtInvoiceCategory(row, column, cellValue) {
      return GetInvoiceCategoryLabel(cellValue);
    },
    handleSearch() {
      this.callInvoiceQuery(1, this.search.resultPagination.pageSize);
    },
    handleResetSearch() {
      this.search.entName = "";
      this.search.invoiceState = "";
      // this.search.hongchongFlag = "";
      this.search.dateRange = "";
      this.search.invoiceCode = "";
      this.search.invoiceNumber = "";
      this.search.invoiceCategory = "";
    },
    handleSearchResultSizeChange(val) {
      this.callInvoiceQuery(1, val);
    },
    handleSearchResultCurrentChange(val) {
      this.callInvoiceQuery(val, this.search.resultPagination.pageSize);
    },
    /**
     * 查询发票
     * @param {Number} pageNum : 当前页码
     * @param {Number} pageSize : 每页数量
     */
    callInvoiceQuery(pageNum, pageSize) {
      let beginTime = "";
      let endTime = "";
      if (this.search.dateRange instanceof Array) {
        beginTime = this.search.dateRange[0];
        endTime = this.search.dateRange[1];
        beginTime = this.dateFormat(
            new Date(beginTime),
            "yyyy-MM-dd HH:mm:ss"
        );
        endTime = this.dateFormat(
            new Date(endTime),
            "yyyy-MM-dd HH:mm:ss"
        );
      }
      this.loading = true;
      let _this = this;
      invoiceQuery({
        invoiceCode: this.search.invoiceCode,
        invoiceNumber: this.search.invoiceNumber,
        invoiceCategory: this.search.invoiceCategory,
        // invoiceCategory: 1,
        customerName: this.search.entName,
        invoiceState: this.search.invoiceState,
        invoiceDateBegin: beginTime,
        invoiceDateEnd: endTime,
        pageNum: pageNum,
        pageSize: pageSize,
      })
          .then((val) => {
            console.log(val)
            _this.search.resultPagination.total = val.data.total;
            _this.search.resultPagination.pageSize = val.data.size;
            _this.search.resultPagination.currentPage =
                val.data.current;
            _this.search.resultList = val.data.records;
            _this.loading = false;
          })
          .catch((err) => {
            _this.$message.error(err);
            _this.loading = false;
          });
    },
    dateFormat(date, fmt) {
      // 小时只支持24小时制
      var o = {
        "M+": date.getMonth() + 1, // 月份
        "d+": date.getDate(), // 日
        "H+": date.getHours(), // 24小时,
        "m+": date.getMinutes(), // 分
        "s+": date.getSeconds(), // 秒
        "q+": Math.floor((date.getMonth() + 3) / 3), // 季度
        S: date.getMilliseconds(), // 毫秒
      };
      if (/(y+)/.test(fmt))
        fmt = fmt.replace(
            RegExp.$1,
            (date.getFullYear() + "").substr(4 - RegExp.$1.length)
        );
      for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
          fmt = fmt.replace(
              RegExp.$1,
              RegExp.$1.length == 1
                  ? o[k]
                  : ("00" + o[k]).substr(("" + o[k]).length)
          );
      return fmt;
    },
    // 获取选中数据
    selectData(selection) {
      this.pdfList = []
      this.selectNumber = selection.length
      selection.map((_, i) => {
        let pdfUrl = ''
        if (selection[i].fileUrl !== null) {
          pdfUrl = selection[i].fileUrl + '.pdf'
          this.pdfList = this.pdfList.concat(pdfUrl)
        }
      })
    },
    // pdf合并打印
    async pdfPrint() {
      if (this.pdfList.length > 0) {
        if (this.token) {
          const url = '/sys/invoice/mergeEInvoicePdf'
          let response = await AxiosRequestData(
              url,
              this.token,
              {
                entTaxId: this.entTaxId,
                pdfUrls: this.pdfList
              },
              false,
              1
          )
          if (response) {
            if (response.code === 0) {
              if (response.data.mergeFileUrl === '') {
                this.$message.error('发票批量打印生成失败！')
              } else {
                window.open(response.data.mergeFileUrl, '_blank')
              }
            } else {
              this.$message.error(response.msg)
            }
          }
        }
      } else {
        this.$message({
          message: '请选择需要批量打印的发票信息！',
          type: 'warning'
        })
      }
    }
  }
}
</script>

<style scoped>

</style>
