<template>
  <div class="app-container">
    <el-card>
      <!-- 搜索工作栏 -->
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="98px"
        ><div class="filter-box">
          <div class="filter-lf">
            <el-form-item label="发票号码" prop="invoiceNum">
              <el-input
                v-model="queryParams.invoiceNum"
                placeholder="请输入发票号码"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="发票代码" prop="invoiceCode">
              <el-input
                v-model="queryParams.invoiceCode"
                placeholder="请输入发票代码"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="销方名称" prop="sellerName">
              <el-input
                v-model="queryParams.sellerName"
                placeholder="请输入销方名称"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="销方税号" prop="sellerRegisterNum">
              <el-input
                v-model="queryParams.sellerRegisterNum"
                placeholder="请输入销方税号"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="购方名称" prop="purchaserName">
              <el-input
                v-model="queryParams.purchaserName"
                placeholder="请输入购方名称"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="购方税号" prop="purchaserRegisterNum">
              <el-input
                v-model="queryParams.purchaserRegisterNum"
                placeholder="请输入购方税号"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="开票日期" prop="invoiceDate">
              <el-date-picker
                v-model="queryParams.invoiceDate"
                style="width: 240px"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                @click="handleQuery"
                >搜索</el-button
              >
              <el-button icon="el-icon-refresh" @click="resetQuery"
                >重置</el-button
              >
            </el-form-item>
            <el-row style="display: inline-block">
              <el-button round type="primary" @click="handleOneMonth"
                >一个月内</el-button
              >
              <el-button round type="primary" @click="handleHalfYear"
                >半年内</el-button
              >
              <el-button round type="primary" @click="handleOneYear"
                >一年内</el-button
              >
            </el-row>
          </div>
        </div>
      </el-form>
      <!-- 操作工具栏 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['accounting:invoices:create']"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            >删除</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            :loading="exportLoading"
            v-hasPermi="['accounting:invoices:export']"
            >导出</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleImport"
            v-hasPermi="['accounting:invoices:export']"
            >导入</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleDownloadData"
            v-hasPermi="['accounting:invoices:export']"
            >下载元数据</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-document"
            size="mini"
            :disabled="multiple"
            @click="handleGLPZ"
            >关联凭证</el-button
          >
        </el-col>
        <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>
      <!-- tab栏列表切换 -->
      <el-tabs v-model="accountingType" @tab-click="handleClick" type="card">
        <el-tab-pane label="进项" name="in"></el-tab-pane>
        <el-tab-pane label="销项" name="out"></el-tab-pane>
      </el-tabs>
      <!-- 列表 -->
      <el-table
        v-loading="loading"
        :data="list"
        stripe
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="发票代码" align="center" prop="invoiceCode" />
        <el-table-column label="发票号码" align="center" prop="invoiceNum" />
        <el-table-column label="大写金额" align="center" prop="amountinWords" />
        <el-table-column label="合计税额" align="center" prop="totalTax" />
        <el-table-column label="税率" align="center" prop="taxRate" />
        <el-table-column label="金额" align="center" prop="totalAmount" />
        <el-table-column label="税额" align="center" prop="commodityTax" />
        <el-table-column
          label="价税合计"
          align="center"
          prop="commodityAmount"
        />
        <el-table-column
          label="小写价税合计"
          align="center"
          prop="amountinFiguers"
        />
        <el-table-column
          label="销方名称"
          align="center"
          prop="sellerName"
          width="260"
        />
        <el-table-column
          label="销方税号"
          align="center"
          prop="sellerRegisterNum"
          width="200"
        />
        <el-table-column
          label="销方开户行及账号"
          align="center"
          prop="sellerBank"
          width="380"
        />
        <el-table-column
          label="销方地址电话"
          align="center"
          prop="sellerAddress"
          width="480"
        />
        <el-table-column
          label="购方名称"
          align="center"
          prop="purchaserName"
          width="240"
        />
        <el-table-column
          label="购方税号"
          align="center"
          prop="purchaserRegisterNum"
          width="200"
        />
        <el-table-column
          label="购方开户行及账号"
          align="center"
          prop="purchaserBank"
          width="460"
        />
        <el-table-column
          label="购方地址电话"
          align="center"
          prop="purchaserAddress"
          width="460"
        />
        <el-table-column label="发票种类" align="center" prop="invoiceType">
        </el-table-column>
        <el-table-column label="开票人" align="center" prop="foteDrawer" />
        <el-table-column label="收款人" align="center" prop="payee" />
        <el-table-column label="复核人" align="center" prop="checker" />
        <el-table-column label="校验码" align="center" prop="checkCode" />
        <el-table-column label="发票状态" align="center" prop="invoiceState">
          <template v-slot="scope">
            <dict-tag
              :type="DICT_TYPE.ACCOUNTING_INVOICES_STATUS"
              :value="scope.row.invoiceState"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="开票日期"
          align="center"
          prop="invoiceDate"
          width="100"
        >
          <template v-slot="scope">
            <span>{{ parseTime2(scope.row.invoiceDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="作废日期"
          align="center"
          prop="printNum"
          width="100"
        >
          <template v-slot="scope">
            <span>{{ parseTime2(scope.row.printNum) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="进销项" align="center" prop="inoutMark">
          <template v-slot="scope">
            <dict-tag
              :type="DICT_TYPE.ACCOUNTING_INVOICES_TYPE"
              :value="scope.row.inoutMark"
            />
          </template>
        </el-table-column>
        <el-table-column label="查重" align="center" prop="duplicateMark">
          <template v-slot="scope">
            <dict-tag
              :type="DICT_TYPE.ACCOUNTING_INVOICES_DUPLICATE"
              :value="scope.row.duplicateMark"
            />
          </template>
        </el-table-column>
        <el-table-column label="二维码查验" align="center" prop="qrCheckCode">
          <template v-slot="scope">
            <dict-tag
              :type="DICT_TYPE.ACCOUNTING_INVOICES_CODE_STATUS"
              :value="scope.row.qrCheckCode"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          width="180"
        >
          <template v-slot="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          fixed="right"
          width="180px"
        >
          <template v-slot="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              v-if="scope.row.fileUrl"
              @click="handleViewFJ(scope.row)"
              >查看附件
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row)"
              >查看
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['accounting:invoices:update']"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['accounting:invoices:delete']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNo"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 对话框(添加 / 修改) -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1300px"
      append-to-body
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="140px"
        :disabled="this.title === '查看发票'"
      >
        <el-row v-if="optType != 'view'">
          <el-col :span="8">
            <UploadInvoice
              :files="fileList"
              @onConfirm="handleImg"
              @onScan="handleScan"
            />
          </el-col>
        </el-row>
        <el-divider>发票信息</el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="发票代码" prop="invoiceCode">
              <el-input
                v-model="form.invoiceCode"
                placeholder="请输入发票代码"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发票号码" prop="invoiceNum">
              <el-input
                v-model="form.invoiceNum"
                placeholder="请输入发票号码"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="大写金额" prop="amountinWords">
              <el-input
                v-model="form.amountinWords"
                placeholder="请输入大写金额"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="合计税额" prop="totalTax">
              <el-input v-model="form.totalTax" placeholder="请输入合计税额" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="税率" prop="taxRate">
              <el-input v-model="form.taxRate" placeholder="请输入税率" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="金额" prop="totalAmount">
              <el-input v-model="form.totalAmount" placeholder="请输入金额" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="税额" prop="commodityTax">
              <el-input v-model="form.commodityTax" placeholder="请输入税额" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="价税合计" prop="commodityAmount">
              <el-input
                v-model="form.commodityAmount"
                placeholder="请输入价税合计"
              />
            </el-form-item> </el-col
        ></el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="小写价税合计" prop="amountinFiguers">
              <el-input
                v-model="form.amountinFiguers"
                placeholder="请输入小写价税合计"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开票人" prop="foteDrawer">
              <el-input v-model="form.foteDrawer" placeholder="请输入开票人" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="销方地址电话" prop="sellerAddress">
              <el-input
                v-model="form.sellerAddress"
                placeholder="请输入销方地址电话"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="销方纳税识别号" prop="sellerRegisterNum">
              <el-input
                v-model="form.sellerRegisterNum"
                placeholder="请输入销方纳税识别号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="销方开户行及账号" prop="sellerBank">
              <el-input
                v-model="form.sellerBank"
                placeholder="请输入销方开户行及账号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="校验码" prop="checkCode">
              <el-input v-model="form.checkCode" placeholder="请输入校验码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="开票日期" prop="invoiceDate">
              <el-date-picker
                clearable
                v-model="form.invoiceDate"
                type="date"
                value-format="timestamp"
                placeholder="选择开票日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="购方税号" prop="purchaserRegisterNum">
              <el-input
                v-model="form.purchaserRegisterNum"
                placeholder="请输入购方税号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="购方开户行及账号" prop="purchaserBank">
              <el-input
                v-model="form.purchaserBank"
                placeholder="请输入购方开户行及账号"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="复核人" prop="checker">
              <el-input v-model="form.checker" placeholder="请输入复核人" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="购方公司名" prop="purchaserName">
              <el-input
                v-model="form.purchaserName"
                placeholder="请输入购方公司名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="购方地址电话" prop="purchaserAddress">
              <el-input
                v-model="form.purchaserAddress"
                placeholder="请输入购方地址电话"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="发票种类" prop="invoiceType">
              <el-input
                v-model="form.invoiceType"
                placeholder="请输入发票种类"
              />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="收款人" prop="payee">
              <el-input v-model="form.payee" placeholder="请输入收款人" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="销方名称" prop="sellerName">
              <el-input
                v-model="form.sellerName"
                placeholder="请输入销方名称"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="二维码查验" prop="qrCheckCode">
              <el-select v-model="form.qrCheckCode" placeholder="请选择">
                <el-option
                  v-for="item in qrCheckCodeOptions"
                  :key="item.id"
                  :value="item.value"
                  :label="item.label"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发票状态" prop="invoiceState">
              <el-select
                v-model="form.invoiceState"
                placeholder="请选择发票状态"
              >
                <el-option
                  v-for="item in invoiceStateOptions"
                  :key="item.id"
                  :value="item.value"
                  :label="item.label"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.invoiceState == 0">
            <el-form-item label="作废日期" prop="printNum">
              <el-date-picker
                clearable
                v-model="form.printNum"
                type="date"
                value-format="timestamp"
                placeholder="选择作废日期"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="进销项" prop="inoutMark">
              <el-select v-model="form.inoutMark" placeholder="请选择">
                <el-option
                  v-for="item in inOrOutOptions"
                  :key="item.id"
                  :value="item.value"
                  :label="item.label"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
            <el-form-item label="查重" prop="duplicateMark">
              <el-select v-model="form.duplicateMark" placeholder="请选择">
                <el-option
                  v-for="item in invoicesDuplicateOptions"
                  :key="item.id"
                  :value="item.value"
                  :label="item.label"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="8">
            <el-form-item label="验真" prop="checkTrue">
              <el-select v-model="form.checkTrue" placeholder="请选择">
                <el-option
                  v-for="item in invoicesCheckOptions"
                  :key="item.id"
                  :value="item.value"
                  :label="item.label"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="optType != 'view'"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 物料导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        name="multipartFile"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 密码输入框-->
    <el-dialog
      title="输入密码"
      :visible.sync="open1"
      width="800px"
      append-to-body
    >
      <el-form
        ref="queryForm"
        :model="queryParams"
        :rules="rules"
        label-width="140px"
      >
        <el-row>
          <el-col :span="14">
            <el-form-item label="密码" prop="inputPassword">
              <el-input
                v-model="queryParams.inputPassword"
                placeholder="请输入密码"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm1">确 定</el-button>
        <el-button @click="cancel1">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 会计凭证选择框-->
    <el-dialog
      title="关联凭证"
      :visible.sync="open2"
      width="800px"
      append-to-body
    >
      <el-form ref="PZform" :model="PZform" :rules="rules" label-width="140px">
        <el-row>
          <el-col :span="14">
            <el-form-item label="会计凭证">
              <el-input
                v-model="PZform.voucherNum"
                placeholder="请选择凭证"
                readonly
              >
                <el-button
                  slot="append"
                  @click="handleSelectVoucher"
                  icon="el-icon-search"
                  style="
                    border-color: #46a6ff;
                    background-color: #46a6ff;
                    color: white;
                  "
                ></el-button>
              </el-input>
              <VoucherSelect
                ref="VoucherSelect"
                @onSelected="onVoucherSelected"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm2">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  createInvoices,
  updateInvoices,
  deleteInvoices,
  getInvoices,
  getInvoicesPage,
  exportInvoicesExcel,
  outTemplate,
  downloadXml,
  getInvoicesPageTime,
  updateArrayInvoices,
} from "@/api/accounting/invoices";
import { getVoucherPage } from "@/api/accounting/voucher";
import { listData } from "@/api/system/dict/data";
import { getAccessToken } from "@/utils/auth";
import VoucherSelect from "@/components/VoucherSelect/single.vue";

export default {
  name: "Invoices",
  components: {
    UploadInvoice: () => import("@/components/UploadInvoice"),
    VoucherSelect,
  },
  data() {
    return {
      optType: undefined,
      // 遮罩层
      loading: true,
      // 非多个禁用
      multiple: true,
      // 导出遮罩层
      exportLoading: false,
      downloadLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 发票列表
      list: [],
      // 弹出层标题
      title: "",
      // 选中数组
      ids: [],
      // 是否显示弹出层
      open: false,
      open1: false,
      open2: false,
      accountingType: "in",
      fileList: [],
      time: null,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        voucherId: null,
        invoiceCode: null,
        invoiceNum: null,
        amountinWords: null,
        price: null,
        totalTax: null,
        taxRate: null,
        totalAmount: null,
        commodityTax: null,
        commodityAmount: null,
        amountinFiguers: null,
        foteDrawer: null,
        sellerAddress: null,
        commodityNum: null,
        sellerRegisterNum: null,
        machineCode: null,
        remarks: null,
        sellerBank: null,
        checkCode: null,
        invoiceDate: [],
        purchaserRegisterNum: null,
        invoiceTypeOrg: null,
        password: null,
        agent: null,
        purchaserBank: null,
        checker: null,
        city: null,
        purchaserName: null,
        commodityType: null,
        province: null,
        invoiceType: null,
        sheetNum: null,
        purchaserAddress: null,
        commodityUnit: null,
        payee: null,
        commodityName: null,
        sellerName: null,
        invoiceCheck: null,
        invoiceSeal: null,
        invoiceQrcode: null,
        invoiceQrnum: null,
        qrCheckCode: null,
        invoiceState: null,
        printNum: null,
        inoutMark: 0,
        invalidMark: null,
        duplicateMark: null,
        checkTrue: null,
        encrypt: null,
        createBy: null,
        createTime: [],
        recordId: null,
        companyId: null,
        company: null,
        deptId: null,
        deptName: null,
        userId: null,
        remark: null,
        fileUrl: null,
        inputPassword: null,
      },
      // 表单参数
      form: {},
      PZform: {
        voucherId: undefined,
        voucherNum: undefined,
      },
      uploadUrl:
        process.env.VUE_APP_BASE_API +
        "/admin-api/accounting/invoices/identify", // 上传地址地址
      headers: { Authorization: "Bearer " + getAccessToken() }, // 设置上传的请求头部
      fileAccept: ".jpeg, .bmp, .jpg, .png, .gif, .pdf, .ofd,",
      // 表单校验
      rules: {
        invoiceCode: [
          { required: true, message: "发票代码不能为空", trigger: "blur" },
        ],
        invoiceNum: [
          { required: true, message: "发票号码不能为空", trigger: "blur" },
        ],
        inputPassword: [
          { required: true, message: "密码不能为空", trigger: "blur" },
        ],
        voucherId: [{ required: true, message: "请选择凭证", trigger: "blur" }],
        inoutMark: [
          { required: true, message: "请选择进销项", trigger: "blur" },
        ],
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getAccessToken() },
        // 上传的地址
        url:
          process.env.VUE_APP_BASE_API +
          "/admin-api/accounting/invoices/inTemplate",
      },
      invoicesCheckOptions: [], //发票查验
      invoicesDuplicateOptions: [], //发票查重
      invoiceTypeOptions: [], //发票类型
      invoiceStateOptions: [], //发票状态
      inOrOutOptions: [], //发票进销项
      qrCheckCodeOptions: [], //发票二维码查验状态
      kjpzOptions: [], //会计凭证
    };
  },
  created() {
    this.getList();
    this.getKJPZ();
    this.handleInitList();
  },

  methods: {
    // 上传文件事件
    handleImg(list) {
      this.fileList = list;
      this.reset();
    },
    handleScan(form) {
      if (form.duplicateMark == 1) {
        this.$message.error("该发票重复");
      }
      const num = form.duplicateMark.toString();
      this.form = form;
      this.form.duplicateMark = num;
    },
    /**
     * 文件预览
     * @param fileUrl
     */
    openLink(fileUrl) {
      const url =
        process.env.VUE_APP_ONLINE_API +
        `/onlinePreview?url=${encodeURIComponent(this.base64Encode(fileUrl))}`;
      window.open(url);
    },
    /** 查看附件按钮操作 */
    handleViewFJ(row) {
      this.openLink(row.fileUrl);
    },
    handleClick(tab) {
      console.log(tab.name);
      if (tab.name == "in") {
        this.queryParams.inoutMark = 0;
      } else {
        this.queryParams.inoutMark = 1;
      }
      this.getList();
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getInvoicesPage(this.queryParams).then((response) => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 查询列表2 */
    getList2() {
      this.loading = true;
      // 执行查询
      getInvoicesPageTime({ months: this.time }).then((response) => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    handleOneMonth() {
      this.time = 1;
      this.getList2();
    },
    handleHalfYear() {
      this.time = 6;
      this.getList2();
    },
    handleOneYear() {
      this.time = 12;
      this.getList2();
    },
    //获取会计凭证
    getKJPZ() {
      getVoucherPage().then((res) => {
        this.kjpzOptions = res.data.list || [];
      });
    },
    //获取字典数据
    handleInitList() {
      // 获取发票类型
      listData({
        pageNo: 1,
        pageSize: 100,
        dictType: "bs_invoice_type",
      }).then((res) => {
        this.invoiceTypeOptions = res.data.list || [];
      });
      // 获取发票进销项
      listData({
        pageNo: 1,
        pageSize: 100,
        dictType: "accounting_invoices_type",
      }).then((res) => {
        this.inOrOutOptions = res.data.list || [];
      });
      // 获取发票查验
      listData({
        pageNo: 1,
        pageSize: 100,
        dictType: "accounting_invoices_check",
      }).then((res) => {
        this.invoicesCheckOptions = res.data.list || [];
      });
      // 获取发票查重
      listData({
        pageNo: 1,
        pageSize: 100,
        dictType: "accounting_invoices_duplicate",
      }).then((res) => {
        this.invoicesDuplicateOptions = res.data.list || [];
      });
      // 获取发票状态
      listData({
        pageNo: 1,
        pageSize: 100,
        dictType: "accounting_invoices_status",
      }).then((res) => {
        this.invoiceStateOptions = res.data.list || [];
      });
      // 获取发票状态
      listData({
        pageNo: 1,
        pageSize: 100,
        dictType: "accounting_invoices_code_status",
      }).then((res) => {
        this.qrCheckCodeOptions = res.data.list || [];
      });
    },
    // 上传成功的函数
    handleSuccess(res) {
      const num = res.data.duplicateMark.toString();
      this.form = res.data;
      this.form.duplicateMark = num;
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 取消按钮 */
    cancel1() {
      this.open1 = false;
    },
    /** 取消按钮 */
    cancel2() {
      this.open2 = false;
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        voucherId: undefined,
        invoiceCode: undefined,
        invoiceNum: undefined,
        amountinWords: undefined,
        price: undefined,
        totalTax: undefined,
        taxRate: undefined,
        totalAmount: undefined,
        commodityTax: undefined,
        commodityAmount: undefined,
        amountinFiguers: undefined,
        foteDrawer: undefined,
        sellerAddress: undefined,
        commodityNum: undefined,
        sellerRegisterNum: undefined,
        machineCode: undefined,
        remarks: undefined,
        sellerBank: undefined,
        checkCode: undefined,
        invoiceDate: undefined,
        purchaserRegisterNum: undefined,
        invoiceTypeOrg: undefined,
        password: undefined,
        agent: undefined,
        purchaserBank: undefined,
        checker: undefined,
        city: undefined,
        purchaserName: undefined,
        commodityType: undefined,
        province: undefined,
        invoiceType: undefined,
        sheetNum: undefined,
        purchaserAddress: undefined,
        commodityUnit: undefined,
        payee: undefined,
        commodityName: undefined,
        sellerName: undefined,
        invoiceCheck: undefined,
        invoiceSeal: undefined,
        invoiceQrcode: undefined,
        invoiceQrnum: undefined,
        qrCheckCode: undefined,
        invoiceState: undefined,
        printNum: undefined,
        inoutMark: undefined,
        invalidMark: undefined,
        duplicateMark: undefined,
        checkTrue: undefined,
        encrypt: undefined,
        createBy: undefined,
        recordId: undefined,
        companyId: undefined,
        company: undefined,
        deptId: undefined,
        deptName: undefined,
        userId: undefined,
        remark: undefined,
        fileUrl: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      console.log(selection);
      this.ids = selection.map((item) => item.id);
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加发票";
      this.fileList = [];
      this.optType = "add";
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      this.optType = "view";
      const id = row.id;
      getInvoices(id).then((response) => {
        this.form = response.data;
        if (response.data.invoiceState != null) {
          const num1 = response.data.invoiceState.toString();
          this.form.invoiceState = num1;
        }
        if (response.data.inoutMark != null) {
          const num2 = response.data.inoutMark.toString();
          this.form.inoutMark = num2;
        }
        if (response.data.duplicateMark != null) {
          const num3 = response.data.duplicateMark.toString();
          this.form.duplicateMark = num3;
        }
        if (response.data.qrCheckCode != null) {
          const num4 = response.data.qrCheckCode.toString();
          this.form.qrCheckCode = num4;
        }
        this.open = true;
        this.title = "查看发票";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      this.optType = "edit";
      getInvoices(id).then((response) => {
        this.form = response.data;
        if (response.data.invoiceState != null) {
          const num1 = response.data.invoiceState.toString();
          this.form.invoiceState = num1;
        }
        if (response.data.inoutMark != null) {
          const num2 = response.data.inoutMark.toString();
          this.form.inoutMark = num2;
        }
        if (response.data.duplicateMark != null) {
          const num3 = response.data.duplicateMark.toString();
          this.form.duplicateMark = num3;
        }
        if (response.data.qrCheckCode != null) {
          const num4 = response.data.qrCheckCode.toString();
          this.form.qrCheckCode = num4;
        }
        this.open = true;
        this.title = "修改发票";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          updateInvoices(this.form).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createInvoices(this.form).then((response) => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除发票编号为"' + id + '"的数据项?')
        .then(function () {
          return deleteInvoices(id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    //关联凭证
    handleGLPZ() {
      this.open2 = true;
      this.PZform = {
        voucherId: undefined,
        voucherNum: undefined,
      };
    },
    submitForm2() {
      this.$refs["PZform"].validate((valid) => {
        if (!valid) {
          return;
        }
        const data = { id: this.ids, voucherId: this.PZform.voucherId };
        updateArrayInvoices(data).then((response) => {
          this.$modal.msgSuccess("关联成功");
          this.open2 = false;
          this.multiple = true;
          this.getList();
        });
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = { ...this.queryParams };
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal
        .confirm("是否确认导出所有发票数据项?")
        .then(() => {
          this.exportLoading = true;
          return exportInvoicesExcel(params);
        })
        .then((response) => {
          this.$download.excel(response, "发票.xls");
          this.exportLoading = false;
        })
        .catch(() => {});
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "发票导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      outTemplate().then((response) => {
        this.$download.excel(response, "发票模板.xls");
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    //下载元数据
    handleDownloadData() {
      this.open1 = true;
      this.queryParams.inputPassword = null;
    },
    submitForm1() {
      this.$refs["queryForm"].validate((valid) => {
        if (!valid) {
          return;
        }
        // 处理查询参数
        let params = { ...this.queryParams };
        downloadXml(params)
          .then((response) => {
            console.log(response.size);
            if (response.size == 39) {
              this.$modal.msgError("密码错误");
              return false;
            } else {
              this.$download.excel(response, "发票元数据.xml");
              this.open1 = false;
            }
          })
          .catch(() => {});
      });
    },
    handleSelectVoucher() {
      this.$refs.VoucherSelect.showFlag = true;
    },
    onVoucherSelected(obj) {
      console.log(obj);
      if (obj != undefined && obj != null) {
        this.PZform.voucherId = obj.id;
        this.PZform.voucherNum = obj.voucherNum;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.el-divider__text.is-center {
  font-weight: bold;
  font-size: large;
}
@import "@/assets/styles/header/index.scss";
@import "@/assets/styles/common/index.scss";
</style>
