<template>
  <div
      id="invoice_query"
      v-loading="loading"
      element-loading-text="拼命加载中......请稍等"
  >
    <el-container>
      <el-form label-position="top" ref="form" style="width: 100%">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="起始日期：">
              <el-date-picker
                  v-model="search.beginDate"
                  type="date"
                  :clearable="false"
                  placeholder="选择日期"
                  style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结束日期：">
              <el-date-picker
                  v-model="search.endDate"
                  type="date"
                  :clearable="false"
                  placeholder="选择日期"
                  style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="6">
            <el-form-item>
                            <span slot="label" style="color: #909399">
                                <span>&nbsp;&nbsp;</span>
                            </span>
              <el-button
                  @click="handleSearch"
                  type="primary"
                  icon="el-icon-search"
              >搜索
              </el-button
              >
              <el-button @click="handleResetSearch"
              >重置
              </el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
        <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-input
                  v-model="search.invoicePerson"
                  clearable
                  placeholder="请输入..."
              >
                <template slot="prepend">开票人</template>
              </el-input>
            </el-form-item>
          </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-autocomplete
                  v-model="search.entName"
                  placeholder="请输入"
                  :fetch-suggestions="entAutoSearch"
                  style="width: 100%"
              >
                <template slot="prepend">客户名称</template>
                <template slot-scope="{ item }">
                  <div class="name">{{ item }}</div>
                </template>
              </el-autocomplete>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-container>
    <div>
      <el-button
          @click="handlePrintFPQSHZDShowDialog"
          type="primary"
          icon="el-icon-printer"
          v-show="true"
      >打印发票签收回执单
      </el-button
      >
    </div>
    <br/>
    <el-container>
      <el-table
          :data="search.resultList"
          @selection-change="handleSearchResultCheckChange"
          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="130"
            align="center"
            :formatter="fmtInvoiceCategory"
        ></el-table-column>
        <el-table-column
            prop="invoiceCode"
            label="发票代码"
            width="110"
            show-overflow-tooltip
        ></el-table-column>
        <el-table-column
            prop="invoiceNumber"
            label="发票号码"
            width="80"
            show-overflow-tooltip
        ></el-table-column>
        <el-table-column
            prop="invoiceStatusMemo"
            label="发票状态"
            width="100"
        ></el-table-column>
        <el-table-column
            prop="invoiceDate"
            label="开票日期"
            width="90"
            show-overflow-tooltip
        ></el-table-column>
        <el-table-column
            prop="invalidTime"
            label="作废日期"
            width="90"
            show-overflow-tooltip
        ></el-table-column>
        <el-table-column
            prop="customerName"
            label="名称"
            width="150"
            show-overflow-tooltip
        ></el-table-column>
        <el-table-column
            prop="customerEntTaxId"
            label="纳税人识别号"
            width="130"
            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-column
            label="操作"
            width="180"
            align="center"
            fixed="right"
        >
          <template slot-scope="scope">
            <el-button
                @click="handleShowInvoiceDetails(scope.row)"
                type="primary"
            >查看票样
            </el-button
            >
            <el-button
                @click="handleInvoiceRefresh(scope.row)"
                :disabled="handleInvoiceRefreshDisabled(scope.row)"
                type="primary"
            >刷新
            </el-button
            >
          </template>
        </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>

    <el-dialog
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        center
        width="300mm"
        top="10vh"
        :visible.sync="invoiceDetails.dialogVisible"
        @opened="handleInvoiceDetailsDialogOpened"
        @closed="handleInvoiceDetailsDialogClosed"
    >
      <div
          v-loading="invoiceDetails.loading"
          element-loading-text="拼命加载中......请稍等"
      >
        <el-row>
          <el-col :span="4">
            <el-radio-group v-model="invoiceDetails.tabPosition">
              <el-radio-button
                  v-for="item in invoiceDetails.tabPositonOptions"
                  :key="item.value"
                  :label="item.value"
                  :disabled="item.disabled"
              >{{ item.label }}
              </el-radio-button
              >
            </el-radio-group>
          </el-col>
          <el-col :span="20">
            <div style="text-align: right">
              <el-button
                  :disabled="invoiceInvalidDisabled"
                  @click="handleInvoiceInvalid"
              >发票作废
              </el-button
              >
              <el-button
                  :disabled="invoiceHongchongDisabled"
                  @click="handleGoHongchong"
              >立即红冲
              </el-button
              >
              <el-button
                  :disabled="downloadInvoiceDisabled"
                  @click="handleInvoiceGenerate"
              >生成发票
              </el-button
              >
              <!-- <el-button :disabled="downloadInvoiceDisabled" @click="handleDownloadInvoiceOFD">
    下载OFD格式发票
              </el-button>-->
              <el-button
                  :disabled="downloadInvoiceDisabled"
                  @click="handleInvoiceDeliveryDialogShow"
              >发票交付
              </el-button
              >
              <el-button
                  :disabled="printInvoiceDisabled"
                  @click="handlePrintInvoice"
              >打印发票与清单
              </el-button
              >
              <el-button
                  :disabled="invoiceDetails.listDisabled"
                  @click="handlePrintInvoiceList"
              >打印发票清单
              </el-button
              >
              <el-button
                  :disabled="printInvoiceDisabled"
                  @click="handlePrintInvoiceNoList"
              >打印发票（不含清单）
              </el-button
              >
              <el-button @click="handlePrintMargins"
              >打印机页边距设置
              </el-button
              >
            </div>
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <div>
          <el-card
              v-show="invoiceDetails.tabPosition == 1"
              style="text-align: center"
          >
            <invoice-dzfp ref="invoice-dzfp-sample"></invoice-dzfp>
          </el-card>
          <div v-show="invoiceDetails.tabPosition == 2">
            <el-table
                :data="invoiceDetails.goodsList"
                height="550px"
                border
                stripe
                style="width: 100%"
            >
              <el-table-column
                  type="index"
                  :index="pageIndex"
                  align="center"
                  label="序号"
                  width="50"
              ></el-table-column>
              <el-table-column
                  prop="goodsCode"
                  label="商品编码"
                  width="180"
                  show-overflow-tooltip
              ></el-table-column>
              <el-table-column
                  prop="goodsName"
                  label="项目名称"
                  width="180"
                  show-overflow-tooltip
              ></el-table-column>
              <el-table-column
                  prop="goodsSpecification"
                  label="规格型号"
              ></el-table-column>
              <el-table-column
                  prop="goodsUnit"
                  label="单位"
              ></el-table-column>
              <el-table-column
                  prop="goodsQuantity"
                  label="数量"
              ></el-table-column>
              <el-table-column
                  prop="goodsPrice"
                  label="单价"
              ></el-table-column>
              <el-table-column
                  prop="goodsTotalPrice"
                  label="金额"
              ></el-table-column>
              <el-table-column
                  prop="goodsTaxRate"
                  label="税率"
              ></el-table-column>
              <el-table-column
                  prop="goodsTotalTax"
                  label="税额"
              ></el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </el-dialog>

    <el-dialog
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        width="282mm"
        top="10vh"
        :visible.sync="printFPQSHZD.dialogVisible"
        append-to-body
    >
      <div>
        <div style="text-align: right">
          <el-button v-print="printFPQSHZD.printObj" type="primary"
          >立即打印
          </el-button
          >
        </div>
        <div
            :id="printFPQSHZD.printObj.id"
            style="
                        margin: 0px;
                        height: auto;
                        font-size: 16px;
                        padding-top: 1px;
                    "
        >
          <h1 style="text-align: center; margin-bottom: 30px">
            发票签收回执单
          </h1>
          <div style="text-indent: 2em; width: 100%">
            <span>致：</span>
            <span style="text-decoration: underline">
                            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        </span>
            <br/>
            <p>
              烦请核对您收到的发票，确认无误后请在发票回执单上签字并且盖章（公章或财务章）。
            </p>
            <p style="line-height: 2">
              今收到
              <span style="text-decoration: underline">
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span
              >开具的&nbsp;<span style="border: 1px solid black"
            >&nbsp;&nbsp;&nbsp;&nbsp;</span
            >&nbsp;增值税普通纸质发票&nbsp;
              <span style="border: 1px solid black"
              >&nbsp;&nbsp;&nbsp;&nbsp;</span
              >&nbsp;增值税专用纸质发票&nbsp;
              <span style="border: 1px solid black"
              >&nbsp;&nbsp;&nbsp;&nbsp;</span
              >&nbsp;（其它）
              <span style="text-decoration: underline">
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span
              >共计
              <span style="text-decoration: underline">
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                {{ search.resultMultipleSelection.length }}
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span
              >份，联次齐全，发票填写正确，明细如下：
            </p>
          </div>
          <div
              style="
                            text-align: center;
                            padding: 0px;
                            margin: 0px;
                            border: 1px solid #868686;
                            margin-top: 30px;
                        "
          >
            <el-table
                :data="search.resultMultipleSelection"
                :summary-method="getFPQSHZDSummaries"
                show-summary
                border
                style="width: 100%; border: 1px solid #868686"
            >
              <el-table-column
                  type="index"
                  :index="pageIndex"
                  align="center"
                  label="序号"
                  width="50"
                  :key="0"
              ></el-table-column>
              <el-table-column
                  prop="invoiceCategory"
                  label="发票种类"
                  align="center"
                  :key="1"
                  :formatter="fmtInvoiceCategory"
              ></el-table-column>
              <el-table-column
                  prop="belongEntName"
                  label="销方"
                  align="center"
                  :key="2"
                  :formatter="fmtInvoiceCategory"
              ></el-table-column>
              <el-table-column
                  prop="customerName"
                  label="购方"
                  align="center"
                  :key="3"
                  :formatter="fmtInvoiceCategory"
              ></el-table-column>
              <el-table-column
                  prop="invoiceDate"
                  label="开票日期"
                  align="center"
                  :key="4"
              ></el-table-column>
              <el-table-column
                  prop="invoiceCode"
                  label="发票代码"
                  align="center"
                  :key="5"
              ></el-table-column>
              <el-table-column
                  prop="invoiceNumber"
                  label="发票号码"
                  align="center"
                  :key="6"
              ></el-table-column>
              <el-table-column
                  prop="totalAmount"
                  label="未税金额"
                  align="center"
                  :key="7"
              ></el-table-column>
              <el-table-column
                  prop="totalTaxes"
                  label="税额"
                  align="center"
                  :key="8"
              ></el-table-column>
              <el-table-column
                  prop="totalAmountTaxes"
                  label="价税合计"
                  align="center"
                  :key="9"
              ></el-table-column>
              <el-table-column
                  prop="amount3"
                  label="备注"
                  align="center"
                  :key="10"
              ></el-table-column>
            </el-table>
          </div>
          <div
              style="text-indent: 2em; width: 100%; margin-top: 30px"
          >
            <p>确认：核对无误！</p>
            <div class="Row">
              <div class="Column">收票单位（公章或财务章）：</div>
              <div class="Column">收票人签字：</div>
              <div class="Column">日期：</div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <invoice-delivery-dialog
        ref="invoiceDeliveryDialogRef"
        @submit="handleInvoiceDeliveryDialogSubmit"
    ></invoice-delivery-dialog>
  </div>
</template>

<script>
import { invoiceQuery, invoiceRefresh, invoiceRetry } from '@/api/invoice'
import { hongchongInvoiceRefresh } from '@/api/hongchong_info'
import {
  printInvoice,
  printInvoiceList,
  printInvoiceNoList,
  printMargins,
} from '@/api/printer'
import { InvoiceInvalid, InvoiceResultData } from '@/api/invoice_ext'
import {
  GetGoodsList,
  GetInvoiceDownloadUrl,
  invoiceDelivery,
} from '@/api/invoice_info'
import { getHongchongDownloadUrl } from '@/api/hongchong_info'
import InvoiceDZFP from '@/components/InvoiceSample/InvoiceDZFP'
import DateHelper from '@/utils/date'
import cache from '@/utils/cache'
import floatCalculate from '@/utils/float-calculate'
import { getSearchHistory } from '@/api/user_config'
import InvoiceDeliveryDialog from './components/invoice-delivery-dialog'

// 发票种类列表
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: '红字发票',
  },
  {
    value: 2,
    label: '空白作废发票',
  },
]

// 发票明细页面标签列表
const invoiceDetailsTabPositonOptions = [
  {
    value: 1,
    label: '发票',
  },
  {
    value: 2,
    label: '商品清单',
  },
]

// 发票明细页面无发票清单标签列表
const invoiceDetailsTabPositonDisabledGoodsListOptions = [
  {
    value: 1,
    label: '发票',
  },
  {
    value: 2,
    label: '商品清单',
    disabled: true,
  },
]

/**
 * 获取发票种类文本；
 * @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_query2',
  components: {
    'invoice-dzfp': InvoiceDZFP,
    InvoiceDeliveryDialog,
  },
  data() {
    return {
      loading: false,
      invoiceCategoryOptions: invoiceCategoryOptions,
      invoiceStateOptions: invoiceStateOptions,
      search: {
        entName: '',
        invoiceState: '',
        beginDate: DateHelper.LocalCurrentMonthStart(),
        endDate: DateHelper.LocalCurrentMonthEnd(),
        invoiceCode: '',
        invoiceNumber: '',
        invoiceCategory: '',
        invoicePerson: '',
        resultList: [],
        resultMultipleSelection: [],
        resultPagination: {
          currentPage: 1,
          pageSizes: [10, 30, 50, 100],
          pageSize: 10,
          total: 0,
        },
      },
      invoiceDetails: {
        loading: false,
        dialogVisible: false,
        tabPositonOptions: invoiceDetailsTabPositonOptions,
        listDisabled: false, // 发票无清单为true，否则为false
        tabPosition: 1,
        selectRow: {}, // 用户选中的发票数据；
        goodsList: [], // 发票清单；
        isGoHongChong: false, // 是否是去红冲，关闭对话框的使用，是红冲这不刷新查询列表；
      },
      printFPQSHZD: {
        dialogVisible: false,
        entName: JSON.parse(cache.getSession('company')).entName,
        printObj: {
          id: 'print-region', // 这里是要打印元素的ID
        },
      },
      tableHeight: '',
      restaurants: [], // 客户提示列表
      invoiceDeliveryDialog: {
        visible: false,
        loading: false,
        interactType: '1',
        interactTypeDetail: '',
      },
    }
  },
  created() {
    this.tableHeight = window.innerHeight - 250
    this.callInvoiceQuery(
        this.search.resultPagination.currentPage,
        this.search.resultPagination.pageSize
    )

    this.getSearchHistory()
  },
  mounted() {
    this.tableHeight = window.innerHeight - 250
    window.onresize = () => {
      return (() => {
        this.tableHeight = window.innerHeight - 250
      })()
    }
  },
  computed: {
    // 发票作废功能是否禁用；
    invoiceInvalidDisabled: function () {
      let row = this.invoiceDetails.selectRow

      // 没有操作数据
      if (!row) return true

      // 发票开具中或发票开票失败
      if (row.status == 1 || row.status == 2) return true
      // 正数已作废、负数已作废、空白作废
      if (row.status == 5 || row.status == 6 || row.status == 7) {
        return true
      }
      // 发票不是纸质发票
      if (row.invoiceCategory != 3 && row.invoiceCategory != 4) {
        return true
      }

      // 发票开具时间不属于当前月份
      var nowMonth = new Date().getMonth()
      let invoiceMonth = new Date(row.invoiceDate).getMonth()
      if (nowMonth != invoiceMonth) return true

      return false
    },
    // 发票红冲功能是否禁用；
    invoiceHongchongDisabled: function () {
      let row = this.invoiceDetails.selectRow

      // 没有操作数据
      if (!row) return true

      // 蓝票
      if (row.invoiceType != 0) return true

      // 发票是纸质专发票
      if (row.invoiceCategory == 4) return true

      // 正数开具成功
      if (row.status != 3) return true

      return false
    },
    // 下载发票功能是否禁用；
    downloadInvoiceDisabled: function () {
      let row = this.invoiceDetails.selectRow

      // 没有操作数据
      if (!row) return true

      // 发票不是电子发票
      if (row.invoiceCategory != 1 && row.invoiceCategory != 2) {
        return true
      }

      // 正数开具成功  负数开具成功
      if (row.status != 3 && row.status != 4) return true

      return false
    },
    // 打印发票功能是否禁用；
    printInvoiceDisabled: function () {
      let row = this.invoiceDetails.selectRow

      // 没有操作数据
      if (!row) return true

      // 发票不是纸质发票
      if (row.invoiceCategory != 3 && row.invoiceCategory != 4) {
        return true
      }

      // 正数开具成功  负数开具成功
      if (row.status != 3 && row.status != 4) return true

      return false
    },
  },
  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)
    },
    // 发票签收回执单 合计
    getFPQSHZDSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = '合计'
          return
        }
        const values = data.map((item) =>
            Number(item[column.property])
        )
        if (index === 7 || index === 8 || index === 9) {
          if (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return floatCalculate.add(prev, curr)
              } else {
                return prev
              }
            }, 0)
          } else {
            sums[index] = 'N/A'
          }
        }
      })

      return sums
    },
    handlePrintMargins() {
      printMargins()
    },
    // 发票刷新按钮是否禁用；
    handleInvoiceRefreshDisabled(row) {
      return row.status != 1
    },
    // 发票刷新；
    handleInvoiceRefresh(row) {
      let _this = this
      _this.loading = true
      invoiceRefresh(row.invoiceReqFlowNo)
          .then((val) => {
            _this.$message.success(val.msg)
            _this.loading = false
            return _this.callInvoiceQuery(
                _this.search.resultPagination.currentPage,
                _this.search.resultPagination.pageSize
            )
          })
          .catch((err) => {
            _this.$message.error(err)
            _this.loading = false
          })
    },
    // 显示发票详细信息弹窗；
    handleShowInvoiceDetails(row) {
      console.log('显示发票详细信息：')
      console.log(row)

      // 空白作废发票
      if (row.invoiceType == 2) {
        this.$message.error('空白作废发票，无法查看票样！')
        return false
      }

      // 开票中
      // if (row.status == 2) {
      //     this.$message.error("发票开票中，无法查看票样！");
      //     return false;
      // }

      // 开票失败
      // if (row.status == 4) {
      //     this.$message.error("发票开票失败，无法查看票样！");
      //     return false;
      // }

      // 如果此时发票状态不是开票成功
      // if (row.status != 3 && row.status != 2) {
      //     this.$message.error("发票状态未知，请您稍后重试！");
      //     return false;
      // } else {
      //     // 设置用户选中的发票数据；
      //     this.invoiceDetails.selectRow = row;
      //     this.invoiceDetails.dialogVisible = true;
      // }

      // 设置用户选中的发票数据；
      this.invoiceDetails.selectRow = row
      this.invoiceDetails.dialogVisible = true
    },
    // 发票详细页面打开结束时的回调；
    handleInvoiceDetailsDialogOpened() {
      // 重置
      this.invoiceDetails.tabPosition = 1
      this.invoiceDetails.listDisabled = true
      this.invoiceDetails.goodsList = [] // 发票清单；
      this.invoiceDetails.isGoHongChong = false

      let row = this.invoiceDetails.selectRow
      if (row) {
        this.invoiceDetails.loading = true
        let _this = this
        if (row.status == 1 || row.status == 2) {
          // 开票中 或 开票失败
          GetGoodsList(row.orderId, 1, 10000)
              .then((val) => {
                let invoiceSample =
                    _this.$refs['invoice-dzfp-sample']
                let title = GetInvoiceCategoryLabel(
                    row.invoiceCategory
                )
                invoiceSample.setTitle(title)
                invoiceSample.setInvoiceBaseInfo({
                  invoiceCode: '待生成',
                  invoiceNo: '待生成',
                  invoiceDate: row.invoiceDate,
                  invoiceCheckCode: '待生成',
                  machineNo: '待生成',
                  invoiceTotalPrice: row.totalAmount,
                  invoiceTotalTax: row.totalTaxes,
                  invoiceTotalPriceTax: row.totalAmountTaxes,
                  payee: '',
                  checker: '',
                  drawer: row.invoicePerson,
                  taxControlCode: '待生成',
                  remarks: row.remark,
                })
                invoiceSample.setInvoiceGF({
                  name: row.customerName,
                  entTaxId: row.customerEntTaxId,
                  bankAccount: row.customerBankAccount,
                  addressPhone: row.customerAddressPhone,
                })
                let entInfo = JSON.parse(
                    cache.getSession('company')
                )
                if (entInfo) {
                  console.log('销方信息：')
                  console.log(entInfo)

                  let bankAccountTemp = entInfo.bankAccountNumber
                  if (entInfo.bankName) {
                    bankAccountTemp =
                        entInfo.bankName +
                        ' ' +
                        bankAccountTemp
                  }
                  let addressPhoneTemp = entInfo.entPhone
                  if (entInfo.entAddress) {
                    addressPhoneTemp =
                        entInfo.entAddress +
                        ' ' +
                        addressPhoneTemp
                  }
                  invoiceSample.setInvoiceXF({
                    name: entInfo.entName,
                    entTaxId: entInfo.entTaxId,
                    bankAccount: bankAccountTemp,
                    addressPhone: addressPhoneTemp,
                  })
                }
                console.log('商品列表：')
                console.log(val.data.records)
                let goodsLsitTemp = []
                if (val.data.records) {
                  for (
                      let i = 0;
                      i < val.data.records.length;
                      i++
                  ) {
                    const element = val.data.records[i]
                    goodsLsitTemp[i] = {
                      goodsCode: element.itemCode,
                      goodsName: element.itemName,
                      goodsSpecification:
                      element.specifications,
                      goodsUnit: element.unit,
                      goodsQuantity: element.number,
                      goodsPrice: element.price,
                      goodsTotalPrice: element.amount,
                      goodsTaxRate: element.taxRate,
                      goodsTotalTax: element.taxes,
                    }
                  }
                }

                if (row.goodsListMark == 1) {
                  // 有清单；
                  invoiceSample.setInvoiceCommodity([])
                  _this.invoiceDetails.goodsList = goodsLsitTemp
                  _this.invoiceDetails.tabPositonOptions = invoiceDetailsTabPositonOptions
                  _this.invoiceDetails.listDisabled = false
                } else {
                  invoiceSample.setInvoiceCommodity(
                      goodsLsitTemp
                  )
                  _this.invoiceDetails.tabPositonOptions = invoiceDetailsTabPositonDisabledGoodsListOptions
                  _this.invoiceDetails.listDisabled = true
                }
                _this.invoiceDetails.loading = false
              })
              .catch((err) => {
                _this.$message.error(err)
                _this.invoiceDetails.loading = false

                _this.invoiceDetails.selectRow = {}
                _this.invoiceDetails.dialogVisible = false
              })
        } else {
          InvoiceResultData(row.orderId, row.invoiceType)
              .then((val) => {
                // 设置发票票样显示信息；
                let invoiceSample =
                    _this.$refs['invoice-dzfp-sample']
                let title = GetInvoiceCategoryLabel(
                    row.invoiceCategory
                )
                invoiceSample.setTitle(title)
                invoiceSample.setInvoiceBaseInfo({
                  invoiceCode: val.data.invoiceData.invoiceCode,
                  invoiceNo: val.data.invoiceData.invoiceNo,
                  invoiceDate: val.data.invoiceData.invoiceDate,
                  invoiceCheckCode:
                  val.data.invoiceData.invoiceCheckCode,
                  machineNo: val.data.invoiceData.machineNo,
                  invoiceTotalPrice:
                  val.data.invoiceData.invoiceTotalPrice,
                  invoiceTotalTax:
                  val.data.invoiceData.invoiceTotalTax,
                  invoiceTotalPriceTax:
                  val.data.invoiceData.invoiceTotalPriceTax,
                  payee: val.data.invoiceData.payee,
                  checker: val.data.invoiceData.checker,
                  drawer: val.data.invoiceData.drawer,
                  taxControlCode:
                  val.data.invoiceData.taxControlCode,
                  remarks: val.data.invoiceData.remarks,
                })
                invoiceSample.setInvoiceGF({
                  name: val.data.invoiceData.buyerName,
                  entTaxId: val.data.invoiceData.buyerEntTaxId,
                  bankAccount:
                  val.data.invoiceData.buyerBankAccount,
                  addressPhone:
                  val.data.invoiceData.buyerAddressPhone,
                })
                invoiceSample.setInvoiceXF({
                  name: val.data.invoiceData.sellerEntName,
                  entTaxId: val.data.invoiceData.sellerEntTaxId,
                  bankAccount:
                  val.data.invoiceData.sellerBankAccount,
                  addressPhone:
                  val.data.invoiceData.sellerAddressPhone,
                })
                if (val.data.invoiceData.goodsListMark == 1) {
                  // 有清单；
                  invoiceSample.setInvoiceCommodity([])
                  _this.invoiceDetails.goodsList =
                      val.data.invoiceData.goodsDetailVOs
                  _this.invoiceDetails.tabPositonOptions = invoiceDetailsTabPositonOptions
                  _this.invoiceDetails.listDisabled = false
                } else {
                  invoiceSample.setInvoiceCommodity(
                      val.data.invoiceData.goodsDetailVOs
                  )
                  _this.invoiceDetails.tabPositonOptions = invoiceDetailsTabPositonDisabledGoodsListOptions
                  _this.invoiceDetails.listDisabled = true
                }
                _this.invoiceDetails.loading = false
              })
              .catch((err) => {
                _this.$message.error(err)
                _this.invoiceDetails.loading = false

                _this.invoiceDetails.selectRow = {}
                _this.invoiceDetails.dialogVisible = false
              })
        }
      } else {
        console.log('没有选中数据！')
      }
    },
    // 发票详细页面关闭结束时的回调
    handleInvoiceDetailsDialogClosed() {
      let row = this.invoiceDetails.selectRow
      if (row && this.invoiceDetails.isGoHongChong == false) {
        this.callInvoiceQuery(
            this.search.resultPagination.currentPage,
            this.search.resultPagination.pageSize
        )
      } else {
        console.log('没有选中数据！')
      }
    },
    // 发票作废；
    handleInvoiceInvalid() {
      let _this = this
      let row = this.invoiceDetails.selectRow
      if (row) {
        this.$confirm(
            '发票代码：' +
            row.invoiceCode +
            ' 发票号码：' +
            row.invoiceNumber +
            ' 是否作废当前发票！',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
        )
            .then(() => {
              _this.invoiceDetails.loading = true
              InvoiceInvalid({
                invoiceInvalidType: row.invoiceType,
                invoiceCategory: row.invoiceCategory,
                invoiceCode: row.invoiceCode,
                invoiceNumber: row.invoiceNumber,
              })
                  .then((val) => {
                    _this.$message.success(val.msg)
                    _this.invoiceDetails.loading = false
                  })
                  .catch((err) => {
                    _this.$message.error(err)
                    _this.invoiceDetails.loading = false
                  })
            })
            .catch(() => {
              // 取消；
            })
      } else {
        console.log('没有选中数据！')
      }
    },
    // 发票红冲
    handleGoHongchong() {
      let row = this.invoiceDetails.selectRow

      let tempPageName = ''
      if (row.invoiceCategory == 3) {
        // 普通纸质发票
        tempPageName = 'ordinary_invoice'
      } else if (row.invoiceCategory == 4) {
        // 专用纸质发票
        tempPageName = 'special_invoice'
      } else if (row.invoiceCategory == 1) {
        // 普通电子发票
        tempPageName = 'electronics_invoice'
      }

      let tempParams = {
        invoiceOperation: 1, // 表示红冲
        invoiceCode: row.invoiceCode,
        invoiceNumber: row.invoiceNumber,
      }

      if (tempPageName) {
        this.invoiceDetails.isGoHongChong = true
        this.invoiceDetails.dialogVisible = false
        this.$router.push({
          name: tempPageName,
          params: tempParams,
        })
      } else {
        this.$message.error('发票种类无效！')
      }
    },
    // 发票生成
    handleInvoiceGenerate() {
      let row = this.invoiceDetails.selectRow
      let _this = this
      let download = function (url) {
        let fullUrl = url + '.pdf'
        console.log(fullUrl)
        window.open(fullUrl)
      }
      if (row) {
        GetInvoiceDownloadUrl({
          invoiceCode: row.invoiceCode,
          invoiceNumber: row.invoiceNumber,
        })
            .then((val) => {
              this.$confirm(
                  `发票号码 [ ${row.invoiceNumber} ] 已生成成功, 是否立即下载?`,
                  '提示',
                  {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'success',
                    center: true,
                  }
              )
                  .then(() => {
                    if (val.data) {
                      download(val.data.fileUrl)
                    } else {
                      _this.$message.error(
                          'PDF格式发票文件下载链接无效！'
                      )
                    }
                  })
                  .catch(() => {
                    // 无取消操作
                  })
            })
            .catch((err) => {
              _this.$message.error(err)
            })
      } else {
        console.log('没有选中数据！')
      }
    },
    // 下载PDF格式发票；
    handleDownloadInvoicePDF() {
      let row = this.invoiceDetails.selectRow
      let _this = this
      let download = function (url) {
        let fullUrl = url + '.pdf'
        console.log(fullUrl)
        window.open(fullUrl)
        // _this
        //     .isRunUrl(fullUrl)
        //     .then((val) => {
        //         let a = document.createElement("a");
        //         a.href = fullUrl;
        //         a.target = "_blank";
        //         a.click();
        //     })
        //     .catch((err) => {
        //         _this.$message.error("PDF格式发票文件下载链接无效！");
        //     });
      }
      if (row) {
        let url = row.fileUrl
        if (url === null || url === '' || url === undefined) {
          GetInvoiceDownloadUrl({
            invoiceCode: row.invoiceCode,
            invoiceNumber: row.invoiceNumber,
          })
              .then((val) => {
                if (val.data) {
                  download(val.data.fileUrl)
                } else {
                  _this.$message.error(
                      'PDF格式发票文件下载链接无效！'
                  )
                }
              })
              .catch((err) => {
                _this.$message.error(err)
              })
        } else {
          download(url)
        }
      } else {
        console.log('没有选中数据！')
      }
    },
    // 下载OFD格式发票；
    // handleDownloadInvoiceOFD() {
    //     let row = this.invoiceDetails.selectRow;
    //     let url = row.fileUrl;
    //     if (row) {
    //         if (url === null || url === '' || url === undefined) {
    //             this.$message.error('OFD格式发票文件下载链接无效！');
    //         } else {
    //             let fullUrl = url + '.ofd';
    //             console.log(fullUrl);
    //             this.isRunUrl(fullUrl).then(val => {
    //                 let a = document.createElement('a')
    //                 a.href = fullUrl;
    //                 a.target = "_blank";
    //                 a.click();
    //             }).catch(err => {
    //                 this.$message.error('OFD格式发票文件下载链接无效！');
    //             })
    //         }
    //     } else {
    //         console.log('没有选中数据！')
    //     }
    // },
    // 打印发票与清单；
    handlePrintInvoice() {
      let row = this.invoiceDetails.selectRow
      if (row) {
        printInvoice(row.invoiceReqFlowNo, row.invoiceType)
            .then()
            .catch((err) => {
              this.$message.error(err)
            })
      } else {
        console.log('没有选中数据！')
      }
    },
    // 打印发票清单；
    handlePrintInvoiceList() {
      let row = this.invoiceDetails.selectRow
      if (row) {
        printInvoiceList(row.invoiceReqFlowNo, row.invoiceType)
            .then()
            .catch((err) => {
              this.$message.error(err)
            })
      } else {
        console.log('没有选中数据！')
      }
    },
    // 打印发票（不含清单）
    handlePrintInvoiceNoList() {
      let row = this.invoiceDetails.selectRow
      if (row) {
        printInvoiceNoList(row.invoiceReqFlowNo, row.invoiceType)
            .then()
            .catch((err) => {
              this.$message.error(err)
            })
      } else {
        console.log('没有选中数据！')
      }
    },
    handleSearch() {
      this.callInvoiceQuery(1, this.search.resultPagination.pageSize)
    },
    handleResetSearch() {
      this.search.entName = ''
      this.search.invoiceState = ''
      // this.search.hongchongFlag = "";
      this.search.beginDate = DateHelper.LocalCurrentMonthStart()
      this.search.endDate = DateHelper.LocalCurrentMonthEnd()
      this.search.invoiceCode = ''
      this.search.invoiceNumber = ''
      this.search.invoiceCategory = ''
    },
    handleSearchResultCheckChange(val) {
      this.search.resultMultipleSelection = val
      console.log('选中数据：')
      console.log(this.search.resultMultipleSelection)
    },
    handleSearchResultSizeChange(val) {
      this.callInvoiceQuery(1, val)
    },
    handleSearchResultCurrentChange(val) {
      this.callInvoiceQuery(val, this.search.resultPagination.pageSize)
    },
    handlePrintFPQSHZDShowDialog() {
      this.printFPQSHZD.dialogVisible = true
    },
    /**
     * 查询发票
     * @param {Number} pageNum : 当前页码
     * @param {Number} pageSize : 每页数量
     */
    callInvoiceQuery(pageNum, pageSize) {
      let beginTime = this.search.beginDate
      let endTime = this.search.endDate

      if (!beginTime || !endTime) {
        this.$message.error(
            '起始日期与结束日期为必输项，请确定后重试！'
        )
        return false
      }

      beginTime = this.dateFormat(
          new Date(beginTime),
          'yyyy-MM-dd HH:mm:ss'
      )

      let endTimeObj = new Date(endTime)
      endTime = this.dateFormat(
          new Date(
              endTimeObj.getFullYear(),
              endTimeObj.getMonth(),
              endTimeObj.getDate(),
              '23',
              '59',
              '59'
          ),
          'yyyy-MM-dd HH:mm:ss'
      )
      if (beginTime && endTime) {
        if (DateHelper.ValidateDateRange(beginTime, endTime) == false) {
          this.$message.error(
              '起始日期与结束日期不合法，请确定后重试！'
          )
          return false
        }
      }

      this.loading = true
      let _this = this
      invoiceQuery({
        invoiceCode: this.search.invoiceCode,
        invoiceNumber: this.search.invoiceNumber,
        invoiceCategory: this.search.invoiceCategory,
        customerName: this.search.entName,
        status: this.search.invoiceState,
        invoicePerson: this.search.invoicePerson,
        invoiceDateBegin: beginTime,
        invoiceDateEnd: endTime,
        pageNum: pageNum,
        pageSize: pageSize,
      })
          .then((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

            _this.getSearchHistory()
          })
          .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
    },
    entAutoSearch(queryString, cb) {
      var restaurants = this.restaurants
      var results = queryString
          ? restaurants.filter(
              this.createEntAutoSearchFilter(queryString)
          )
          : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createEntAutoSearchFilter(queryString) {
      return (restaurant) => {
        return (
            restaurant
                .toLowerCase()
                .indexOf(queryString.toLowerCase()) === 0
        )
      }
    },
    // 获取客户搜索历史
    getSearchHistory() {
      let _this = this
      getSearchHistory()
          .then((val) => {
            _this.restaurants = val.data
          })
          .catch((err) => {
          })
          .finally(() => {
          })
    },
    handleInvoiceDeliveryDialogShow() {
      let row = this.invoiceDetails.selectRow
      let _this = this
      if (row) {
        _this.invoiceDetails.loading = true
        GetInvoiceDownloadUrl({
          invoiceCode: row.invoiceCode,
          invoiceNumber: row.invoiceNumber,
        })
            .then((val) => {
              _this.$refs.invoiceDeliveryDialogRef.url = val.data.fileUrl
              _this.$refs.invoiceDeliveryDialogRef.visible = true
            })
            .catch((err) => {
              _this.$message.error(err)
            })
            .finally(() => {
              _this.invoiceDetails.loading = false
            })
      } else {
        console.log('没有选中数据！')
      }
    },
    handleInvoiceDeliveryDialogSubmit(interactType, interactTypeDetail) {
      let row = this.invoiceDetails.selectRow
      let _this = this
      if (row) {
        _this
            .$confirm(
                `发票号码 [ ${row.invoiceNumber} ] 将执行发票交付, 是否继续?`,
                '提示',
                {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning',
                  center: true,
                }
            )
            .then(() => {
              _this.$refs.invoiceDeliveryDialogRef.loading = true
              console.log(row)
              invoiceDelivery({
                invoiceReqFlowNo: row.invoiceReqFlowNo,
                interactType: interactType,
                interactTypeDetail: interactTypeDetail,
              })
                  .then((val) => {
                    _this.$refs.invoiceDeliveryDialogRef.visible = false
                  })
                  .catch((err) => {
                    _this.$message.error(err)
                  })
                  .finally(() => {
                    _this.$refs.invoiceDeliveryDialogRef.loading = false
                  })
            })
            .catch(() => {
              // 无取消操作
            })
      } else {
        console.log('没有选中数据！')
      }
    },
  },
}
</script>

<style scoped>
.Row {
  display: table;
  width: 100%; /*Optional*/
  table-layout: fixed; /*Optional*/
  /* border-spacing: 10px; Optional */
}

.Column {
  display: table-cell;
  /* background-color: red; Optional */
}
</style>
