<template>
  <div class="app-container">
    <div slot="header" class="card-title">{{ $t("收款单") }}</div>
    <!-- 搜索工作栏 -->
    <el-card v-show="showSearch" class="card">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="100px" class="card">
        <!-- <el-row :span="24"> -->
        <el-form-item :label="$t('收款单号')">
          <el-input style="max-width: 188px" v-model.trim="queryParams.receiptNo" :placeholder="$t('请输入收款单号')" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item :label="$t('客户名称')">
          <el-select multiple :remote-method="customerDropDownFn" remote clearable filterable v-model="queryParams.customerIdList" :placeholder="$t('请输入关键词')">
            <el-option v-for="(item, index) in customeList" :key="item.id" :value="item.id" :label="item.name"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('状态')">
          <dict-selector multiple :type="DICT_TYPE.ECW_RECEIPT_STATE" v-model="queryParams.stateList" clearable />
        </el-form-item>
        <el-form-item :label="$t('业务员')">
          <el-select multiple v-model="queryParams.salesmanIdList" :placeholder="$t('请选择业务员')" clearable>
            <el-option v-for="item in creatorData" :key="item.id" :label="item.nickname" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('开票状态')">
          <dict-selector multiple :type="DICT_TYPE.INVOICING_STATUS" v-model="queryParams.invoicingStatus" clearable />
        </el-form-item>
        <el-form-item :label="$t('明细状态')">
          <dict-selector multiple :type="DICT_TYPE.RECEIPT_DETAIL_STATUS" v-model="queryParams.receiptItemStatus" clearable />
        </el-form-item>
        <el-form-item :label="$t('开票资料状态')">
          <dict-selector multiple :type="DICT_TYPE.INVOICE_DATA_STATUS" v-model="queryParams.invoiceDataStatus" clearable />
        </el-form-item>
        <!-- </el-row> -->
        <el-form-item :label="$t('编号')">
          <el-input style="max-width: 188px" v-model.trim="queryParams.numberNo" :placeholder="$t('订单号和提单号,自编号')" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <!-- <el-row :span="24"> -->
        <!-- <el-col style="width: 592px"> -->
        <el-form-item :label="$t('创建时间')">
          <el-date-picker v-model="dateFilter" type="datetimerange" range-separator="-" value-format="yyyy-MM-dd HH:mm:ss" :start-placeholder="$t('请选择日期')" :end-placeholder="$t('请选择日期')"> </el-date-picker>
        </el-form-item>
        <!-- </el-col> -->

        <!-- </el-row> -->
        <el-row :span="24">
          <el-col style="width: 592px">
            <el-form-item>
              <el-button type="primary" @click="handleQuery">{{ $t("查找") }}</el-button>
              <!--lanbm 2024-05-29 添加的批处理功能按钮-->
              <el-button type="primary" @click="handleQuery2">{{ $t("批量反审核") }}</el-button>
              <el-button type="primary" @click="handleQuery3">{{ $t("批量反核销") }}</el-button>
              <el-button type="primary" @click="handleQuery4">{{ $t("批量核销") }}</el-button>
              <!--lanbm 2024-05-29 添加的批处理功能按钮-->
              <!-- 财务2.2-->
              <el-button @click="handleShowFileUploadDialog" type="primary" v-hasPermi="['ecw:voucher:importBankCollectionInfo']">{{ $t("导入银行收款信息") }}</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-table v-loading="loadings" :data="list" @selection-change="handleSelectionChange" border class="card">
      <el-table-column type="selection" width="55" align="center" fixed="left"> </el-table-column>
      <el-table-column :label="$t('序号')" align="center" fixed="left" prop="id" type="index">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <!--lanbm 2024-06-06 添加链接-->
      <el-table-column :label="$t('收款单号')" width="150" fixed="left" align="center" prop="receiptNo">
        <template slot-scope="scope">
          <span style="color: #1890ff" @click="verificationCancelClick(scope.row)">{{ scope.row.receiptNo }}</span>
        </template>
      </el-table-column>
      <!--订单号，提单号，lanbm 2024-05-29 add-->
      <!-- 财务v2.2 新增收款单对应多订单展示处理 -->
      <el-table-column :label="$t('订单号/提单号')" fixed="left" width="230" align="center" prop="orderNo">
        <template slot-scope="{ row }">
          <div v-for="item in row.orderInfoList" :key="item.orderId">
            <router-link :to="`/order/detail?orderId=${item.orderId}`" class="link-type"> {{ item.orderNo }}/{{ item.tidanNo }} </router-link>
          </div>
          <!-- <span style="color: #1890ff" @click="paymentDetail2(scope.row)">{{ scope.row.orderNo }}</span> -->
        </template>
      </el-table-column>
      <!-- <el-table-column :label="$t('提单号')" align="center" prop="tidanNo" /> -->
      <!-- <template slot-scope="scope"> -->
      <!-- <span style="color: #1890ff;" @click="verificationCancelClick(scope.row)">{{scope.row.receiptNo}}</span> -->
      <!-- </template> -->
      <!-- </el-table-column> -->
      <el-table-column :label="$t('客户名称')" align="center" prop="customerName" />
      <el-table-column :label="$t('创建日期')" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('实收日期')" align="center" prop="payedAt">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.payedAt, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('业务员')" align="center" prop="salesmanName" />
      <el-table-column :label="$t('状态')" align="center">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.ECW_RECEIPT_STATE" :value="scope.row.state" />
          <span v-if="scope.row.remark && (scope.row.state == 1 || scope.row.state == 3 || scope.row.state == 8)" :title="scope.row.remark"><i class="el-icon-question"></i></span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('应收')" align="center" prop="ysShow"> </el-table-column>
      <el-table-column :label="$t('实收')" align="center" prop="ssShow"> </el-table-column>
      <el-table-column :label="$t('核销比例')" align="center" prop="hxBiLi"> </el-table-column>
      <el-table-column :label="$t('是否开票')" align="center">
        <template slot-scope="scope">
          {{ scope.row.openInvoice === 0 ? $t("否") : $t("是") }}
        </template>
      </el-table-column>
      <!--lanbm 2024-05-14 add-->
      <el-table-column :label="$t('明细状态')" align="center" prop="mxStatus">
        <template slot-scope="{ row }">
          <dict-tag :type="DICT_TYPE.RECEIPT_DETAIL_STATUS" :value="row.receiptItemStatus" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('开票状态')" align="center">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.INVOICING_STATUS" :value="scope.row.invoicingStatus" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('开票资料状态')" align="center">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.INVOICE_DATA_STATUS" :value="scope.row.invoiceDataStatus" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('操作')" width="300" fixed="right" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" v-hasPermi="['ecw:voucher:see']" @click="verificationCancelClick(scope.row)">{{ $t("查看") }}</el-button>
          <el-button v-if="scope.row.state === 0" size="mini" type="text" v-hasPermi="['ecw:voucher:edit']" @click="handleAdd(scope.row.id)">{{ $t("编辑") }}</el-button>
          <!-- <el-button
            v-if="scope.row.state == "
            size="mini"
            type="text"
            @click="verificationClick(scope.row)"
            >{{ $t('核销') }}</el-button
          > -->
          <el-button v-if="scope.row.state == 4 || scope.row.state == 5 || scope.row.state == 6" size="mini" type="text" v-hasPermi="['ecw:voucher:cancelWriteOff']" @click="writeOffShow(2, scope.$index)">{{ $t("反核销") }}</el-button>
          <el-button v-if="scope.row.state == 1" size="mini" type="text" v-hasPermi="['ecw:voucher:deApproval']" @click="writeOffShow(1, scope.$index)">{{ $t("反审核") }}</el-button>
          <el-button v-if="scope.row.state == 7" size="mini" type="text" v-hasPermi="['ecw:vocher:cancelAppoval']" @click="cancelClick(scope.$index, 1)">{{ $t("取消审核") }}</el-button>
          <el-button v-if="scope.row.state == 11" size="mini" type="text" v-hasPermi="['ecw:vocher:cancelWriteOfflNo']" @click="cancelClick(scope.$index, 3)">{{ $t("取消反核销审核") }}</el-button>
          <el-button v-if="scope.row.state == 10" size="mini" type="text" v-hasPermi="['ecw:vocher:cancelWriteOffAll']" @click="cancelClick(scope.$index, 4)">{{ $t("取消全部核销审核") }}</el-button>
          <el-button v-if="scope.row.state == 9" size="mini" type="text" v-hasPermi="['ecw:vocher:cancelAppovalNo']" @click="cancelClick(scope.$index, 2)">{{ $t("取消反审核") }}</el-button>
          <el-button size="mini" type="text" v-if="scope.row.state == 9 || scope.row.state == 7 || scope.row.state == 11 || scope.row.state == 10" v-hasPermi="['ecw:voucher:cancelWriteOff']" @click="$router.push(`/bpm/process-instance/detail?id=` + scope.row.bmpId)">{{ $t("审核详情") }}</el-button>
          <el-button v-if="scope.row.state == 5" size="mini" type="text" v-hasPermi="['ecw:voucher:ballot']" @click="openInvoice(scope.row.id)">{{ $t("开票") }}</el-button>
          <el-button v-if="scope.row.state == 1 || scope.row.state == 2 || scope.row.state == 3" v-hasPermi="['ecw:voucher:payment']" size="mini" type="text" @click="verificationCancelClick(scope.row)">{{ $t("收款") }}</el-button>
          <el-button v-if="scope.row.state == 0" size="mini" type="text" v-hasPermi="['ecw:voucher:delete']" @click="deleteClick(scope.row)">{{ $t("删除") }}</el-button>
          <el-button v-if="scope.row.state != 0 && scope.row.state != 7 && scope.row.state != 11 && scope.row.state != 8 && scope.row.state != 9" size="mini" type="text" @click="toprint(scope.row.id)" v-hasPermi="['ecw:voucher:print']">{{ $t("打印") }}</el-button>
          <el-button v-if="scope.row.state != 0 && scope.row.state != 7 && scope.row.state != 11 && scope.row.state != 8 && scope.row.state != 9" size="mini" type="text" v-hasPermi="['ecw:voucher:derive']" @click="exportReceipt(scope.row.id)">{{ $t("导出账单") }}</el-button>

          <!-- 财务2.2新增 5 个按钮-->
          <!-- 待收款==1  待提交 ==2 已部分核销==3 -->
          <el-button size="mini" v-if="scope.row.state == 1 || scope.row.state == 2 || scope.row.state == 3" v-hasPermi="['ecw:voucher:editReceipt']" @click="handleAdd(scope.row.id)" type="text"> {{ $t("修改收款单") }}</el-button>
          <!-- 当收款单状态≠草稿0且≠审核中7且≠审批拒绝8，开票状态=已取消2||不开票 3，按钮显示且可点击，跳转申请开票页面 -->
          <el-button size="mini" v-if="scope.row.state != 0 && scope.row.state != 7 && scope.row.state != 8 && (scope.row.invoicingStatus == 2 || scope.row.invoicingStatus == 3)" v-hasPermi="['ecw:voucher:applyInvoice']" type="text" @click="goInvoiceOperate({ id: scope.row.id, key: 'create' })">{{ $t("申请开票") }}</el-button>
          <!-- 开票状态=待开票0 -->
          <el-button size="mini" v-hasPermi="['ecw:voucher:editInvoiceApplication']" v-if="scope.row.invoicingStatus === 0" type="text" @click="goInvoiceOperate({ id: scope.row.invoiceId, key: 'edit' })">{{ $t("修改开票申请") }}</el-button>
          <!-- 当收款单状态≠草稿0且开票状态=待开票0， -->
          <el-button v-if="scope.row.state != 0 && scope.row.invoicingStatus === 0" size="mini" v-hasPermi="['ecw:voucher:cancalInvoicing']" type="text" @click="goInvoiceOperate({ id: scope.row.invoiceId, key: 'cancel' })">{{ $t("取消开票") }}</el-button>
          <!-- 当开票状态=已开票才显示，跳转开票信息查看页面  -->
          <el-button v-if="scope.row.invoicingStatus === 1" @click="goInvoiceOperate({ id: scope.row.invoiceId, key: 'view' })" size="mini" v-hasPermi="['ecw:voucher:invoiceInformation']" type="text">{{ $t("开票信息") }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.rows" @pagination="getList" />
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="$t('导出账单')" :visible.sync="open" width="500px" style="margin-top: 20vh !important" append-to-body>
      <!-- <div slot="title" class="card-title" style='border-bottom: 2px solid #f8f8f8;'>
            <span>{{ $t('导出账单') }}</span>
            <i class="el-icon-close" @click="cancel"></i>
          </div> -->
      <div class="dialog-footer">
        <el-button type="primary" style="width: 130px" @click="submitForm(1)" v-loading="downloading">{{ $t("国内账单") }}</el-button>
        <el-button plain v-loading="downloading" type="primary" style="width: 130px; margin: 0" @click="submitForm(2)">Debite note</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="writeOffType == 1 ? $t('收款单反审核') : $t('收款单反核销')" :visible.sync="dialogVisible" width="30%">
      <div class="cancel_content">
        <span>{{ $t("申请理由") }}</span>
        <el-input type="textarea" :rows="6" v-model="reason" :placeholder="$t('请输入理由')"></el-input>
      </div>
      <span slot="footer" class="dialog-footers">
        <el-button v-if="writeOffType == 1" type="primary" @click="writeOffClick()">{{ $t("提交反审核") }}</el-button>
        <el-button v-else type="primary" @click="writeOffClick()">{{ $t("提交反核销") }}</el-button>
        <el-button @click="dialogVisible = false">{{ $t("取消") }}</el-button>
      </span>
    </el-dialog>
    <el-dialog :title="cancelTitle" :visible.sync="cancelShow" width="30%">
      <div class="cancel_content">
        <span>{{ $t("申请理由") }}</span>
        <el-input type="textarea" :rows="6" v-model="cancelReason" :placeholder="$t('请输入取消理由')"></el-input>
      </div>
      <span slot="footer" class="dialog-footers">
        <el-button type="primary" @click="cancelWriteOffClick()">{{ $t("提交") }}</el-button>
        <el-button @click="cancelShow = false">{{ $t("取消") }}</el-button>
      </span>
    </el-dialog>
    <!--收款单批量反审核 对话框，一个逻辑一个对话框，
      避免做过多的逻辑判断 lanbm 2024-05-29 add-->
    <el-dialog :title="dialogTitle2" :visible.sync="dialogVisible2" width="30%">
      <div class="cancel_content">
        <span>{{ $t("申请理由") }}</span>
        <el-input type="textarea" :rows="6" v-model="reason" :placeholder="$t('请输入理由')"></el-input>
      </div>
      <span slot="footer" class="dialog-footers">
        <el-button type="primary" @click="writeOffClick2()">{{ $t("提交反审核") }}</el-button>
        <el-button @click="dialogVisible2 = false">{{ $t("取消") }}</el-button>
      </span>
    </el-dialog>
    <!--收款单批量反核销 对话框，一个逻辑一个对话框，
      避免做过多的逻辑判断 lanbm 2024-05-29 add-->
    <el-dialog :title="dialogTitle3" :visible.sync="dialogVisible3" width="30%">
      <div class="cancel_content">
        <span>{{ $t("申请理由") }}</span>
        <el-input type="textarea" :rows="6" v-model="reason" :placeholder="$t('请输入理由')"></el-input>
      </div>
      <span slot="footer" class="dialog-footers">
        <el-button type="primary" @click="writeOffClick3()">{{ $t("提交反核销") }}</el-button>
        <el-button @click="dialogVisible3 = false">{{ $t("取消") }}</el-button>
      </span>
    </el-dialog>

    <!-- 批量导入弹窗 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" @close="closeUploadDialog" append-to-body>
      <el-upload ref="upload" :multiple="false" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?ignoreItem=' + upload.ignoreItem" :data="upload.data" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload" />
        <div class="el-upload__text">
          {{ $t("将文件拖到此处，或") }}<em>{{ $t("点击上传") }}</em>
        </div>
        <div slot="tip" class="el-upload__tip text-center">
          <span>{{ $t("仅允许导入xls、xlsx格式文件。") }}</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">{{ $t("下载模板") }} </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer-upload">
        <el-button type="primary" @click="submitFileForm">{{ $t("确 定") }}</el-button>
        <el-button @click="upload.open = false">{{ $t("取 消") }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="$t('导入提示信息，请确认是否提交')" :visible.sync="continueUploadModal.show" width="30%">
      <div v-html="continueUploadModal.msg"></div>
      <span slot="footer" class="dialog-footer-upload">
        <el-button @click="continueUploadModal.show = false">{{ $t("取 消") }}</el-button>
        <el-button type="primary" :disabled="!fileCopy" @click="continueUpload">{{ $t("确 定") }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { customerDropDownList } from "@/api/ecw/customerCommissionInfo"
import { getCustomerList } from "@/api/ecw/customer"
import { listSimpleUsers } from "@/api/system/user"
import { DICT_TYPE } from "@/utils/dict"
import CustomerSelector from "@/components/CustomerSelector"
import { getCurrencyPage } from "@/api/ecw/currency"
import { getBaseHeader } from "@/utils/request"
import {
  getReceiptList,
  // receiptVerification,
  // receiptVerificationCancel,
  receiptExportExcel,
  deleteReceipt,
  financeReceiptWriteOffNo,
  financeApproveNo,
  financeReceiptWriteOffNo2,
  financeApproveNo2,
  financeReceiptWriteOff2,
  cancelFinanceReceiptApproval,
  cancelFinanceReceiptApprovalNo,
  cancelFinanceReceiptWriteOffNo,
  cancelFinanceReceiptWriteOff,
  handleDownloadReceiptTmp
} from "@/api/ecw/financial"

// lanbm 2024-05-30 添加注释
// 收款单状态 0 草稿，1 待收款，2 待提交
// 3 已部分核销，4已核销
// 5 已核销待开票，6 已开票，
// 7 审核中，8审核失败，9反审核中
// 10 全部核销中，11反核销审核中

export default {
  name: "EcwFinancialVoucher",
  components: {
    CustomerSelector
  },
  data() {
    return {
      fileCopy: null,
      upload: {
        ignoreItem: false,
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: this.$t("导入银行收款信息"),
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: getBaseHeader(),
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/admin-api/ecw/receipt-item/import"
      },
      continueUploadModal: {
        show: false,
        msg: ""
      },
      exportId: "",
      open: false,
      showSearch: true,
      loadings: false,
      form: {},
      creatorData: [],
      list: [],
      total: 0,
      dateType: [],
      loading: "",
      params: {},
      customeList: [],
      // 查询参数
      queryParams: {
        page: 1,
        rows: 20,
        customerIdList: [],
        stateList: null,
        salesmanIdList: [],
        numberNo: null,
        dateType: null,
        date: null,
        originId: null,
        destinationId: null,
        transportId: null,
        isCargoControl: null,
        orderExceptionStatus: null,
        orderExceptionType: null,
        orderNo: null,
        consignorId: null,
        marks: null,
        prodId: null,
        productRecord: null,
        followUpSalesmanId: null,
        receiptItemStatus: null, //明细状态
        invoicingStatus: null, //开票状态
        invoiceDataStatus: null //开票明细状态
      },
      dateFilter: [],
      downloading: false, // 导出状态
      dialogVisible: false,
      reason: "",
      writeOffType: 1,
      writeOffIndex: 0,
      cancelShow: false,
      cancelTitle: "",
      cancelReason: "",
      cancelIndex: 0,
      selectIndex: 0,
      // 选中数组
      ids: [],
      BpmNameList: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      listPar: [],
      dialogVisible2: false, //批量反审核对话框
      dialogTitle2: "收款单批量反审核",
      dialogVisible3: false, //批量反核销对话框
      dialogTitle3: "收款单批量反核销",
      currencyList: []
    }
  },
  activated() {
    this.customerDropDownFn()
    const orderNo = this.$route.query.orderNo || ""
    if (orderNo) {
      this.queryParams.numberNo = orderNo
    }
    this.getList()
  },
  computed: {},
  created() {
    this.customerDropDownFn()
    //获取汇率 lanbm 2024-06-06 add
    getCurrencyPage(this.params).then((res) => (this.currencyList = res.data.list))

    let that = this
    listSimpleUsers().then((res) => (that.creatorData = res.data))
    const orderNo = this.$route.query.orderNo || ""
    if (orderNo) {
      this.queryParams.numberNo = orderNo
    }
    this.getList()
  },
  methods: {
    closeUploadDialog() {
      this.fileCopy = null
    },
    customerDropDownFn(val) {
      customerDropDownList({ pageNo: 1, pageSize: 200, searchKey: val }).then((res) => {
        if (res.code === 0) {
          this.customeList = res.data.list
        }
      })
    },
    continueUpload() {
      this.$message.success(this.$t("正在提交，请稍后。"))
      this.$refs.upload.handleStart(this.fileCopy.raw)
      this.fileCopy = null
      this.$refs.upload.submit()
    },
    handleShowFileUploadDialog() {
      this.upload.open = true
      this.upload.ignoreItem = false
      this.$nextTick(() => {
        this.upload.isUploading = false
        this.$refs.upload.clearFiles()
      })
      // this.upload.url = process.env.VUE_APP_BASE_API + "/admin-api/ecw/receipt-item/import?ignoreItem=" + false
    },
    // 下载导入模板
    importTemplate() {
      handleDownloadReceiptTmp().then((res) => {
        this.$download.excel(res, "银行收款信息模板.xlsx")
        this.$message({
          message: this.$t("下载模板成功"),
          type: "success"
        })
      })
    },
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false
      this.continueUploadModal.show = false
      // 错误
      if (response.code == "1004520042") {
        // this.$modal.msgError(response.msg)
        this.$notify({
          title: this.$t("错误提示"),
          dangerouslyUseHTMLString: true,
          message: this.$t(response.msg),
          type: "error",
          duration: 0
        })
        this.$refs.upload.clearFiles()

        return
      }
      // 警告
      if (response.code == "1004520043") {
        this.upload.ignoreItem = true
        this.fileCopy = file
        // this.$modal.msgError(response.msg)
        this.continueUploadModal.show = true
        this.continueUploadModal.msg = response.msg
        return
      }
      if (response.code !== 0) {
        this.$modal.msgError(response.msg)
        return
      }
      this.upload.open = false
      this.fileCopy = null
      this.$refs.upload.clearFiles()
      // 拼接提示语
      // let data = response.data
      // let text = this.$t("创建成功数量：") + data.createUsernames.length
      // for (const username of data.createUsernames) {
      //   text += "<br />&nbsp;&nbsp;&nbsp;&nbsp;" + username
      // }
      // text += "<br />更新成功数量：" + data.updateUsernames.length
      // for (const username of data.updateUsernames) {
      //   text += "<br />&nbsp;&nbsp;&nbsp;&nbsp;" + username
      // }
      // text += "<br />更新失败数量：" + Object.keys(data.failureUsernames).length
      // for (const username in data.failureUsernames) {
      //   text += "<br />&nbsp;&nbsp;&nbsp;&nbsp;" + username + this.$t("：") + data.failureUsernames[username]
      // }
      // this.$alert(text, this.$t("导入结果"), { dangerouslyUseHTMLString: true })
      // this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      if (!this.fileCopy) {
        this.$refs.upload.submit()
      }
    },
    //发票新增/编辑页面
    goInvoiceOperate({ id, key }) {
      this.$router.push("/financial/invoiceOperate?id=" + id + "&key=" + key)
    },
    /** 查询列表 */
    getList() {
      this.loading = true
      this.params = {}
      for (var key in this.queryParams) {
        if (this.queryParams[key]) {
          this.params[key] = this.queryParams[key]
        }
      }
      console.log(this.params)
      // 处理查询参数
      let params = this.removeEmpty({ ...this.params })
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, "createTime")
      // 执行查询
      getReceiptList(params).then((response) => {
        this.list = response.data.list
        this.total = response.data.total
        this.loading = false
      })
    },
    changeCustomerId(e) {
      this.$set(this.queryParams, "customerId", e.id)
    },
    verificationClick(row) {
      const id = row.id
      return this.$router.push("receiptDetail?id=" + id)
      //   this.$modal
      //     .confirm("您确认要核销吗？")
      //     .then(function () {
      //       return receiptVerification(id);
      //     })
      //     .then(() => {
      //       this.getList();
      //       this.$modal.msgSuccess("核销成功");
      //     })
      //     .catch(() => {});
    },
    verificationCancelClick(row) {
      const id = row.id
      return this.$router.push("/financial/receiptDetail?id=" + id)
      // this.$modal
      //   .confirm("您确认要反核销吗？")
      //   .then(function () {
      //     return receiptVerificationCancel(id);
      //   })
      //   .then(() => {
      //     this.getList();
      //     this.$modal.msgSuccess("反核销成功");
      //   })
      //   .catch(() => {});
    },
    getCurrencyLabel(id) {
      let label = this.currencyList.filter((item) => item.id == id)
      if (label.length > 0) return this.$i18n.locale == "zh_CN" ? label[0].titleZh : label[0].titleEn
      return ""
    },
    //显示取消审核弹窗
    cancelClick(index, type) {
      this.selectIndex = index
      this.cancelIndex = type
      this.cancelReason = ""
      if (this.cancelIndex == 1) {
        this.cancelTitle = this.$t("取消审核")
      } else if (this.cancelIndex == 2) {
        this.cancelTitle = this.$t("取消反审核")
      } else if (this.cancelIndex == 3) {
        this.cancelTitle = this.$t("取消反核销审核")
      } else {
        this.cancelTitle = this.$t("取消全部核销审核")
      }
      this.cancelShow = true
    },
    //取消审核
    cancelWriteOffClick() {
      if (!this.cancelReason) {
        this.$modal.msgError(this.$t("请输入申请理由"))
        return
      }
      var receiptId = this.list[this.selectIndex].id
      if (this.cancelIndex == 1) {
        cancelFinanceReceiptApproval({
          receiptId: receiptId,
          remark: this.cancelReason
        }).then((res) => {
          this.cancelShow = false
          this.getList()
          this.$message.success(this.$t("提交成功"))
        })
      } else if (this.cancelIndex == 2) {
        cancelFinanceReceiptApprovalNo({
          receiptId: receiptId,
          remark: this.cancelReason
        }).then((res) => {
          this.cancelShow = false
          this.getList()
          this.$message.success(this.$t("提交成功"))
        })
      } else if (this.cancelIndex == 3) {
        cancelFinanceReceiptWriteOffNo({
          receiptId: receiptId,
          remark: this.cancelReason
        }).then((res) => {
          this.cancelShow = false
          this.getList()
          this.$message.success(this.$t("提交成功"))
        })
      } else {
        cancelFinanceReceiptWriteOff({
          receiptId: receiptId,
          remark: this.cancelReason
        }).then((res) => {
          this.cancelShow = false
          this.getList()
          this.$message.success(this.$t("提交成功"))
        })
      }
    },
    writeOffClick() {
      if (!this.reason) {
        this.$modal.msgError(this.$t("请输入申请理由"))
        return
      }
      const receiptIdData = this.list[this.writeOffIndex]
      if (this.writeOffType == 1) {
        financeApproveNo({
          receiptId: receiptIdData.id,
          receiptNo: receiptIdData.receiptNo,
          remark: this.reason
        }).then((res) => {
          this.getList()
          this.$message.success(this.$t("提交成功"))
          this.dialogVisible = false
        })
      } else {
        financeReceiptWriteOffNo({
          receiptId: receiptIdData.id,
          receiptNo: receiptIdData.receiptNo,
          remark: this.reason
        }).then((res) => {
          this.getList()
          this.$message.success(this.$t("提交成功"))
          this.dialogVisible = false
        })
      }
    },
    deleteClick(row) {
      const id = row.id
      this.$modal
        .confirm(this.$t("是否确认删除该收款单") + "?")
        .then(function () {
          return deleteReceipt(id)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess(this.$t("删除成功"))
        })
        .catch(() => {})
    },
    /** 搜索按钮操作 */
    handleQuery() {
      if (this.dateFilter && this.dateFilter.length > 0) {
        this.queryParams.beginCreateTime = this.dateFilter[0]
        this.queryParams.endCreateTime = this.dateFilter[1]
      } else {
        this.queryParams.beginCreateTime = ""
        this.queryParams.endCreateTime = ""
      }
      this.queryParams.page = 1
      this.getList()
    },
    handleQuery2() {
      //批量反审核 lanbm 2024-05-14 add
      if (this.ids.length == 0) {
        this.$message.error(this.$t("请选择需要批量反审核收款单。"))
        return
      }

      this.listPar = []
      for (var i = 0; i < this.ids.length; i++) {
        if (this.ids[i].state != 1) {
          this.$message.error(this.$t("选中项中有不符合反审核条件的收款单。"))
          return
        }
        let obj = {
          receiptId: this.ids[i].id,
          receiptNo: this.ids[i].receiptNo,
          remark: this.reason
        }
        this.listPar.push(obj)
      }
      this.reason = ""
      this.dialogVisible2 = true
    },
    writeOffClick2() {
      //批量反审核 提交响应函数
      financeReceiptWriteOffNo2(this.listPar).then((res) => {
        this.getList()
        this.$message.success(this.$t("提交成功"))
        this.reason = ""
        this.dialogVisible2 = true
      })
    },
    handleQuery3() {
      //批量反核销 lanbm 2024-05-14 add
      if (this.ids.length == 0) {
        this.$message.error(this.$t("请选择需要批量反核销收款单。"))
        return
      }
      this.listPar = []
      for (var i = 0; i < this.ids.length; i++) {
        //必须满足能反核销的状态条件
        if (this.ids[i].state == 4 || this.ids[i].state == 5 || this.ids[i].state == 6) {
          let obj = {
            receiptId: this.ids[i].id,
            receiptNo: this.ids[i].receiptNo,
            remark: this.reason
          }
          this.listPar.push(obj)
        } else {
          this.$message.error(this.$t("选中项中有不符合反审核条件的收款单。"))
          return
        }
      }
      this.reason = ""
      this.dialogVisible3 = true
    },
    writeOffClick3() {
      //批量反核销 提交按钮响应函数
      financeReceiptWriteOffNo2(this.listPar).then((res) => {
        this.getList()
        this.$message.success(this.$t("提交成功"))
        this.reason = ""
        this.dialogVisible3 = true
      })
    },
    handleQuery4() {
      //批量核销 lanbm 2024-05-14 add
      if (this.ids.length == 0) {
        //校验参数
        this.$message.error(this.$t("请选择需要批量核销的收款单。"))
        return
      }
      //var str = JSON.stringify(this.ids);
      this.listPar = []
      for (var i = 0; i < this.ids.length; i++) {
        if (this.ids[i].state == 0) {
          this.$message.error(this.ids[i].receiptNo + "是草稿状态，不能核销。")
          return
        }
        if (this.ids[i].state == 4) {
          this.$message.error(this.ids[i].receiptNo + "是已核销状态，不用再次核销。")
          return
        }

        let obj = {
          receiptId: this.ids[i].id,
          receiptNo: this.ids[i].receiptNo,
          remark: this.reason
        }
        this.listPar.push(obj)
      }
      //var str2 = JSON.stringify(listPar);
      financeReceiptWriteOff2(this.listPar).then((res) => {
        this.getList()
        this.$message.success(this.$t("提交成功"))
        this.dialogVisible = false
      })
    },
    /** 新增按钮操作 */
    handleAdd(id) {
      return this.$router.push("/financial/creatCollection?id=" + id)
    },
    toprint(id) {
      return this.$router.push("/financial/printVoucher?id=" + id)
    },
    openInvoice(id) {
      return this.$router.push("/financial/openInvoice?id=" + id)
    },
    exportReceipt(id) {
      this.open = true
      this.exportId = id
    },
    //显示反审核反核销弹窗
    writeOffShow(type, index) {
      this.writeOffType = type
      this.writeOffIndex = index
      this.reason = ""
      this.dialogVisible = true
    },
    submitForm(type) {
      this.downloading = true
      receiptExportExcel({ id: this.exportId, billType: type })
        .then((response) => {
          this.$download.excel(response, `${type === 1 ? this.$t("国内账单") : "Debite_note"}.xls`)
          this.open = false
        })
        .finally(() => (this.downloading = false))
    },
    paymentDetail2(row) {
      //到订单详情 lanbm 2024-05-29 add
      const id = row.orderId
      //路由地址，不是文件路径地址
      return this.$router.push("/order/detail?orderId=" + id)
    },
    handleSelectionChange(selection) {
      //表格多选函数 lanbm 2024-05-20 add
      this.id = []
      this.ids = selection
      this.single = selection.length !== 1
      this.multiple = !selection.length
    }
  }
}
</script>

<style scoped>
.dialog-footer-upload {
  display: flex;
  justify-content: end;
  padding-top: 30px;
}
.card {
  margin-top: 20px;
}
.dialog-footer {
  padding: 30px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;

  height: 160px;
}
.dialog-footers {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.card-title {
  font-size: 18px;
  font-weight: bold;
}
.cancel_content {
  display: flex;
  flex-direction: column;
}
.cancel_content span {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 10px;
}
</style>
