<template>
  <div class="borderless" v-loading="pageLoading">
    <div class="customer-head">
      <div class="customer-back">
        <el-button type="danger" style="border: none;background: none;color: red" icon="el-icon-arrow-left" @click="backToList">返回列表 </el-button>
        <el-button v-if="form.id && pageIds.length" type="text" @click="lastPage">上一票</el-button>
        <el-button v-if="form.id && pageIds.length" type="text" @click="nextPage">下一票</el-button>
      </div>
      <div class="add-customer-btn">
        <el-button size="small" style="margin-right: 8px" :loading="saveLoading" :disabled="!form.id" @click="previewreportfun">预 览 </el-button>
        <el-button
          size="small"
          style="margin-right: 8px"
          v-if="roleName.indexOf('admin') != -1"
          :loading="saveLoading"
          :disabled="!form.id"
          @click="DesignreportDialog = true"
          >报表设计
        </el-button>
        <el-button type="success" size="small" :disabled="!form.id" plain @click="newbillFun">添加单据 </el-button>
        <el-button
          size="small"
          type="primary"
          style="margin-right: 8px"
          :disabled="!form.id || form.isCleared != 1"
          v-if="!form.voucherNo && whetheropen == 1"
          :loading="saveLoading"
          @click="generateVoucherfun"
          >生成凭证
        </el-button>
        <span v-if="form.voucherNo && voucher == 1" style="font-size: 12px;margin-right: 8px;">已生成凭证</span>
        <el-button
          size="small"
          type="warning"
          plain
          style="margin-right: 8px"
          :disabled="!form.id || editPower"
          v-if="form.isCleared == 1"
          :loading="saveLoading"
          @click="finstlbillsRevokeSettlementfun"
          >撤销结算
        </el-button>
        <el-button
          size="small"
          type="success"
          plain
          style="margin-right: 8px"
          :disabled="!form.id || editPower"
          v-else
          :loading="saveLoading"
          @click="submit('结算')"
          >确认结算
        </el-button>
        <el-button
          size="small"
          type="primary"
          style="margin-right: 8px"
          :disabled="form.isCleared == 1 || editPower"
          v-if="editSave"
          :loading="saveLoading"
          @click="editHandle"
          >编 辑
        </el-button>
        <el-button
          size="small"
          type="primary"
          style="margin-right: 8px"
          :disabled="form.isCleared == 1"
          v-else
          :loading="saveLoading"
          @click="editCustomer()"
          >保 存
        </el-button>
      </div>
    </div>

    <div style="margin: 55px 5px 0px 5px;'">
      <el-card class="box-card">
        <el-form :model="form" ref="form" label-width="90px" :rules="rules" class="demo-ruleForm">
          <el-row>
            <el-row>
              <el-col :span="5">
                <el-form-item label="往来单位" prop="corpCnName">
                  <search-query
                    :datalist="corpData"
                    :selectValue="form.corpCnName"
                    :clearable="true"
                    :disabled="editSave || tableData.length != 0 || tableData.length > 0"
                    :filterable="true"
                    :remote="true"
                    :buttonIf="false"
                    placeholder="请选择往来单位"
                    :forParameter="{
                      key: 'id',
                      label: 'cnName',
                      value: 'cnName'
                    }"
                    @corpChange="corpChange($event, 'corpCnName')"
                    @remoteMethod="corpBcorpsListfun"
                    @corpFocus="corpBcorpsListfun"
                  >
                  </search-query>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="开户帐号" prop="bankId">
                  <search-query
                    :datalist="bankData"
                    :selectValue="form.bankId"
                    :clearable="true"
                    :disabled="editSave || !form.corpId"
                    :filterable="true"
                    :buttonIf="false"
                    :allowCreate="true"
                    placeholder="请选择开户帐号"
                    :forParameter="{
                      key: 'id',
                      label: 'accountBankNo',
                      value: 'id'
                    }"
                    @corpChange="corpChange($event, 'bankId')"
                    @corpFocus="bcorpsbankListfun"
                  >
                  </search-query>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="事由" prop="remarks">
                  <el-input
                    style="width: 100%;"
                    v-model="form.remarks"
                    size="small"
                    autocomplete="off"
                    :disabled="editSave"
                    clearable
                    placeholder="请输入事由"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="费用名称" prop="feeCnName">
                  <dic-select
                    v-model="form.feeCnName"
                    placeholder="费用名称"
                    key="id"
                    label="cnName"
                    url="/blade-los/bfees/listAll"
                    :filterable="true"
                    :multiple="true"
                    :collapseTags="true"
                    :disabled="editSave"
                    dataType="string"
                  ></dic-select>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="结算日期" prop="billDate">
                  <el-date-picker
                    v-model="form.billDate"
                    clearable
                    style="width: 100%;"
                    type="date"
                    size="small"
                    :disabled="editSave"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    placeholder="选择结算日期"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="业务开始" prop="businessDateStart">
                  <el-date-picker
                    v-model="form.businessDateStart"
                    clearable
                    style="width: 100%;"
                    type="date"
                    size="small"
                    :disabled="editSave || tableData.length > 0"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    placeholder="选择业务开始日期"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="业务结束" prop="businessDateEnd">
                  <el-date-picker
                    v-model="form.businessDateEnd"
                    clearable
                    style="width: 100%;"
                    type="date"
                    size="small"
                    :disabled="editSave || tableData.length > 0"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    placeholder="选择业务结束日期"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label="收/付" prop="queryAmount">
                  <search-query
                    :datalist="dcData"
                    :selectValue="form.dc"
                    :filterable="true"
                    :clearable="true"
                    :remote="true"
                    :buttonIf="false"
                    :disabled="editSave || tableData.length > 0"
                    placeholder="请选择收/付"
                    @corpChange="corpChange($event, 'dc')"
                  >
                  </search-query>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label="币别" prop="curCode">
                  <search-query
                    :datalist="curCodeData"
                    :selectValue="form.curCode"
                    :clearable="true"
                    :disabled="editSave || tableData.length > 0"
                    :buttonIf="false"
                    :filterable="true"
                    :remote="true"
                    placeholder="请选择币别"
                    :forParameter="{
                      key: 'id',
                      label: 'code',
                      value: 'code'
                    }"
                    @corpChange="corpChange($event, 'curCode')"
                    @remoteMethod="getRateListfun"
                    @corpFocus="getRateListfun"
                  >
                  </search-query>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="业务编号" prop="businessNo">
                  <el-input
                    style="width: 100%;"
                    v-model="form.businessNo"
                    size="small"
                    autocomplete="off"
                    :disabled="editSave || tableData.length > 0"
                    clearable
                    placeholder="请输入业务编号"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="来源单号" prop="requestNo">
                  <el-input
                    style="width: 100%;"
                    v-model="form.requestNo"
                    size="small"
                    autocomplete="off"
                    :disabled="true"
                    clearable
                    placeholder="请输入来源单号"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="ACCT NO" prop="accountNo">
                  <el-input
                    style="width: 100%;"
                    v-model="form.accountNo"
                    size="small"
                    autocomplete="off"
                    :disabled="editSave || tableData.length > 0"
                    clearable
                    placeholder="请输入ACCT NO"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="MBL NO" prop="mblno">
                  <el-input
                    style="width: 100%;"
                    v-model="form.mblno"
                    size="small"
                    autocomplete="off"
                    :disabled="editSave || tableData.length > 0"
                    clearable
                    placeholder="请输入MBL NO"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="HBL NO" prop="hblno">
                  <el-input
                    style="width: 100%;"
                    v-model="form.hblno"
                    size="small"
                    autocomplete="off"
                    :disabled="editSave || tableData.length > 0"
                    clearable
                    placeholder="请输入HBL NO"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="对账单号" prop="checkNo">
                  <el-input
                    style="width: 100%;"
                    v-model="form.checkNo"
                    size="small"
                    autocomplete="off"
                    :disabled="editSave || tableData.length > 0"
                    clearable
                    placeholder="请输入对账单号"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="业务类型" prop="businessTypes">
                  <dic-select
                    v-model="form.businessTypes"
                    placeholder="业务类型"
                    key="id"
                    label="label"
                    keyValue="value"
                    :activateCreated="false"
                    :mockData="businessTypesData"
                    :filterable="true"
                    :multiple="true"
                    :collapseTags="true"
                    :disabled="editSave"
                    dataType="string"
                  ></dic-select>
                </el-form-item>
              </el-col>
            </el-row>

            <expand :showBtn="true" :showSpan="true">
              <el-row>
                <el-col :span="5">
                  <el-form-item label="船 名" prop="vesselCnName">
                    <el-input
                      style="width: 100%;"
                      v-model="form.vesselCnName"
                      size="small"
                      autocomplete="off"
                      :disabled="editSave || tableData.length > 0"
                      clearable
                      placeholder="请选择船名"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="5">
                  <el-form-item label="航 次" prop="voyageNo">
                    <el-input
                      style="width: 100%;"
                      v-model="form.voyageNo"
                      size="small"
                      autocomplete="off"
                      :disabled="editSave || tableData.length > 0"
                      clearable
                      placeholder="请输入航次"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </expand>

            <el-row>
              <el-col span="24">
                <div style="text-align: right">
                  <!--<el-button  size="small" type="" style="margin-right: 8px" :disabled="settlementdistar || editSave"-->
                  <!--            :loading="saveLoading" @click="ResetFilter">重置条件-->
                  <!--</el-button>-->
                  <!-- <el-checkbox v-model="appendType" :disabled="settlementdistar || editSave" false-label="检索" true-label="追加">追加</el-checkbox> -->
                  <el-button size="small" type="primary" :disabled="settlementdistar || editSave" :loading="saveLoading" @click="retrievalfun"
                    >检 索
                  </el-button>
                  <el-button size="small" :disabled="tableData.length > 0" @click="ResetFilter">重置条件 </el-button>
                </div>
              </el-col>
            </el-row>
          </el-row>
        </el-form>
      </el-card>
      <el-card style="margin-top: 10px">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="查询结果" name="1">
            <query-finstlbillsitems
              ref="finstlbillsitems"
              :queryData="queryData"
              :editSave="editSave"
              :settlementdistar="settlementdistar"
              :handleSelectionData="handleSelectionData"
              @handleSelectionChange="addSelectionChange"
              @deletefun="finstlbillsitemsRemovefun"
            >
              <template slot="menuLeft">
                <div>
                  <el-button size="small" type="success" :disabled="editSave || generateStatus" :loading="saveLoading" @click="SelectedRows"
                    >确认选定行
                  </el-button>
                  <el-input
                    style="width: 10%;margin-left: 10px;"
                    v-model="invoiceAmountCNY"
                    size="small"
                    autocomplete="off"
                    type="numbers"
                    clearable
                    placeholder="开票金额"
                  >
                    <span style="line-height: 32px;" slot="suffix">CNY</span>
                  </el-input>
                  <el-input
                    style="width: 10%;margin-left: 5px;"
                    v-model="invoiceAmountUSD"
                    size="small"
                    autocomplete="off"
                    type="numbers"
                    clearable
                    placeholder="开票金额"
                  >
                    <span style="line-height: 32px;" slot="suffix">USD</span>
                  </el-input>
                  <el-button style="margin-left: 10px" :disabled="editSave" size="small" type="primary" @click="invoiceMatchingfun()"
                    >匹配金额</el-button
                  >
                  <span style="font-size: 18px;font-weight: 600;margin-left: 50px;">
                    <span style="color: #67C23A;margin-right: 10px;"> CNY:￥{{ Number(amountSubSum).toFixed(2) }}元 </span>
                    <span style="color: #E6A23C;"> USD:${{ Number(amountSubUsdSum).toFixed(2) }}元 </span>
                  </span>
                </div>
              </template>
            </query-finstlbillsitems>
          </el-tab-pane>
          <el-tab-pane label="选定数据" name="2">
            <finstlbillsitems
              ref="finstlbillsitems"
              :tableData="tableData"
              :editSave="editSave || form.requestNo"
              :settlementdistar="settlementdistar"
              :handleSelectionData="handleSelectionData"
              @handleSelectionChange="handleSelectionChange"
              @deletefun="finstlbillsitemsRemovefun"
            >
              <template slot="menuLeft">
                <div>
                  <el-button size="small" type="danger" style="margin-left: 10px" :disabled="editSave" :loading="saveLoading" @click="batchDeletefun"
                    >一键删除
                  </el-button>
                  <span style="font-size: 18px;font-weight: 600;margin-left: 50px;">
                    <span style="color: #67C23A;margin-right: 10px;"> CNY:￥{{ Number(amountSubSum).toFixed(2) }}元 </span>
                    <span style="color: #E6A23C;"> USD:${{ Number(amountSubUsdSum).toFixed(2) }}元 </span>
                  </span>
                </div>
              </template>
            </finstlbillsitems>
          </el-tab-pane>
          <el-tab-pane label="凭证数据" name="3">
            <div style="margin-bottom: 10px">
              <el-button
                size="small"
                type="primary"
                style="margin-right: 8px"
                :loading="saveLoading"
                @click="addEntryfun"
                :disabled="editSave || generateStatus"
                >添加分录
              </el-button>
              <el-button
                size="small"
                type="primary"
                style="margin-right: 8px"
                :loading="saveLoading"
                @click="oneClickSave"
                :disabled="editSave || generateStatus"
                >一键保存
              </el-button>
              <el-button
                size="small"
                type="danger"
                style="margin-right: 8px"
                :loading="saveLoading"
                @click="deleteEntryfun"
                :disabled="editSave || generateStatus"
                >删除分录
              </el-button>
            </div>
            <fromtable-details
              :assemblyForm="form"
              :tableData="form.finStlBillsVoucherItemsList"
              :handleSelectionData="handleSelectionData2"
              :disabled="editSave || generateStatus"
              @handleSelectionChange="handleSelectionChange2"
              @addRowsfun="addRowsfun"
              @deletefun="deletefun"
              @auxiliaryAccountingfun="auxiliaryAccountingfun"
              @showOffRecordsfun="showOffRecordsfun"
            >
            </fromtable-details>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    <el-card style="margin-top: 10px">
      <el-row>
        <el-col :span="3">
          <div class="bottomFlex" style="color: #6BBCD1">
            <span>应付:</span>
            <span class="weightnum">¥{{ form.amountCr || 0 }}</span>
          </div>
        </el-col>
        <el-col :span="3">
          <div class="bottomFlex" style="color: #6BBCD1">
            <span>应付:</span>
            <span class="weightnum">${{ form.amountCrUsd || 0 }}</span>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="bottomFlex" style="color: #6BBCD1">
            <span>应付合计:</span>
            <span class="weightnum">¥{{ form.amountCrLoc || 0 }}</span>
          </div>
        </el-col>
        <el-col :span="3">
          <div class="bottomFlex" style="color: #81B337">
            <span>应收:</span>
            <span class="weightnum">¥{{ form.amountDr || 0 }}</span>
          </div>
        </el-col>
        <el-col :span="3">
          <div class="bottomFlex" style="color: #81B337">
            <span>应收:</span>
            <span class="weightnum">${{ form.amountDrUsd || 0 }}</span>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="bottomFlex" style="color: #81B337">
            <span>应收合计:</span>
            <span class="weightnum">¥{{ form.amountDrLoc || 0 }}</span>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!--选择数据弹窗-->
    <el-dialog title="选择数据" class="el-dialogDeep" :visible.sync="retrievePopupsType" append-to-body width="70%" :close-on-click-modal="false">
      <div>
        <avue-crud :option="retrievePopupsOption" :data="retrievePopupsData" ref="retrievePopupsRef" id="out-table">
          <template slot="menu" slot-scope="{ row }">
            <el-button type="text" size="small" @click.stop="retrievePopupsSelect(row)">选择 </el-button>
          </template>
        </avue-crud>
      </div>
    </el-dialog>

    <!--设计报表弹窗-->
    <el-dialog
      append-to-body
      title="设计报表"
      class="el-dialogDeep"
      :visible.sync="DesignreportDialog"
      width="70%"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :close-on-press-escape="false"
      v-dialog-drag
    >
      <reports :id="form.id" :assemblyForm="form" businessValue="JSZX"></reports>
    </el-dialog>

    <!--预览-->
    <el-dialog
      title="打印"
      :visible.sync="selectPrintingDialog"
      append-to-body
      width="70%"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :close-on-press-escape="false"
      v-dialog-drag
    >
      <div>
        <reportformsList ref="reportformsList" @reportRadio="reportRadio"></reportformsList>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="selectPrintingDialog = false">取 消</el-button>
      </span>
    </el-dialog>

    <!--报表组件-->
    <reportContainer ref="reportContainer"></reportContainer>
    <!--辅助核算-->
    <el-dialog title="核算项目维护" append-to-body :visible.sync="auxiliaryVisible" class="el-dialogDeep" width="40%" :before-close="handleClose">
      <div>科目名称: {{ subjectRow.accountFullName }}</div>
      <div style="margin-top: 10px">
        <el-form :model="subjectRow" ref="subjectRow" label-width="70px" class="demo-ruleForm">
          <!--#region-->
          <!--<div>外币核算:</div>-->
          <!--<el-row>-->
          <!--    <el-col :span="4">-->
          <!--        <el-form-item label="币种:" prop="curCode">-->
          <!--            <el-input style="width: 100%;" v-model="subjectRow.curCode"-->
          <!--                      size="small" autocomplete="off"-->
          <!--                      clearable placeholder="请输入币种" >-->
          <!--            </el-input>-->
          <!--        </el-form-item>-->
          <!--    </el-col>-->
          <!--    <el-col :span="4">-->
          <!--        <el-form-item label="汇率:" prop="exrate">-->
          <!--            <el-input style="width: 100%;" v-model="subjectRow.exrate"-->
          <!--                      size="small" autocomplete="off"-->
          <!--                      clearable placeholder="请输入汇率" >-->
          <!--            </el-input>-->
          <!--        </el-form-item>-->
          <!--    </el-col>-->
          <!--    <el-col :span="4">-->
          <!--        <el-form-item label="借方金额:" prop="amountDrUsd">-->
          <!--            <el-input style="width: 100%;" v-model="subjectRow.amountDrUsd"-->
          <!--                      size="small" autocomplete="off"-->
          <!--                      clearable placeholder="请输入借方金额" >-->
          <!--            </el-input>-->
          <!--        </el-form-item>-->
          <!--    </el-col>-->
          <!--    <el-col :span="4">-->
          <!--        <el-form-item label="贷方金额:" prop="amountCrUsd">-->
          <!--            <el-input style="width: 100%;" v-model="subjectRow.amountCrUsd"-->
          <!--                      size="small" autocomplete="off"-->
          <!--                      clearable placeholder="请输入贷方金额" >-->
          <!--            </el-input>-->
          <!--        </el-form-item>-->
          <!--    </el-col>-->
          <!--    <el-col :span="4">-->
          <!--        <el-form-item label="本币借方:" prop="amountDr">-->
          <!--            <el-input style="width: 100%;" v-model="subjectRow.amountDr"-->
          <!--                      size="small" autocomplete="off"-->
          <!--                      clearable placeholder="请输入本币借方" >-->
          <!--            </el-input>-->
          <!--        </el-form-item>-->
          <!--    </el-col>-->
          <!--    <el-col :span="4">-->
          <!--        <el-form-item label="本币贷方:" prop="amountCr">-->
          <!--            <el-input style="width: 100%;" v-model="subjectRow.amountCr"-->
          <!--                      size="small" autocomplete="off"-->
          <!--                      clearable placeholder="请输入本币贷方" >-->
          <!--            </el-input>-->
          <!--        </el-form-item>-->
          <!--    </el-col>-->
          <!--</el-row>-->
          <!--#endregion-->
          <!--#region-->
          <!--<div>数量核算:</div>-->
          <!--<el-row>-->
          <!--    <el-col :span="4">-->
          <!--        <el-form-item label="单位:" prop="unitNo">-->
          <!--            <el-input style="width: 100%;" v-model="subjectRow.unitNo"-->
          <!--                      size="small" autocomplete="off"-->
          <!--                      clearable placeholder="请输入单位" >-->
          <!--            </el-input>-->
          <!--        </el-form-item>-->
          <!--    </el-col>-->
          <!--    <el-col :span="4">-->
          <!--        <el-form-item label="规格:" prop="voucherNo">-->
          <!--            <el-input style="width: 100%;" v-model="subjectRow.voucherNo"-->
          <!--                      size="small" autocomplete="off"-->
          <!--                      clearable placeholder="请输入规格" >-->
          <!--            </el-input>-->
          <!--        </el-form-item>-->
          <!--    </el-col>-->
          <!--    <el-col :span="4">-->
          <!--        <el-form-item label="借方数量:" prop="quantityDr">-->
          <!--            <el-input style="width: 100%;" v-model="subjectRow.quantityDr"-->
          <!--                      size="small" autocomplete="off"-->
          <!--                      clearable placeholder="请输入借方数量" >-->
          <!--            </el-input>-->
          <!--        </el-form-item>-->
          <!--    </el-col>-->
          <!--    <el-col :span="4">-->
          <!--        <el-form-item label="借方单价:" prop="voucherNo">-->
          <!--            <el-input style="width: 100%;" v-model="subjectRow.voucherNo"-->
          <!--                      size="small" autocomplete="off"-->
          <!--                      clearable placeholder="请输入借方单价" >-->
          <!--            </el-input>-->
          <!--        </el-form-item>-->
          <!--    </el-col>-->
          <!--    <el-col :span="4">-->
          <!--        <el-form-item label="贷方数量:" prop="quantityCr">-->
          <!--            <el-input style="width: 100%;" v-model="subjectRow.quantityCr"-->
          <!--                      size="small" autocomplete="off"-->
          <!--                      clearable placeholder="请输入贷方数量" >-->
          <!--            </el-input>-->
          <!--        </el-form-item>-->
          <!--    </el-col>-->
          <!--    <el-col :span="4">-->
          <!--        <el-form-item label="贷方单价:" prop="voucherNo">-->
          <!--            <el-input style="width: 100%;" v-model="subjectRow.voucherNo"-->
          <!--                      size="small" autocomplete="off"-->
          <!--                      clearable placeholder="请输入贷方单价" >-->
          <!--            </el-input>-->
          <!--        </el-form-item>-->
          <!--    </el-col>-->
          <!--</el-row>-->
          <!--#endregion-->
          <el-row :gutter="40">
            <el-col :span="12" v-if="subjectAccount.isCorp">
              <!--<div>客户核算：</div>-->
              <el-form-item label="客户名称:" prop="corpCnName">
                <search-query
                  style="width: 100%"
                  ref="searchQueryRef"
                  :datalist="corpCnNameData"
                  :selectValue="subjectRow.corpCnName"
                  :filterable="true"
                  :clearable="true"
                  :remote="true"
                  :buttonIf="true"
                  placeholder="请选择客户名称"
                  :forParameter="{ key: 'id', label: 'cnName', value: 'cnName' }"
                  @corpFocus="getBcorpsListfun"
                  @remoteMethod="getBcorpsListfun"
                  @corpChange="corpChange2($event, 'corpCnName')"
                  @eldialogConfirm="eldialogConfirm('bcorps')"
                  @bottonSearchfun="bottonSearchfun('bcorps')"
                >
                  <bcorps ref="bcorps" :eldialog="true" @selectionChange="eldialogMultipleChoice($event, 'bcorps')"></bcorps>
                </search-query>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="subjectAccount.isDept">
              <!--<div>部门核算：</div>-->
              <el-form-item label="部门名称:" prop="deptName">
                <tree-select
                  v-model="subjectRow.deptName"
                  filterable
                  :data="deptData"
                  :props="{ label: 'title', children: 'children' }"
                  nodeKey="title"
                  size="small"
                  :multiple="false"
                  placeholder="请选择部门名称"
                  @focus="getDeptTreefun"
                  @input="corpChange2($event, 'deptName')"
                >
                </tree-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="subjectAccount.isEmpl">
              <!--<div>职员核算：</div>-->
              <el-form-item label="职员名称:" prop="emplName">
                <search-query
                  :datalist="emplData"
                  :selectValue="subjectRow.emplName"
                  :clearable="true"
                  :buttonIf="false"
                  :filterable="true"
                  :remote="true"
                  placeholder="请选择职员名称"
                  :forParameter="{ key: 'id', label: 'name', value: 'name' }"
                  @corpFocus="userGetListfun"
                  @corpChange="corpChange2($event, 'emplName')"
                  @remoteMethod="userGetListfun"
                >
                </search-query>
              </el-form-item>
            </el-col>
            <!--<el-col :span="12" v-if="subjectAccount.isItem">-->
            <!--    <div>项目核算：</div>-->
            <!--    <el-form-item label="项目名称:" prop="itemName">-->
            <!--        <el-input style="width: 100%;" v-model="subjectRow.itemName"-->
            <!--                  size="small" autocomplete="off"-->
            <!--                  clearable placeholder="请输入项目名称" >-->
            <!--        </el-input>-->
            <!--        <search-query :datalist="itemData"-->
            <!--                      :selectValue="subjectRow.itemName"-->
            <!--                      :clearable="true"-->
            <!--                      :buttonIf="false"-->
            <!--                      :filterable="true"-->
            <!--                      :remote="true"-->
            <!--                      placeholder="请选择项目名称"-->
            <!--                      :forParameter="{ key:'id', label:'cnName', value:'cnName'}"-->
            <!--                      @corpFocus="baccitemstypeListfun"-->
            <!--                      @corpChange="corpChange($event,'itemName')"-->
            <!--                      @remoteMethod="baccitemstypeListfun" >-->
            <!--        </search-query>-->
            <!--    </el-form-item>-->
            <!--</el-col>-->
          </el-row>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="auxiliaryVisible = false">取 消</el-button>
        <el-button type="primary" @click="auxiliaryDeterminefun">确 定</el-button>
      </span>
    </el-dialog>
    <!--预收预付核销-->
    <el-dialog
      title="预收预付核销管理"
      append-to-body
      :visible.sync="offRecordsVisible"
      class="el-dialogDeep"
      width="80%"
      :before-close="handleClose"
    >
      <div>
        科目名称:
        {{
          subjectRow.accountCode +
            " " +
            subjectRow.accountFullName +
            (subjectRow.isEmpl === 1 && subjectRow.emplName ? "/" + subjectRow.emplName : "") +
            (subjectRow.isDept === 1 && subjectRow.deptName ? "/" + subjectRow.deptName : "") +
            (subjectRow.isCorp === 1 && subjectRow.corpShortName ? "/" + subjectRow.corpShortName : "") +
            (subjectRow.isItem === 1 ? "/" + subjectRow.itemClassify + "-" + (subjectRow.itemName ? subjectRow.itemName : "") : "")
        }}
        方向：{{ subjectRow.dc === "D" ? "借" : "贷" }}
      </div>
      <div>
        借方金额: CNY {{ fixedAmt(subjectRow.amountDr, 16) }} {{ subjectRow.isForeign === 1 ? "USD " + fixedAmt(subjectRow.amountDrUsd, 16) : "" }}
      </div>
      <div>
        贷方金额: CNY {{ fixedAmt(subjectRow.amountCr, 16) }} {{ subjectRow.isForeign === 1 ? "USD " + fixedAmt(subjectRow.amountCrUsd, 16) : "" }}
      </div>
      <div style="margin-top: 10px; margin-bottom: 10px">
        <el-form :model="subjectRowOff" ref="subjectRowOff" label-width="70px" class="demo-ruleForm">
          <el-row :gutter="40">
            <el-col :span="12" v-if="subjectRowOff.isCorp">
              <!--<div>客户核算：</div>-->
              <el-form-item label="客户名称:" prop="corpCnName">
                <search-query
                  style="width: 100%"
                  ref="searchQueryRef"
                  :datalist="corpCnNameData"
                  :selectValue="subjectRowOff.corpCnName"
                  :filterable="true"
                  :clearable="true"
                  :remote="true"
                  :buttonIf="true"
                  placeholder="请选择客户名称"
                  :forParameter="{ key: 'id', label: 'cnName', value: 'cnName' }"
                  @corpFocus="getBcorpsListfun"
                  @remoteMethod="getBcorpsListfun"
                  @corpChange="corpChangeOff($event, 'corpCnName')"
                  @eldialogConfirm="eldialogConfirmOff('bcorps')"
                  @bottonSearchfun="bottonSearchfun('bcorps')"
                >
                  <bcorps ref="bcorps" :eldialog="true" @selectionChange="eldialogMultipleChoice($event, 'bcorps')"></bcorps>
                </search-query>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="subjectRowOff.isCorp">
              <el-form-item label="" prop="">
                <el-button type="primary" @click="regetOffVoucherItems">查询</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div style="margin-top: 10px">
        <!--        show-summary-->
        <!--        :summary-method="summaryMethodOff"-->
        <el-table
          ref="tableOffRecords"
          :cell-style="{ padding: '0px', fontSize: '12px' }"
          :header-cell-style="tableHeaderCellStyle"
          :close-on-click-modal="false"
          :data="offRecordsData"
          :border="true"
          style="width: 100%"
          show-summary
          :summary-method="summaryMethodOff"
          @selection-change="handleOffRecordsSelectionChange"
          :row-class-name="rowClassName"
        >
          <el-table-column fixed="left" type="selection" width="50"> </el-table-column>
          <el-table-column type="index" width="40" style="text-align: center"> </el-table-column>
          <el-table-column prop="voucherDate" label="凭证日期" width="120" style="padding: 0">
            <template slot-scope="{ row }">
              <span>{{ row.voucherDate }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="descr" label="摘要" width="200" style="padding: 0">
            <template slot-scope="{ row }">
              <span>{{ row.descr }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="accountCode" label="科目名称" width="240" style="padding: 0">
            <template slot-scope="{ row }">
              <span>
                {{
                  row.accountCode +
                    " " +
                    row.accountFullName +
                    (row.isEmpl === 1 && row.emplName ? "/" + row.emplName : "") +
                    (row.isDept === 1 && row.deptName ? "/" + row.deptName : "") +
                    (row.isCorp === 1 && row.corpShortName ? "/" + row.corpShortName : "") +
                    (row.isItem === 1 ? "/" + row.itemClassify + "-" + (row.itemName ? row.itemName : "") : "")
                }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="dc" label="借贷" width="40px" style="padding: 0">
            <template slot-scope="{ row }">
              <span>{{ row.dc === "C" ? "借" : "贷" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="本币金额">
            <el-table-column label="借方">
              <el-table-column prop="amountDr" label="金额" width="100px" style="text-align: right">
                <template slot-scope="{ row }">
                  <span>{{ displayAmt(row.amountDr) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="amountDrOffCurrent" label="本次可核销" width="120px" style="text-align: right">
                <template slot-scope="{ row }">
                  <el-input-number
                    v-if="subjectRow.dc === 'C' && row.amountDrBlc !== '0.00'"
                    style="width: 100%"
                    v-model="row.amountDrOffCurrent"
                    size="small"
                    autocomplete="off"
                    :disabled="form.voucherStatus == 1"
                    placeholder="请输入借方"
                    :precision="2"
                    @change="offAmountBlur(row, 'D')"
                    :controls="false"
                  >
                  </el-input-number>
                  <span v-if="subjectRow.dc === 'D' || row.amountDr === '0.00'">{{ displayAmt(row.amountDrOff) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="amountDrBlc" label="核销余额" width="100px" style="text-align: right">
                <template slot-scope="{ row }">
                  <span>{{ displayAmt(row.amountDrBlc) }}</span>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column label="货方">
              <el-table-column prop="amountCr" label="金额" width="100px" style="text-align: right">
                <template slot-scope="{ row }">
                  <span>{{ displayAmt(row.amountCr) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="amountCrOffCurrent" label="本次可核销" width="120px" style="text-align: right">
                <template slot-scope="{ row }">
                  <el-input-number
                    v-if="subjectRow.dc !== 'C' && row.amountCrBlc !== '0.00'"
                    style="width: 100%"
                    v-model="row.amountCrOffCurrent"
                    size="small"
                    autocomplete="off"
                    :disabled="form.voucherStatus == 1"
                    placeholder="请输入货方"
                    :precision="2"
                    @change="offAmountBlur(row, 'C')"
                    :controls="false"
                  >
                  </el-input-number>
                  <span v-if="subjectRow.dc === 'C' || row.amountCrBlc === '0.00'">{{ displayAmt(row.amountCrOff) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="amountCrBlc" label="核销余额" width="100px" style="text-align: right">
                <template slot-scope="{ row }">
                  <span>{{ displayAmt(row.amountCrBlc) }}</span>
                </template>
              </el-table-column>
            </el-table-column>
          </el-table-column>
          <el-table-column label="外币金额">
            <el-table-column prop="curCode" label="币种" width="50px" align="center"> </el-table-column>
            <el-table-column prop="exrate" label="汇率" width="80px" style="text-align: right">
              <template slot-scope="{ row }">
                <span>{{ row.exrate ? Number(row.exrate).toFixed(4) : "" }}</span>
              </template>
            </el-table-column>
            <el-table-column label="借方">
              <el-table-column prop="amountDrUsd" label="金额" width="100px" style="text-align: right">
                <template slot-scope="{ row }">
                  <span>{{ displayAmt(row.amountDrUsd) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="amountDrUsdOffCurrent" label="本次可核销" width="120px" style="text-align: right">
                <template slot-scope="{ row }">
                  <el-input-number
                    v-if="subjectRow.dc === 'C' && row.amountDrUsdBlc !== '0.00'"
                    style="width: 100%; text-align: right"
                    v-model="row.amountDrUsdOffCurrent"
                    size="small"
                    autocomplete="off"
                    :disabled="form.voucherStatus == 1 || row.curCode == 'CNY'"
                    clearable
                    placeholder="请输入借方"
                    :precision="2"
                    @change="offAmountUSDBlur(row, 'Dusd')"
                    :controls="false"
                  >
                  </el-input-number>
                  <span v-if="subjectRow.dc === 'D' || row.amountDrUsdBlc === '0.00'">{{ displayAmt(row.amountDrUsdOff) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="amountDrUsdBlc" label="核销余额" width="100px" style="text-align: right">
                <template slot-scope="{ row }">
                  <span>{{ displayAmt(row.amountDrUsdBlc) }}</span>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column label="货方">
              <el-table-column prop="amountCrUsd" label="金额" width="100px" style="text-align: right">
                <template slot-scope="{ row }">
                  <span>{{ displayAmt(row.amountCrUsd) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="amountCrUsdOffCurrent" label="金额" width="120px" style="text-align: right">
                <template slot-scope="{ row }">
                  <el-input-number
                    v-if="subjectRow.dc !== 'C' && row.amountCrUsdBlc !== '0.00'"
                    style="width: 100%"
                    v-model="row.amountCrUsdOffCurrent"
                    size="small"
                    autocomplete="off"
                    :disabled="form.voucherStatus == 1 || row.curCode == 'CNY'"
                    clearable
                    placeholder="请输入货方"
                    :precision="2"
                    @change="offAmountUSDBlur(row, 'Cusd')"
                    :controls="false"
                  >
                  </el-input-number>
                  <span v-if="subjectRow.dc === 'C' || row.amountCrUsdBlc === '0.00'">{{ displayAmt(row.amountCrUsdOff) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="amountCrUsdBlc" label="核销余额" width="100px" style="text-align: right">
                <template slot-scope="{ row }">
                  <span>{{ displayAmt(row.amountCrUsdBlc) }}</span>
                </template>
              </el-table-column>
            </el-table-column>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="offRecordsVisible = false">取 消</el-button>
        <el-button type="primary" @click="offRecordsDeterminefun">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import SearchQuery from "@/components/iosbasic-data/searchquery.vue";
import { getRateList } from "@/api/iosBasicData/rateManagement";
import { bcorpsbankList, getBcorpslistByType } from "@/api/iosBasicData/bcorps";
import {
  finstlbillsDetail,
  finstlbillsitemsRemove,
  finstlbillslistAccBillV1,
  finstlbillsSubmit,
  finstlbillsConfirmSettlement,
  finstlbillsRevokeSettlement,
  finstlbillsGetByDetail,
  finstlbillslistAccBillByCorp,
  finstlbillsGenerateVoucher,
  voucherRemove
} from "@/api/iosBasicData/finstlbills";
import { getDeptLazyTree } from "@/api/system/dept";
import expand from "@/components/basic-container/expand.vue";
import queryFinstlbillsitems from "@/views/iosBasicData/PaymentApplication/assembly/finstlbillsitems.vue";
import finstlbillsitems from "@/views/iosBasicData/PaymentApplication/assembly/finstlbillsitems2.vue";
import reports from "@/views/iosBasicData/SeafreightExportF/bills/assembly/reports.vue";
import reportformsList from "@/views/iosBasicData/SeafreightExportF/bills/assembly/reportformsList.vue";
import { getList as getreportsList, reportsGetReportData } from "@/api/iosBasicData/reports";
import reportContainer from "@/views/iosBasicData/report-container/report-container.vue";
import { generateFinStlBills } from "@/api/iosBasicData/fininvoices";
import { dateFormat } from "@/util/date";
import dicSelect from "@/components/dicSelect/main";
import { isProcurement } from "@/api/basicData/configuration";
import fromtableDetails from "./components/fromtableDetails.vue";
import { getCurrentDate } from "@/util/date";
import { accountsDetail } from "@/api/iosBasicData/accounts";
import { getOffVoucherItems } from "@/api/iosBasicData/finvouchers";
import TreeSelect from "@/components/iosbasic-data/TreeSelect.vue";
import { selectEmpls } from "@/api/approval/processConfig";
import { getBcorpsList } from "@/api/iosBasicData/bcorps";
import bcorps from "@/views/iosBasicData/bcorps/index.vue";
export default {
  components: {
    reportContainer,
    reportformsList,
    reports,
    SearchQuery,
    expand,
    finstlbillsitems,
    dicSelect,
    queryFinstlbillsitems,
    fromtableDetails,
    TreeSelect,
    bcorps
  },
  props: {
    // 编辑还是保存
    editSave: {
      type: Boolean,
      default: true
    },
    pageIds: {
      type: Array, // 指定 prop 的类型为 Array
      default: () => [] // 提供一个默认值，这里使用函数形式返回一个空数组
    }
  },
  data() {
    return {
      handleSelectionData2: [], // 分录多选的数据
      removedFinvouchersitems: [],
      voucherTypeData: [], // 凭证字数据
      voucherSourceData: [], // 业务类型
      auxiliaryVisible: false, // 辅助核算弹窗
      offRecordsVisible: false, // 预收预付核销弹窗
      offRecordsData: [], // 预收预付核销数据
      offRecordsSelectionData: [],
      subjectRowOff: {}, // 核销科目弹窗的显示数据
      subjectRow: {}, // 科目弹窗的显示数据
      subjectAccount: {}, // 当前选择科目的数据
      corpCnNameData: [], // 客户核算 下拉数据
      deptData: [], // 部门核算 下拉数据
      emplData: [], // 职员核算 下拉数据
      itemData: [], // 项目核算 下拉数据
      generateStatus: false,
      amountSubSum: 0,
      amountDSubSum: 0,
      amountCSubSum: 0,
      amountSubUsdSum: 0,
      amountDSubUsdSum: 0,
      amountCSubUsdSum: 0,
      retrievePopupsType: false, // 弹窗开启关闭
      retrievePopupsData: [], // 选择弹窗数据
      retrievePopupsOption: {
        border: true,
        calcHeight: 30,
        tip: false,
        height: "auto",
        index: true,
        addBtn: false,
        viewBtn: false,
        delBtn: false,
        editBtn: false,
        refreshBtn: false,
        columnBtn: false,
        menuWidth: "60",
        column: [
          {
            label: "客户中文名",
            prop: "cnName",
            overHidden: true
          },
          {
            label: "客户英文文名",
            prop: "cnName",
            overHidden: true
          }
        ]
      },
      invoiceAmountCNY: 0, // 费用明细开票金额输入框CNY
      invoiceAmountUSD: 0, // 费用明细开票金额输入框USD
      settlementdistar: false, // 结算挑进来的
      DesignreportDialog: false, // 设计报表弹窗
      selectPrintingDialog: false, // 预览报表
      // 收/付数据
      dcData: [
        {
          label: "全部",
          value: null
        },
        {
          label: "收",
          value: "D"
        },
        {
          label: "付",
          value: "C"
        }
      ],
      appendType: "检索", // 是否追加
      activeName: "1",
      queryData: [],
      tableData: [],
      pageLoading: false, // 全屏加载动画
      saveLoading: false, // 按钮动画
      // 绑定的数据
      form: {
        dc: null,
        billDate: dateFormat(new Date()),
        voucherSource: "MANUAL",
        voucherSourceName: "手工凭证",
        voucherType: "VOUNO-TRANS", // 凭证类型
        voucherTypeName: "转账凭证",
        voucherDate: getCurrentDate(),
        finStlBillsVoucherItemsList: []
      },
      addData: [],
      handleSelectionData: [], // 表格选择的数据
      corpData: [], // 结算单位 数据
      bankData: [], // 查询银行数据
      curCodeData: [], // 币别
      srcforParameter: {},
      // 业务类型
      businessTypesData: [
        {
          label: "海运出口",
          value: "SE"
        },
        {
          label: "海运进口",
          value: "SI"
        }
      ],
      rules: {
        corpCnName: [
          {
            required: true,
            message: "请输入付费对象",
            trigger: "blur"
          }
        ],
        // bankId: [
        //     { required: true, message: '请输入开户银行', trigger: 'blur' },
        // ],
        remarks: [
          {
            required: true,
            message: "请输入付费事由",
            trigger: "blur"
          }
        ],
        billDate: [
          {
            required: true,
            message: "请选择结算日期",
            trigger: "blur"
          }
        ],
        estimatedTime: [
          {
            required: true,
            message: "请输入预计收回",
            trigger: "blur"
          }
        ],
        collectionSituation: [
          {
            required: true,
            message: "请输入收款情况",
            trigger: "blur"
          }
        ]
      },
      roleName: [], // 当前的角色权限
      saberUserInfo: {}, // 当前登录人信息
      editPower: false, // 当前是否可以编辑
      voucher: 0,
      auditing: 0,
      whetheropen: 0
    };
  },
  created() {
    this.roleName = localStorage.getItem("roleName").split(",");
    // 获取当前登录人个人信息
    this.saberUserInfo = JSON.parse(localStorage.getItem("saber-userInfo")).content;
    isProcurement({ param: "automatic.generate.voucher" }).then(res => {
      // res.data.data === '1'
      this.voucher = res.data.data;
    });
    isProcurement({ param: "whether.open" }).then(res => {
      res.data.data = "1";
      this.whetheropen = res.data.data;
    });
    isProcurement({ param: "whether.auditing" }).then(res => {
      // res.data.data === '1'
      this.auditing = res.data.data;
    });
  },
  methods: {
    corpChange2(value, name) {
      let found = false;
      // 客户名称客户名称
      if (name == "corpCnName") {
        for (let item of this.corpCnNameData) {
          if (item.cnName == value) {
            found = true;
            this.$set(this.subjectRow, "corpEnName", item.enName);
            this.$set(this.subjectRow, "corpCnName", item.cnName);
            this.$set(this.subjectRow, "corpShortName", item.shortName);
            this.$set(this.subjectRow, "corpId", item.id);
          }
        }
        if (!found) {
          this.$set(this.subjectRow, "corpEnName", "");
          this.$set(this.subjectRow, "corpCnName", "");
          this.$set(this.subjectRow, "corpShortName", "");
          this.$set(this.subjectRow, "corpId", 0);
        }
      }
      // 核算
      else if (name == "deptName") {
        for (let item of this.deptData) {
          if (item.title == value) {
            found = true;
            this.$set(this.subjectRow, "deptName", item.title);
            this.$set(this.subjectRow, "deptId", item.id);
          }
        }
        if (!found) {
          this.$set(this.subjectRow, "deptName", "");
          this.$set(this.subjectRow, "deptId", 0);
        }
      }
      // 职员
      else if (name == "emplName") {
        for (let item of this.emplData) {
          if (item.name == value) {
            found = true;
            this.$set(this.subjectRow, "emplName", item.name);
            this.$set(this.subjectRow, "emplId", item.id);
          }
        }
        if (!found) {
          this.$set(this.subjectRow, "emplName", "");
          this.$set(this.subjectRow, "emplId", 0);
        }
      }
      // 项目核算
      else if (name == "itemName") {
        for (let item of this.itemData) {
          if (item.cnName == value) {
            found = true;
            this.$set(this.subjectRow, "itemName", item.cnName);
            this.$set(this.subjectRow, "itemId", item.id);
          }
        }
        if (!found) {
          this.$set(this.subjectRow, "itemName", "");
          this.$set(this.subjectRow, "itemId", 0);
        }
      } else if (name == "voucherType") {
        this.$set(this.form, name, value);
        for (let item of this.voucherTypeData) {
          if (item.dictKey == value) {
            found = true;
            this.$set(this.form, "voucherTypeName", item.dictValue + "凭证");
          }
        }
        if (!found) {
          this.$set(this.subjectRow, "voucherTypeName", "");
        }
      } else if (name == "voucherSource") {
        this.$set(this.form, name, value);
      }
    },
    corpChangeOff(value, name) {
      let found = false;
      // 客户名称
      if (name == "corpCnName") {
        for (let item of this.corpCnNameData) {
          if (item.cnName == value) {
            found = true;
            this.$set(this.subjectRowOff, "corpEnName", item.enName);
            this.$set(this.subjectRowOff, "corpCnName", item.cnName);
            this.$set(this.subjectRowOff, "corpShortName", item.shortName);
            this.$set(this.subjectRowOff, "corpId", item.id);
          }
        }
        if (!found) {
          this.$set(this.subjectRowOff, "corpEnName", "");
          this.$set(this.subjectRowOff, "corpCnName", "");
          this.$set(this.subjectRowOff, "corpShortName", "");
          this.$set(this.subjectRowOff, "corpId", 0);
        }
      }
      // 核算
      else if (name == "deptName") {
        for (let item of this.deptData) {
          if (item.title == value) {
            found = true;
            this.$set(this.subjectRowOff, "deptName", item.title);
            this.$set(this.subjectRowOff, "deptId", item.id);
          }
        }
        if (!found) {
          this.$set(this.subjectRowOff, "deptName", "");
          this.$set(this.subjectRowOff, "deptId", 0);
        }
      }
      // 职员
      else if (name == "emplName") {
        for (let item of this.emplData) {
          if (item.name == value) {
            found = true;
            this.$set(this.subjectRowOff, "emplName", item.name);
            this.$set(this.subjectRowOff, "emplId", item.id);
          }
        }
        if (!found) {
          this.$set(this.subjectRowOff, "emplName", "");
          this.$set(this.subjectRowOff, "emplId", 0);
        }
      }
      // 项目核算
      else if (name == "itemName") {
        for (let item of this.itemData) {
          if (item.cnName == value) {
            found = true;
            this.$set(this.subjectRowOff, "itemName", item.cnName);
            this.$set(this.subjectRowOff, "itemId", item.id);
          }
        }
        if (!found) {
          this.$set(this.subjectRowOff, "itemName", "");
          this.$set(this.subjectRowOff, "itemId", 0);
        }
      } else if (name == "voucherType") {
        this.$set(this.form, name, value);
        for (let item of this.voucherTypeData) {
          if (item.dictKey == value) {
            found = true;
            this.$set(this.form, "voucherTypeName", item.dictValue + "凭证");
          }
        }
        if (!found) {
          this.$set(this.subjectRowOff, "voucherTypeName", "");
        }
      } else if (name == "voucherSource") {
        this.$set(this.form, name, value);
      }
    },
    bottonSearchfun(name) {
      this.$nextTick(() => {
        if (this.$refs.bcorps.selectionList.length == 0) return;
        this.$refs.bcorps.$refs.crud.toggleSelection(); // 先清空所以选择的数据
      });
    },
    // 下拉多选弹窗数据多选回调
    eldialogMultipleChoice(list, name) {
      if (name == "bcorps") {
        let arr = [];
        if (list.length > 1) {
          this.$refs.bcorps.$refs.crud.toggleSelection(); // 先清空所以选择的数据
          arr = [list[list.length - 1]]; // 获取最新点击的数组
          this.$refs.bcorps.$refs.crud.toggleSelection(arr, true); // 把刚点击的数组变成选择状态
        } else {
          arr = list;
        }
        this.$refs.bcorps.selectionList = arr;
      } else {
        console.log("其他的组件");
      }
    },
    // 下拉多选弹窗的确认
    eldialogConfirm(name) {
      if (name == "bcorps") {
        if (this.$refs.bcorps.isShow) {
          console.log("列表确认");
          this.$set(this.subjectRow, "corpCnName", this.$refs.bcorps.selectionList[0].cnName);
          this.$set(this.subjectRow, "corpEnName", this.$refs.bcorps.selectionList[0].enName);
          this.$set(this.subjectRow, "corpId", this.$refs.bcorps.selectionList[0].id);
        } else {
          console.log("详情确认");
          this.$refs.bcorps.$refs.detail.submitForm();
          this.$set(this.subjectRow, "corpCnName", this.$refs.bcorps.$refs.detail.formData.cnName);
          this.$set(this.subjectRow, "corpEnName", this.$refs.bcorps.$refs.detail.formData.enName);
          this.$set(this.subjectRow, "corpId", this.$refs.bcorps.$refs.detail.formData.id);
        }
      } else {
        console.log("其他的组件");
      }
      this.$refs.searchQueryRef.corpVisible = false;
    },
    // 下拉多选弹窗的确认
    eldialogConfirmOff(name) {
      if (name == "bcorps") {
        if (this.$refs.bcorps.isShow) {
          console.log("列表确认");
          this.$set(this.subjectRowOff, "corpCnName", this.$refs.bcorps.selectionList[0].cnName);
          this.$set(this.subjectRowOff, "corpEnName", this.$refs.bcorps.selectionList[0].enName);
          this.$set(this.subjectRowOff, "corpId", this.$refs.bcorps.selectionList[0].id);
        } else {
          console.log("详情确认");
          this.$refs.bcorps.$refs.detail.submitForm();
          this.$set(this.subjectRowOff, "corpCnName", this.$refs.bcorps.$refs.detail.formData.cnName);
          this.$set(this.subjectRowOff, "corpEnName", this.$refs.bcorps.$refs.detail.formData.enName);
          this.$set(this.subjectRowOff, "corpId", this.$refs.bcorps.$refs.detail.formData.id);
        }
      } else {
        console.log("其他的组件");
      }
      this.$refs.searchQueryRef.corpVisible = false;
    },
    fixedAmt(amt, len) {
      let N = Number(amt);
      let S = isNaN(N) ? "0.00" : N.toFixed(2);
      while (S.length < len) {
        S = "_" + S;
      }
      return S;
    },
    displayAmt(amt, len) {
      let N = Number(amt);
      let S = isNaN(N) ? "" : N.toFixed(len ? len : 2);
      let Z = 0;
      return S === Z.toFixed(len ? len : 2) ? "" : S;
    },
    // 表头样式
    tableHeaderCellStyle({ row, column, rowIndex, columnIndex }) {
      return "padding:4px 0px;fontSize:12px;color:#000;background:#ecf5ff;text-align:center";
    },
    summaryMethodOff(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 2) {
          sums[index] = "合计";
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        // 显示列的统计 金额
        let arr = ["amountDrOffCurrent", "amountCrOffCurrent", "amountDrUsdOffCurrent", "amountCrUsdOffCurrent"];
        // 判断是否有这个数据
        if (arr.indexOf(column.property) != -1) {
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] = this.displayAmt(sums[index]); // 把合计的参数保留两位小数
            // sums[index] += " 元";
          } else {
            sums[index] = " ";
          }
        }
      });
      return sums;
    },
    rowClassName({ row, rowIndex }) {
      let rowName = "",
        findRow = this.handleSelectionData.find(c => c.rowIndex === row.rowIndex);
      if (findRow) {
        rowName = "current-row "; // elementUI 默认高亮行的class类 不用再样式了^-^,也可通过css覆盖改变背景颜色
      }
      return rowName; //也可以再加上其他类名 如果有需求的话
    },
    // 表格多选数据
    handleOffRecordsSelectionChange(list) {
      this.offRecordsSelectionData = list;
    },
    handleClose(done) {
      done();
    },
    newGuid() {
      let vd = "0123456789abcdefghijklmnopqrstuvwxyz".split("");
      var i = vd,
        o = [],
        s = Math.random,
        n;
      (o[8] = o[13] = o[18] = o[23] = "-"), (o[14] = "4");
      for (var r = 0; r < 36; r++) o[r] || ((n = 0 | (16 * s())), (o[r] = i[19 == r ? (3 & n) | 8 : 15 & n]));
      return o.join("");
    },
    // 添加分录
    addEntryfun() {
      let obj = {
        dynUID: this.newGuid().replace(/-/g, "")
      };
      console.log(obj);
      if (this.form.finStlBillsVoucherItemsList.length > 0) {
        obj.descr = this.form.finStlBillsVoucherItemsList[this.form.finStlBillsVoucherItemsList.length - 1].descr;
      }
      this.form.finStlBillsVoucherItemsList.push(obj);
    },
    forceNumber(n) {
      try {
        let N = parseFloat(n);
        if (isNaN(N)) {
          N = 0.0;
        } else {
          let S = N.toFixed(2);
          N = Number(S);
        }

        return N;
      } catch (e) {
        return 0.0;
      }
    },
    oneClickSave() {
      if (this.form.finStlBillsVoucherItemsList.length < 2) {
        return this.$message.warning("请填写至少凭证两笔分录后再保存！");
      }
      this.editCustomer();
    },
    // 行添加
    addRowsfun(row, index) {
      //第二个参数为0的时候，是可以添加参数的，1的时候是删除
      let obj = {
        dynUID: this.newGuid().replace(/-/g, "")
      };
      this.form.finStlBillsVoucherItemsList.splice(index, 0, obj);
    },
    // 行删除
    deletefun(row, index) {
      let offVouItems = Array.isArray(row.offVouItems) ? row.offVouItems : [];

      if (row.id) {
        this.$set(row, "changeMode", row.changeMode === "d" ? "u" : "d");
        // this.finvouchersitemsRemovefun(row.id);
        this.removedFinvouchersitems.push(row);
        voucherRemove(row.id).then(res => {
          this.form.finStlBillsVoucherItemsList.splice(index, 1);
        });
      } else {
        this.form.finStlBillsVoucherItemsList.splice(index, 1);
      }

      offVouItems.forEach(item => {
        let rowIdx = this.form.finStlBillsVoucherItemsList.indexOf(item);
        if (rowIdx >= 0) {
          if (item.id) {
            this.$set(item, "changeMode", item.changeMode === "d" ? "u" : "d");
            // this.finvouchersitemsRemovefun(row.id);
            this.removedFinvouchersitems.push(item);
            this.form.finStlBillsVoucherItemsList.splice(rowIdx, 1);
          } else this.form.finStlBillsVoucherItemsList.splice(rowIdx, 1);
        }
      });
    },
    // 删除分录
    deleteEntryfun() {
      if (this.handleSelectionData2.length == 0) {
        return this.$message.warning("请选择至少一条数据");
      }
      let offVouItems = [];
      let multiList = this.handleSelectionData2;
      let arr = this.form.finStlBillsVoucherItemsList;
      // 获取有id 的数据
      const itemsWithId = multiList.filter(item => item.id);
      let arrIds = itemsWithId.map(item => item.id); // 获取id 数据
      console.log(arrIds);
      // 把选中的删除掉
      multiList.forEach(item => {
        offVouItems = offVouItems.concat(Array.isArray(item.offVouItems) ? item.offVouItems : []);

        if (!item.hasOwnProperty("id")) {
          for (let index in arr) {
            if (JSON.stringify(item) == JSON.stringify(arr[index])) {
              arr.splice(Number(index), 1);
            }
          }
        }
      });
      // 有id 的处理
      if (itemsWithId.length != 0) {
        voucherRemove(arrIds.join(",")).then(res => {
          arrIds.forEach(id => {
            let i = this.form.finStlBillsVoucherItemsList.findIndex(item => item.id === id);
            if (i >= 0) {
              let row = this.form.finStlBillsVoucherItemsList[i];
              this.$set(row, "changeMode", "d");
              this.removedFinvouchersitems.push();
              this.form.finStlBillsVoucherItemsList.splice(i, 1);
            }
          });
          this.$message.success("删除成功");
        });
      }
      offVouItems.forEach(item => {
        let rowIdx = this.form.finStlBillsVoucherItemsList.indexOf(item);
        if (rowIdx >= 0) {
          if (item.id) {
            this.$set(item, "changeMode", item.changeMode === "d" ? "u" : "d");
            // this.finvouchersitemsRemovefun(row.id);
            this.removedFinvouchersitems.push(item);
            this.form.finStlBillsVoucherItemsList.splice(rowIdx, 1);
          } else this.form.finStlBillsVoucherItemsList.splice(rowIdx, 1);
        }
      });
    },
    // 借方/贷方 本币的计算
    offAmountBlur(row, name) {
      if (name === "D") {
        this.$set(row, "amountCrOffCurrent", 0);
      }
      if (name === "C") {
        this.$set(row, "amountDrOffCurrent", 0);
      }

      let a = row.amountCrOffCurrent ? Number(row.amountCrOffCurrent) : 0;
      this.$set(row, "amountCrOffCurrent", a > Number(row.amountCrBlc) ? Number(row.amountCrBlc) : a);
      a = row.amountDrOff ? Number(row.amountDrOff) : 0;
      this.$set(row, "amountDrOffCurrent", a > Number(row.amountDrBlc) ? Number(row.amountDrBlc) : a);

      if (row.curCode === "USD") {
        this.$set(row, "exrate", row.exrate ? Number(row.exrate) : 1);
        this.$set(row, "amountCrUsdOffCurrent", (row.amountCrOffCurrent / row.exrate).toFixed(2));
        this.$set(row, "amountDrUsdOffCurrent", (row.amountDrOffCurrent / row.exrate).toFixed(2));
      }
    },
    // 外币的计算
    offAmountUSDBlur(row, name) {
      if (name === "Dusd") {
        this.$set(row, "amountCrUsdOffCurrent", 0);
      }
      if (name === "Cusd") {
        this.$set(row, "amountDrUsdOffCurrent", 0);
      }
      let a = row.amountCrUsdOffCurrent ? Number(row.amountCrUsdOffCurrent) : 0;
      this.$set(row, "amountCrUsdOffCurrent", a > Number(row.amountCrUsdBlc) ? Number(row.amountCrUsdBlc) : a);
      a = row.amountDrUsdOffCurrent ? Number(row.amountDrUsdOffCurrent) : 0;
      this.$set(row, "amountDrUsdOffCurrent", a > Number(row.amountDrUsdBlc) ? Number(row.amountDrUsdBlc) : a);

      this.$set(row, "exrate", row.exrate ? Number(row.exrate) : 1);
      this.$set(row, "amountCrOffCurrent", (row.amountCrUsdOffCurrent * row.exrate).toFixed(2));
      this.$set(row, "amountDrOffCurrent", (row.amountDrUsdOffCurrent * row.exrate).toFixed(2));
    },
    // 客户
    getBcorpsListfun(cnName) {
      getBcorpsList(1, 10, { cnName }).then(res => {
        this.corpCnNameData = res.data.data.records;
      });
    },
    // 部门
    getDeptTreefun() {
      getDeptLazyTree(JSON.parse(localStorage.getItem("saber-userInfo")).content.dept_pid.split(",")[0]).then(res => {
        this.deptData = res.data.data;
      });
    },
    // 职员
    userGetListfun(account = undefined, type = false) {
      // userGetList(1, 10, { account }, JSON.parse(localStorage.getItem('saber-userInfo')).content.dept_pid.split(',')[0]).then(res => {
      //     this.emplData = res.data.data.records
      // })
      selectEmpls(1, 10, { cname: account, whetherEmployedOrNot: 1 }).then(res => {
        if (Array.isArray(res.data.data.records)) {
          res.data.data.records.forEach(item => {
            item.name = item.cname;
          });
        }
        this.emplData = res.data.data.records;
      });
    },
    handleSelectionChange2(list) {
      this.handleSelectionData2 = list;
    },
    // 科目编辑打开辅助核算弹窗
    auxiliaryAccountingfun(row) {
      // 获取状态
      accountsDetail(row.accountId).then(res => {
        this.subjectAccount = res.data.data;
        this.subjectRow = row;
        // 如果三个都没有勾选 直接不自动打开弹窗
        if (res.data.data.isCorp || res.data.data.isDept || res.data.data.isEmpl || res.data.data.isItem) {
          this.auxiliaryVisible = true;
        }
      });
    },
    regetOffVoucherItems() {
      getOffVoucherItems(this.subjectRowOff).then(res => {
        let list = Array.isArray(res.data.data) ? res.data.data : [];
        list.forEach(item => {
          if (this.offRecordsData.findIndex(i => i.id === item.id) === -1) {
            this.offRecordsData.push(item);
          }
        });
      });
    },
    offRecordsDeterminefun() {
      if (!Array.isArray(this.offRecordsData)) {
        this.offRecordsVisible = false;
        return;
      }

      if (this.offRecordsSelectionData.length === 0) {
        return this.$message.warning("请选择至少一条数据");
      }

      let row = this.subjectRow;
      let amt = row.dc === "D" ? Number(row.amountCr) : Number(row.amountDr);
      let usd = row.dc === "D" ? Number(row.amountCrUsd) : Number(row.amountDrUsd);
      let amtOff = 0.0,
        usdOff = 0;
      let rows = [];
      this.offRecordsSelectionData.forEach(item => {
        let currAmt = 0;
        if (row.dc === "D") {
          currAmt = Number(item.amountCrOffCurrent);
          amtOff = amtOff + currAmt;
          if (item.curCode === "USD") {
            usdOff = usdOff + Number(item.amountCrUsdOffCurrent);
          }
        } else {
          currAmt = Number(item.amountDrOffCurrent);
          amtOff = amtOff + currAmt;
          if (item.curCode === "USD") {
            usdOff = usdOff + Number(item.amountDrUsdOffCurrent);
          }
        }
        currAmt = currAmt > 0.0 ? currAmt.toFixed(2) : "0.00";
        if (currAmt !== "0.00") {
          rows.push(item);
        }
      });

      if (amt.toFixed(2) !== amtOff.toFixed(2)) {
        return this.$message({
          dangerouslyUseHTMLString: true,
          message: "<div>选定核销金额与应核销金额不一致！</div>",
          type: "warning"
        });
      }

      rows.forEach(item => {
        let obj = {
          dynUID: this.newGuid().replace(/-/g, "")
        };
        let flds = "accountId,accountCode,accountCnName,accountEnName,accountFullName,accountLevel,accountProperty,dc,";
        flds += "isArAp,isCorp,isDc,isDept,isEmpl,isForeign,curCode,isQuantity,unitNo,isItem,itemClassify,itemClassifyId,itemId,itemName,";
        flds += "corpId,corpShortName,corpCnName,corpEnName,deptId,deptName,emplId,emplName,exrate";
        flds.split(",").forEach(name => {
          obj[name] = item[name];
        });
        obj.descr = row.descr;
        if (row.dc === "D") {
          obj.amountDr = item.amountCrOffCurrent;
          obj.amountCr = 0.0;
          if (item.curCode === "USD") {
            obj.amountDrUsd = item.amountCrUsdOffCurrent;
            obj.amountCrUsd = 0.0;
          }
        } else {
          obj.amountCr = item.amountDrOffCurrent;
          obj.amountDr = 0.0;
          if (item.curCode === "USD") {
            obj.amountCrUsd = item.amountDrUsdOffCurrent;
            obj.amountDrUsd = 0.0;
          }
        }
        obj.isOff = 1;
        obj.offSrcItemId = item.id;
        obj.offVouItemId = row.id;
        if (!Array.isArray(row.offVouItems)) row.offVouItems = [];
        row.offVouItems.push(obj);

        this.form.finStlBillsVoucherItemsList.push(obj);
      });

      this.offRecordsVisible = false;
    },
    // 辅助核算弹窗确认按钮
    auxiliaryDeterminefun() {
      this.auxiliaryVisible = false;
    },
    // 获取核销记录
    showOffRecordsfun(row) {
      // 获取状态
      this.subjectRowOff = JSON.parse(JSON.stringify(row));
      getOffVoucherItems(this.subjectRowOff).then(res => {
        this.offRecordsSelectionData = [];
        this.offRecordsData = Array.isArray(res.data.data) ? res.data.data : [];
        this.subjectRow = row;
        this.offRecordsVisible = true;
      });
    },
    lastPage() {
      if (this.pageIds.length) {
        const index = this.pageIds.indexOf(this.form.id);
        if (index == 0) {
          return this.$message.error("没有上一票了");
        }
        const lastIndex = index - 1;
        // if (this.form.id) {
        //     this.unLock({
        //         moduleName: "SE",
        //         tableName: "SE_order",
        //         billId: this.form.id,
        //         billNo: this.form.mblno
        //     });
        // }
        this.finstlbillsDetailfun(this.pageIds[lastIndex]);
      }
    },
    nextPage() {
      if (this.pageIds.length) {
        const index = this.pageIds.indexOf(this.form.id);
        if (this.pageIds[this.pageIds.length - 1] == this.form.id) {
          return this.$message.error("没有下一票了");
        }
        const nextIndex = index + 1;
        // if (this.form.id) {
        //     this.unLock({
        //         moduleName: "SE",
        //         tableName: "SE_order",
        //         billId: this.form.id,
        //         billNo: this.form.mblno
        //     });
        // }
        this.finstlbillsDetailfun(this.pageIds[nextIndex]);
      }
    },
    // 打印
    reportRadio(val) {
      // 获取报表数据
      reportsGetReportData({
        billId: this.form.id,
        reportCode: val.classifyCode,
        groupCode: val.groupCode,
        type: "JSZX"
      }).then(res => {
        this.handleReportPreview(val.url, res.data.data.data);
      });
    },
    // 报表预览
    previewreportfun() {
      getreportsList(1, 10, {
        businessType: "JSZX"
        // classifyCode:'结算中心',
        // groupCode:'付费结算'
      }).then(res => {
        if (res.data.data.records.length == 1) {
          this.reportRadio(res.data.data.records[0]);
        } else {
          this.saveLoading = true;
          this.selectPrintingDialog = true;
          this.saveLoading = false;
          let page = {
            pageSize: 10,
            currentPage: 1,
            total: 0
          };
          this.$nextTick(() => {
            this.$refs.reportformsList.onLoad(page, {
              businessType: "JSZX"
              // classifyCode:'结算中心',
              // groupCode:'付费结算'
            });
          });
        }
      });
    },
    submit(type) {
      this.$confirm("确定进行结算操作?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.editCustomer(type);
        })
        .catch(() => {
          this.saveLoading = false; // 关闭按钮动画
        });
    },
    // 费用明细开票匹配
    invoiceMatchingfun() {
      if (this.invoiceAmountCNY != 0 || this.invoiceAmountUSD != 0) {
        let dataCNY = JSON.parse(JSON.stringify(this.invoiceAmountCNY));
        let dataUSD = JSON.parse(JSON.stringify(this.invoiceAmountUSD));
        for (let item of this.tableData) {
          this.$refs.finstlbillsitems.$refs.tableRef.toggleRowSelection(item, false);
          if (this.invoiceAmountCNY != 0) {
            if (dataCNY < 0) {
              dataCNY = 0;
            }
            if (dataCNY > 1500) {
              if (item.currentStlCurCode == "CNY") {
                this.$set(item, "currentStlAmountRMB", 1500);
                this.$refs.finstlbillsitems.$refs.tableRef.toggleRowSelection(item, true);
                dataCNY -= 1500;
              }
            } else {
              if (item.currentStlCurCode == "CNY") {
                if (dataCNY != 0) {
                  this.$refs.finstlbillsitems.$refs.tableRef.toggleRowSelection(item, true);
                }
                this.$set(item, "currentStlAmountRMB", dataCNY);
                dataCNY -= 1500;
              }
            }
          }
          if (this.invoiceAmountUSD != 0) {
            if (dataUSD < 0) {
              dataUSD = 0;
            }
            if (dataUSD > 1500) {
              if (item.currentStlCurCode == "USD") {
                this.$set(item, "currentStlAmountUSD", 1500);
                this.$refs.finstlbillsitems.$refs.tableRef.toggleRowSelection(item, true);
                dataUSD -= 1500;
              }
            } else {
              if (item.currentStlCurCode == "USD") {
                this.$set(item, "currentStlAmountUSD", dataUSD);
                if (dataUSD != 0) {
                  this.$refs.finstlbillsitems.$refs.tableRef.toggleRowSelection(item, true);
                }
                dataUSD -= 1500;
              }
            }
          }
        }
      }
    },
    // 一键删除
    batchDeletefun() {
      if (this.handleSelectionData.length == 0) {
        return this.$message.warning("请选择要删除的数据");
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        // 获取有id 的数据
        const itemsWithId = this.handleSelectionData.filter(item => item.hasOwnProperty("id"));
        let arrIds = itemsWithId.map(item => item.id); // 获取id 数据
        // 把选中的删除掉
        this.handleSelectionData.forEach(item => {
          for (let index in this.tableData) {
            if (item.accBillNo == this.tableData[index].accBillNo) {
              this.tableData.splice(Number(index), 1);
              this.form.finStlBillsItemsList = this.tableData;
            }
          }
        });
        // 有id 的处理
        if (itemsWithId.length != 0) {
          finstlbillsitemsRemove(arrIds.join(",")).then(res => {
            this.$message.success("操作成功");
          });
        }
      });
    },
    // 删除
    finstlbillsitemsRemovefun(id, index) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        if (id) {
          finstlbillsitemsRemove(id).then(res => {
            this.$message.success("操作成功");
          });
        }
        this.tableData.splice(index, 1);
        this.form.finStlBillsItemsList = this.tableData;
      });
    },
    // 下拉回调
    corpChange(value, name) {
      // 结算单位
      if (name == "corpCnName") {
        // 开户银行
        this.$set(this.form, "bankId", "");
        this.$set(this.form, "bankAccountName", "");
        this.$set(this.form, "bankAccountBank", "");
        this.$set(this.form, "bankAccountNo", "");
        if (!value) {
          this.$set(this.form, "corpId", "");
          this.$set(this.form, "corpCnName", "");
          this.$set(this.form, "corpEnName", "");
          this.$set(this.form, "corpArgreementNo", "");
        }
        for (let item of this.corpData) {
          if (item.cnName == value) {
            this.$set(this.form, "corpId", item.id);
            this.$set(this.form, "corpCnName", item.cnName);
            this.$set(this.form, "corpEnName", item.enName);
            this.$set(this.form, "corpArgreementNo", item.enName);
            this.bcorpsbankListfun();
          }
        }
      } else if (name == "bankId") {
        if (!value) {
          this.$set(this.form, "bankId", "");
          this.$set(this.form, "bankAccountName", "");
          this.$set(this.form, "bankAccountBank", "");
          this.$set(this.form, "bankAccountNo", "");
        }
        for (let item of this.bankData) {
          if (item.id == value) {
            this.$set(this.form, "bankId", item.id);
            this.$set(this.form, "bankAccountName", item.accountName);
            this.$set(this.form, "bankAccountBank", item.accountBank);
            this.$set(this.form, "bankAccountNo", item.accountNo);
          }
        }
      } else {
        this.$set(this.form, name, value);
      }
    },
    // 编辑
    editHandle() {
      this.editSave = false;
    },
    // 保存
    newbillFun() {
      if (this.form.isCleared == 1) {
        this.$emit("toAddEdit");
      } else {
        this.$confirm("是否需要保存?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.editCustomer("toAddEdit");
          })
          .catch(() => {
            this.$emit("toAddEdit");
          });
      }
    },
    editCustomer(type) {
      this.$refs.form.validate(valid => {
        if (!valid) return;
        if (!this.generateStatus) {
          if (!this.form.id) {
            // 是否选择从表数据
            if (this.addData.length == 0) {
              this.$message.warning("请选择结算数据");
              return;
            }
          }
        }

        if (type == "结算") {
          if (this.auditing == 1) {
            for (let [index, row] of this.tableData.entries()) {
              if (row.feeCnName == "增值税") {
                if (!row.taxInvoiceNumber || !row.taxInvoiceDate || !row.deductionTime) {
                  this.pageLoading = false;
                  this.saveLoading = false;
                  return this.$message.error("请完善第" + Number(index + 1) + "行增值税明细信息");
                }
              }
            }
          }
        }
        // 判断借方金额合计 是否等于 贷方金额合计
        let msgs = [];
        let amountDrSum = 0;
        let amountCrSum = 0;
        let index = 0;
        if (this.form.finStlBillsVoucherItemsList && this.form.finStlBillsVoucherItemsList.length) {
          for (let item of this.form.finStlBillsVoucherItemsList) {
            index++;
            let amtDr = this.forceNumber(item.amountDr);
            let amtCr = this.forceNumber(item.amountCr);
            amountDrSum += amtDr;
            amountCrSum += amtCr;
            let descr = item.descr ? item.descr.trim() : "";
            if (!descr) {
              msgs.push(`第 ${index} 行分录请填写摘要！`);
            } else {
              item.descr = descr;
            }
            if (!item.accountId) {
              msgs.push(`第 ${index} 行分录缺少科目代码！`);
            } else {
              if (item.isCorp === 1 && !item.corpId) {
                msgs.push(`第 ${index} 行分录科目 ${item.accountCode} ${item.accountFullName} 核算客户，请选择客户名称！`);
              }
              if (item.isDept === 1 && !item.deptId) {
                msgs.push(`第 ${index} 行分录科目 ${item.accountCode} ${item.accountFullName} 核算部门，请选择部门名称！`);
              }
              if (item.isEmpl === 1 && !item.emplId) {
                msgs.push(`第 ${index} 行分录科目 ${item.accountCode} ${item.accountFullName} 核算职员，请选择职员名称！`);
              }
              // if (item.isItem === 1 && !item.itemId) {
              //   msgs.push(`第 ${index} 行分录科目 ${item.accountCode} ${item.accountFullName} 核算项目，请选择项目名称！`);
              // }
              if (amtDr.toFixed(2) === "0.00" && amtCr.toFixed(2) === "0.00") {
                msgs.push(`第 ${index} 行分录科目 ${item.accountCode} ${item.accountFullName} 请填写金额！`);
              }
            }
          }
          if (amountDrSum !== amountCrSum) {
            msgs.push(`凭证借贷金额不平衡！`);
          }

          if (msgs.length > 0) {
            return this.$message({
              dangerouslyUseHTMLString: true,
              message: msgs.join("<br /><br />"),
              type: "warning"
            });
          }
        }

        // this.form.finStlBillsVoucherItemsList = this.form.finStlBillsVoucherItemsList.concat(this.removedFinvouchersitems);
        this.saveLoading = true; // 打开按钮动画
        if (this.form.estimatedTime) {
          this.form.estimatedTime = this.form.estimatedTime + " 00:00:00";
        }
        this.saveLoading = true; // 加载动画
        this.form.billNoFormat = "STL";
        this.form.businessTypeCode = "STL";
        this.form.businessType = "STL"; // 结算单
        this.form.businessDateStart = this.form.businessDateStart ? this.form.businessDateStart.slice(0, 10) + " 00:00:00" : null; // 财务开始日期
        this.form.businessDateEnd = this.form.businessDateEnd ? this.form.businessDateEnd.slice(0, 10) + " 00:00:00" : null; // 财务开始日期
        this.form.billDate = this.form.billDate ? this.form.billDate.slice(0, 10) + " 00:00:00" : null;
        this.form.auditDateTo = this.form.auditDateTo ? this.form.auditDateTo.slice(0, 10) + " 00:00:00" : null;
        this.form.voucherDate = this.form.voucherDate ? this.form.voucherDate.slice(0, 10) + " 00:00:00" : null;
        this.form.settlementType = this.settlementType;
        if (this.form.id) {
          if (type == "选定行") {
            this.form.finStlBillsItemsList = this.addData.map((item, index) => {
              if (item.currentStlCurCode == "CNY") {
                item.currentStlAmount = item.currentStlAmountRMB;
              } else {
                item.currentStlAmount = item.currentStlAmountUSD;
              }
              if (!this.form.id) {
                // delete item.businessType
                delete item.billDate;
                delete item.accountDc;
              }
              return item;
            });
          }
          if (this.form.finStlBillsItemsList.length != 0) {
            this.form.finStlBillsItemsList = this.form.finStlBillsItemsList.map((item, index) => {
              if (item.currentStlCurCode == "CNY") {
                item.currentStlAmount = item.currentStlAmountRMB;
                console.log(1, item.currentStlAmount, item.currentStlAmountRMB);
              } else {
                item.currentStlAmount = item.currentStlAmountUSD;
              }
              return item;
            });
          } else {
            this.form.finStlBillsItemsList = this.addData.map((item, index) => {
              if (item.currentStlCurCode == "CNY") {
                item.currentStlAmount = item.currentStlAmountRMB;
              } else {
                item.currentStlAmount = item.currentStlAmountUSD;
              }
              if (!this.form.id) {
                // delete item.businessType
                delete item.billDate;
                delete item.accountDc;
              }
              return item;
            });
          }
        } else {
          this.form.finStlBillsItemsList = this.addData.map((item, index) => {
            if (item.currentStlCurCode == "CNY") {
              item.currentStlAmount = item.currentStlAmountRMB;
            } else {
              item.currentStlAmount = item.currentStlAmountUSD;
            }
            if (!this.form.id) {
              // delete item.businessType
              delete item.billDate;
              delete item.accountDc;
            }
            return item;
          });
        }
        // 判断是结算还是保存
        if (type == "结算") {
          finstlbillsSubmit(this.form).then(res => {
            this.form = res.data.data;
            this.tableData = this.form.finStlBillsItemsList.map(item => {
              item.stlTtlAmountNet = Number(item.stlTtlAmount) - Number(item.stlTtlAmount) * (Number(item.taxRate) + Number(item.surchargeRate));
              item.currentStlAmountNet =
                Number(item.unsettledAmount) - Number(item.unsettledAmount) * (Number(item.taxRate) + Number(item.surchargeRate));
              if (item.curCode == "CNY") {
                this.$set(item, "currentInvoiceAmountRMB", item.currentInvoiceAmount);
                this.$set(item, "amountRMB", item.amount);
                this.$set(item, "amountNetRMB", item.amountNet);
                this.$set(item, "stlTtlAmountRMB", item.stlTtlAmount);
                this.$set(item, "stlTtlAmountNetRMB", item.stlTtlAmountNet);

                this.$set(item, "currentStlAmountNetRMB", item.currentStlAmountNet);
                this.$set(item, "currentStlAmountRMB", Number(item.currentStlAmount ? item.currentStlAmount : 0));
                this.$set(item, "currentStlAmountUSD", Number(0));
              } else {
                this.$set(item, "currentInvoiceAmountUSD", item.currentInvoiceAmount);
                this.$set(item, "amountUSD", item.amount);
                this.$set(item, "amountNetUSD", item.amountNet);
                this.$set(item, "stlTtlAmountNetUSD", item.stlTtlAmountNet);
                this.$set(item, "stlTtlAmountUSD", item.stlTtlAmount);
                this.$set(item, "currentStlAmountNetUSD", item.currentStlAmountNet);
                this.$set(item, "currentStlAmountUSD", Number(item.currentStlAmount ? item.currentStlAmount : 0));
                this.$set(item, "currentStlAmountRMB", Number(0));
              }

              if (item.srcIdInvoices) {
                this.settlementdistar = true;
              }
              return item;
            });
            this.finstlbillsConfirmSettlementfun();
          });
        } else if (type == "toAddEdit") {
          finstlbillsSubmit(this.form)
            .then(res => {
              this.$message.success("操作成功");
              this.saveLoading = false; // 关闭按钮动画
              this.$emit(type);
              this.finstlbillsDetailfun(this.form.id, type);
            })
            .catch(() => {
              this.saveLoading = false;
            });
        } else {
          if (this.generateStatus) {
            this.form.finStlBillsItemsList = this.tableData.map((item, index) => {
              if (item.currentStlCurCode == "CNY") {
                item.currentStlAmount = item.currentStlAmountRMB;
              } else {
                item.currentStlAmount = item.currentStlAmountUSD;
              }
              if (!this.form.id) {
                // delete item.businessType
                delete item.billDate;
                delete item.accountDc;
              }
              return item;
            });
          }
          finstlbillsSubmit(this.form)
            .then(res => {
              this.$message.success("操作成功");
              this.finstlbillsDetailfun(res.data.data.id, type);
            })
            .catch(() => {
              this.saveLoading = false;
            });
        }
      });
    },
    // 详情接口
    finstlbillsDetailfun(id, type) {
      this.activeName = "2";
      this.pageLoading = true;
      finstlbillsDetail(id)
        .then(res => {
          this.form = res.data.data;
          if (
            this.roleName.indexOf("admin") == -1
              ? this.roleName.indexOf("允许修改他人业务") == -1
                ? this.saberUserInfo.user_id != this.form.createUser
                : false
              : false
          ) {
            this.editPower = true;
          } else {
            this.editPower = false;
          }
          this.tableData = this.form.finStlBillsItemsList.map(item => {
            item.stlTtlAmountNet = Number(item.stlTtlAmount) - Number(item.stlTtlAmount) * (Number(item.taxRate) + Number(item.surchargeRate));
            item.currentStlAmountNet =
              Number(item.unsettledAmount) - Number(item.unsettledAmount) * (Number(item.taxRate) + Number(item.surchargeRate));
            if (item.curCode == "CNY") {
              this.$set(item, "currentInvoiceAmountRMB", item.currentInvoiceAmount);
              this.$set(item, "amountRMB", item.amount);
              this.$set(item, "amountNetRMB", item.amountNet);
              this.$set(item, "stlTtlAmountRMB", item.stlTtlAmount);
              this.$set(item, "stlTtlAmountNetRMB", item.stlTtlAmountNet);

              this.$set(item, "currentStlAmountNetRMB", item.currentStlAmountNet);
              this.$set(item, "currentStlAmountRMB", Number(item.currentStlAmount ? item.currentStlAmount : 0));
              this.$set(item, "currentStlAmountUSD", Number(0));
            } else {
              this.$set(item, "currentInvoiceAmountUSD", item.currentInvoiceAmount);
              this.$set(item, "amountUSD", item.amount);
              this.$set(item, "amountNetUSD", item.amountNet);
              this.$set(item, "stlTtlAmountNetUSD", item.stlTtlAmountNet);
              this.$set(item, "stlTtlAmountUSD", item.stlTtlAmount);

              this.$set(item, "currentStlAmountNetUSD", item.currentStlAmountNet);
              this.$set(item, "currentStlAmountUSD", Number(item.currentStlAmount ? item.currentStlAmount : 0));
              this.$set(item, "currentStlAmountRMB", Number(0));
            }

            if (item.srcIdInvoices) {
              this.settlementdistar = true;
            }
            return item;
          });
          if (type == "选定行") {
            this.finstlbillslistAccBillV1fun();
          }
          this.bcorpsbankListfun(); // 查银行数据
        })
        .finally(() => {
          setTimeout(() => {
            this.saveLoading = false;
          }, 500);
          this.pageLoading = false;
        });
    },
    // 结算按钮
    generateFinStlBillsfun(id, dc, type) {
      this.activeName = "2";
      let typeName = null;
      this.generateStatus = true;
      this.pageLoading = true;
      this.settlementType = dc;
      if (type == "CHK-D") {
        typeName = "收费结算";
      }
      if (type == "CHK-C") {
        typeName = "对账付款";
      }
      if (type == "FFSQ") {
        typeName = "付费结算";
      }
      if (type == "DCDD") {
        typeName = "收付相抵";
      }
      if (type == "XXFP") {
        typeName = "销项发票";
      }
      if (type == "GZXZ") {
        typeName = "其他结算";
      }
      generateFinStlBills({
        billId: id,
        dc: dc,
        type: typeName
      })
        .then(res => {
          res.data.data.finStlBillsItemsList = res.data.data.finStlBillsItemsList ? res.data.data.finStlBillsItemsList : [];
          this.form = res.data.data;
          this.tableData = this.form.finStlBillsItemsList.map(item => {
            item.stlTtlAmountNet = Number(item.stlTtlAmount) - Number(item.stlTtlAmount) * (Number(item.taxRate) + Number(item.surchargeRate));
            item.currentStlAmountNet =
              Number(item.unsettledAmount) - Number(item.unsettledAmount) * (Number(item.taxRate) + Number(item.surchargeRate));
            if (item.curCode == "CNY") {
              this.$set(item, "currentInvoiceAmountRMB", item.currentInvoiceAmount);
              this.$set(item, "amountRMB", item.amount);
              this.$set(item, "amountNetRMB", item.amountNet);
              this.$set(item, "stlTtlAmountRMB", item.stlTtlAmount);
              this.$set(item, "stlTtlAmountNetRMB", item.stlTtlAmountNet);

              this.$set(item, "currentStlAmountNetRMB", item.currentStlAmountNet);
              this.$set(item, "currentStlAmountRMB", Number(item.currentStlAmount ? item.currentStlAmount : 0));
              this.$set(item, "currentStlAmountUSD", Number(0));
            } else {
              this.$set(item, "currentInvoiceAmountUSD", item.currentInvoiceAmount);
              this.$set(item, "amountUSD", item.amount);
              this.$set(item, "amountNetUSD", item.amountNet);
              this.$set(item, "stlTtlAmountNetUSD", item.stlTtlAmountNet);
              this.$set(item, "stlTtlAmountUSD", item.stlTtlAmount);

              this.$set(item, "currentStlAmountNetUSD", item.currentStlAmountNet);
              this.$set(item, "currentStlAmountUSD", Number(item.currentStlAmount ? item.currentStlAmount : 0));
              this.$set(item, "currentStlAmountRMB", Number(0));
            }
            if (item.srcIdInvoices) {
              this.settlementdistar = true;
            }
            return item;
          });
          this.bcorpsbankListfun(); // 查银行数据
        })
        .finally(() => {
          this.pageLoading = false;
        });
    },
    // 重置条件
    ResetFilter() {
      this.form = {
        dc: null,
        billDate: dateFormat(new Date())
      };
    },
    // 弹窗选择
    retrievePopupsSelect(row) {
      // this.form = row
      this.$set(this.form, "corpId", row.id);
      this.$set(this.form, "corpCnName", row.cnName);
      this.$set(this.form, "corpEnName", row.enName);
      this.$set(this.form, "corpArgreementNo", row.enName);
      this.retrievePopupsType = false;
      this.bcorpsbankListfun();
      this.finstlbillslistAccBillV1fun('检索');
    },
    // 检索
    retrievalfun() {
      this.activeName = "1";
      // 判断是否有对账单位
      if (!this.form.corpId && (this.form.businessNo || this.form.accountNo || this.form.hblno || this.form.mblno)) {
        console.log("新接口");
        this.finstlbillslistAccBillByCorpfun();
      } else {
        if (!this.form.corpId) {
          return this.$message.warning("请填写对账单位");
        }
        console.log("原来的接口");
        this.finstlbillslistAccBillV1fun('检索');
      }
    },
    // 检索弹窗数据
    finstlbillslistAccBillByCorpfun() {
      let obj = {};
      obj.type = "2";
      obj.curCode = this.form.curCode; // 币别
      obj.dc = this.form.dc; // 收付 D=收 C=付
      obj.accBillNo = this.form.accountNo; // 账单编号  ACCT NO
      obj.billNo = this.form.businessNo; // 单据编号  JOB NO
      obj.mblno = this.form.mblno; // MB/L NO
      obj.hblno = this.form.hblno; // HB/L NO
      obj.queryAmount = this.form.queryAmount; // 查询金额
      obj.businessType = this.form.businessTypes; // 业务类型
      obj.feeCnName = this.form.feeCnName;
      obj.vesselCnName = this.form.vesselCnName; // 中文船名
      obj.receivableAdvance = this.form.receivableAdvance; // 预收帐款
      obj.voyageNo = this.form.voyageNo; // 航次
      obj.signforDateList = this.form.signforDateList; // 签收日期
      obj.auditStatus = "0";
      obj.businessDateStart = this.form.businessDateStart; // 业务开始日期
      obj.businessDateEnd = this.form.businessDateEnd; // 业务开始日期
      finstlbillslistAccBillByCorp(obj).then(res => {
        this.retrievePopupsType = true;
        this.retrievePopupsData = res.data.data;
      });
    },
    // 检索接口
    finstlbillslistAccBillV1fun(type) {
      // 对账单位
      if (!this.form.corpId) {
        this.$message.warning("请选择对账单位");
        return;
      }
      let obj = {};
      obj.type = "2";
      obj.curCode = this.form.curCode; // 币别
      obj.dc = this.form.dc; // 收付 D=收 C=付
      obj.accBillNo = this.form.accountNo; // 账单编号  ACCT NO
      obj.billNo = this.form.businessNo; // 单据编号  JOB NO
      obj.mblno = this.form.mblno; // MB/L NO
      obj.hblno = this.form.hblno; // HB/L NO
      obj.queryAmount = this.form.queryAmount; // 查询金额
      obj.businessType = this.form.businessTypes; // 业务类型
      obj.feeCnName = this.form.feeCnName;
      obj.vesselCnName = this.form.vesselCnName; // 中文船名
      obj.receivableAdvance = this.form.receivableAdvance; // 预收帐款
      obj.voyageNo = this.form.voyageNo; // 航次
      obj.signforDateList = this.form.signforDateList; // 签收日期
      obj.auditStatus = "0";
      obj.businessDateStart = this.form.businessDateStart; // 业务开始日期
      obj.businessDateEnd = this.form.businessDateEnd; // 业务开始日期
      // 判断是否有对账单号
      if (this.form.checkNo) {
        obj.corpId = this.form.corpId; // 结算单位
        obj.checkNo = this.form.checkNo; // CHK NO 对账单号
        finstlbillsGetByDetail(obj).then(res => {
          let arr = res.data.data.finStlBillsItemsList.map(item => {
            delete item.id;
            if (item.curCode == "CNY") {
              // 发票
              this.$set(item, "currentInvoiceAmountRMB", item.currentInvoiceAmount);
              // 应结算金额
              this.$set(item, "amountRMB", item.amount);
              // 已结算金额
              this.$set(item, "stlTtlAmountRMB", item.stlTtlAmount);
              if (item.dc == "D") {
                // 本次金额
                this.$set(item, "currentStlAmountRMB", Number(item.currentStlAmount ? item.currentStlAmount : 0));
              } else {
                // 本次金额
                this.$set(item, "currentStlAmountRMB", Number(item.appliedCurrentStlAmount ? item.appliedCurrentStlAmount : 0));
              }
              this.$set(item, "currentStlAmountUSD", Number(0));
            } else {
              // 发票
              this.$set(item, "currentInvoiceAmountUSD", item.currentInvoiceAmount);
              // 应结算金额
              this.$set(item, "amountUSD", item.amount);
              // 已结算金额
              this.$set(item, "stlTtlAmountUSD", item.stlTtlAmount);
              // 本次金额
              if (item.dc == "D") {
                // 本次金额
                this.$set(item, "currentStlAmountUSD", Number(item.currentStlAmount ? item.currentStlAmount : 0));
              } else {
                // 本次金额
                this.$set(item, "currentStlAmountUSD", Number(item.appliedCurrentStlAmount ? item.appliedCurrentStlAmount : 0));
              }
              this.$set(item, "currentStlAmountRMB", Number(0));
            }
            return item;
          });
          if (type == "追加") {
            // let a = [...this.queryData, ...arr];
            // this.queryData = a.filter((obj, index) => {
            //   return (
            //     a.findIndex(elem => {
            //       return elem.accBillNo === obj.accBillNo;
            //     }) === index
            //   );
            // });
            this.queryData = [];
            for (let item of arr) {
              if (this.tableData.filter(row => row.accBillNo == item.accBillNo).length == 0) {
                this.queryData.push(item);
              }
            }
          } else {
            // 获取有id 的数据
            const itemsWithId = this.queryData.filter(item => item.hasOwnProperty("id"));
            let arrIds = itemsWithId.map(item => item.id); // 获取id 数据
            // 有id 的处理
            if (itemsWithId.length != 0) {
              finstlbillsitemsRemove(arrIds.join(",")).then(res => {
                this.$message.success("操作成功");
              });
            }
            // if (arr.length == 0) {
            //   this.$message.warning("当前检索暂无数据！");
            // }
            this.queryData = [];
            for (let item of arr) {
              if (this.tableData.filter(row => row.accBillNo == item.accBillNo).length == 0) {
                this.queryData.push(item);
              }
            }
            if (this.queryData.length == 0&&type=='检索') {
              this.$message.warning("当前检索暂无数据！");
            }
          }
        });
      } else {
        obj.corpCnName = this.form.corpId; // 结算单位
        obj.checkBillNo = this.form.checkNo; // CHK NO 对账单号
        finstlbillslistAccBillV1(obj).then(res => {
          let arr = res.data.data.map((item, index) => {
            item.accBillId = item.id;
            delete item.id;
            // 账单编号
            item.accBillNo = item.billNo;
            item.currentStlCurCode = item.curCode; // 币别
            item.currentStlExrate = item.exrate;
            // isCleared
            item.lineNo = Number(index) + 1;
            item.pType = item.businessType;
            item.billNo = item.businessBillDivideNo ? item.businessBillDivideNo : item.businessBillNo;
            item.accDate = item.billDate;
            item.dc = item.accountDc; // 收付
            if (item.curCode == "CNY") {
              // 发票
              this.$set(item, "currentInvoiceAmountRMB", item.currentInvoiceAmount);
              // 应结算金额
              this.$set(item, "amountRMB", item.amount);
              // 已结算金额
              this.$set(item, "stlTtlAmountRMB", item.stlTtlAmount);
              // 本次金额
              if (item.dc == "D") {
                // 本次金额
                this.$set(item, "currentStlAmountRMB", Number(item.reconciliationCurrentAmount ? item.reconciliationCurrentAmount : 0));
              } else {
                // 本次金额
                this.$set(item, "currentStlAmountRMB", Number(item.reconciliationCurrentAmount ? item.reconciliationCurrentAmount : 0));
              }
              this.$set(item, "currentStlAmountUSD", Number(0));
            } else {
              // 发票
              this.$set(item, "currentInvoiceAmountUSD", item.currentInvoiceAmount);
              // 应结算金额
              this.$set(item, "amountUSD", item.amount);
              // 已结算金额
              this.$set(item, "stlTtlAmountUSD", item.stlTtlAmount);
              // 本次金额
              if (item.dc == "D") {
                // 本次金额
                this.$set(item, "currentStlAmountUSD", Number(item.reconciliationCurrentAmount ? item.reconciliationCurrentAmount : 0));
              } else {
                // 本次金额
                this.$set(item, "currentStlAmountUSD", Number(item.reconciliationCurrentAmount ? item.reconciliationCurrentAmount : 0));
              }
              this.$set(item, "currentStlAmountRMB", Number(0));
            }
            return item;
          });

          if (type == "追加") {
            // let a = [...this.queryData, ...arr];
            // this.queryData = a.filter((obj, index) => {
            //   return (
            //     a.findIndex(elem => {
            //       return elem.accBillNo === obj.accBillNo;
            //     }) === index
            //   );
            // });
            this.queryData = [];
            for (let item of arr) {
              if (this.tableData.filter(row => row.accBillNo == item.accBillNo).length == 0) {
                this.queryData.push(item);
              }
            }
          } else {
            // 获取有id 的数据
            const itemsWithId = this.queryData.filter(item => item.hasOwnProperty("id"));
            let arrIds = itemsWithId.map(item => item.id); // 获取id 数据
            // 有id 的处理
            if (itemsWithId.length != 0) {
              finstlbillsitemsRemove(arrIds.join(",")).then(res => {
                this.$message.success("操作成功");
              });
            }
            // if (arr.length == 0) {
            //   this.$message.warning("当前检索暂无数据！");
            // }
            this.queryData = [];
            for (let item of arr) {
              if (this.tableData.filter(row => row.accBillNo == item.accBillNo).length == 0) {
                this.queryData.push(item);
              }
            }
            if (this.queryData.length == 0&&type=='检索') {
              this.$message.warning("当前检索暂无数据！");
            }
          }
        });
      }
    },
    // 结算确认
    finstlbillsConfirmSettlementfun() {
      this.pageLoading = true;
      this.form.businessDateStart = this.form.businessDateStart ? this.form.businessDateStart.slice(0, 10) + " 00:00:00" : null; // 财务开始日期
      this.form.businessDateEnd = this.form.businessDateEnd ? this.form.businessDateEnd.slice(0, 10) + " 00:00:00" : null; // 财务开始日期
      this.form.billDate = this.form.billDate ? this.form.billDate.slice(0, 10) + " 00:00:00" : null;
      this.form.auditDateTo = this.form.auditDateTo ? this.form.auditDateTo.slice(0, 10) + " 00:00:00" : null;

      (this.form.url = "/iosBasicData/ComputationCenter/index"), (this.form.pageStatus = "this.$store.getters.SettlementCenterF");
      this.form.pageLabel = "结算中心(F)";
      finstlbillsConfirmSettlement(this.form)
        .then(res => {
          this.$message.success("操作成功");
          this.finstlbillsDetailfun(res.data.data.id);
          this.editSave = true;
        })
        .finally(() => {
          this.pageLoading = false;
          this.saveLoading = false;
        });
    },
    // 生成凭证
    generateVoucherfun() {
      this.$confirm("确定要生成凭证?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.pageLoading = true;
        this.form.businessDateStart = this.form.businessDateStart ? this.form.businessDateStart.slice(0, 10) + " 00:00:00" : null; // 财务开始日期
        this.form.businessDateEnd = this.form.businessDateEnd ? this.form.businessDateEnd.slice(0, 10) + " 00:00:00" : null; // 财务开始日期
        this.form.billDate = this.form.billDate ? this.form.billDate.slice(0, 10) + " 00:00:00" : null;
        this.form.auditDateTo = this.form.auditDateTo ? this.form.auditDateTo.slice(0, 10) + " 00:00:00" : null;
        finstlbillsGenerateVoucher(this.form)
          .then(res => {
            this.$message.success("操作成功");
            this.finstlbillsDetailfun(this.form.id);
          })
          .finally(() => {
            this.pageLoading = false;
          });
      });
    },
    // 结算撤销
    finstlbillsRevokeSettlementfun() {
      this.$confirm("确定进行撤销对账操作?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.pageLoading = true;
        this.form.businessDateStart = this.form.businessDateStart ? this.form.businessDateStart.slice(0, 10) + " 00:00:00" : null; // 财务开始日期
        this.form.businessDateEnd = this.form.businessDateEnd ? this.form.businessDateEnd.slice(0, 10) + " 00:00:00" : null; // 财务开始日期
        this.form.billDate = this.form.billDate ? this.form.billDate.slice(0, 10) + " 00:00:00" : null;
        this.form.auditDateTo = this.form.auditDateTo ? this.form.auditDateTo.slice(0, 10) + " 00:00:00" : null;
        finstlbillsRevokeSettlement(this.form)
          .then(res => {
            this.$message.success("操作成功");
            this.finstlbillsDetailfun(res.data.data.id);
          })
          .finally(() => {
            this.pageLoading = false;
            this.saveLoading = false;
          });
      });
    },
    // 确认选定行
    SelectedRows() {
      this.editCustomer("选定行");
    },
    addSelectionChange(list) {
      this.amountSubSum = 0;
      this.amountDSubSum = 0;
      this.amountCSubSum = 0;
      this.amountSubUsdSum = 0;
      this.amountDSubUsdSum = 0;
      this.amountCSubUsdSum = 0;
      if (list.length) {
        list.forEach(e => {
          console.log(e.accountDc);
          if (e.dc == "D") {
            this.amountDSubSum += Number(e.currentStlAmountRMB ? e.currentStlAmountRMB : 0);
            this.amountDSubUsdSum += Number(e.currentStlAmountUSD ? e.currentStlAmountUSD : 0);
          }
          if (e.dc == "C") {
            this.amountCSubSum += Number(e.currentStlAmountRMB ? e.currentStlAmountRMB : 0);
            this.amountCSubUsdSum += Number(e.currentStlAmountUSD ? e.currentStlAmountUSD : 0);
          }
        });
      }
      this.amountSubSum = Number(this.amountDSubSum - this.amountCSubSum);
      this.amountSubUsdSum = Number(this.amountDSubUsdSum - this.amountCSubUsdSum);
      this.addData = list;
    },
    // 下面表格多选
    handleSelectionChange(list) {
      this.amountSubSum = 0;
      this.amountDSubSum = 0;
      this.amountCSubSum = 0;
      this.amountSubUsdSum = 0;
      this.amountDSubUsdSum = 0;
      this.amountCSubUsdSum = 0;
      if (list.length) {
        list.forEach(e => {
          if (e.dc == "D") {
            this.amountDSubSum += Number(e.currentStlAmountRMB ? e.currentStlAmountRMB : 0);
            this.amountDSubUsdSum += Number(e.currentStlAmountUSD ? e.currentStlAmountUSD : 0);
          }
          if (e.dc == "C") {
            this.amountCSubSum += Number(e.currentStlAmountRMB ? e.currentStlAmountRMB : 0);
            this.amountCSubUsdSum += Number(e.currentStlAmountUSD ? e.currentStlAmountUSD : 0);
          }
        });
      }
      this.amountSubSum = Number(this.amountDSubSum - this.amountCSubSum);
      this.amountSubUsdSum = Number(this.amountDSubUsdSum - this.amountCSubUsdSum);
      this.handleSelectionData = list;
    },
    //返回列表
    backToList() {
      this.$emit("goBack");
    },
    // 请求的接口
    // 获取币别数据
    getRateListfun(cnName) {
      getRateList({ current: 1, size: 10, cnName }).then(res => {
        this.curCodeData = res.data.data.records;
      });
    },
    // 获取结算单位数据
    corpBcorpsListfun(cnName) {
      getBcorpslistByType(1, 10, { cnName }).then(res => {
        this.corpData = res.data.data.records;
      });
    },
    // 获取银行数据
    bcorpsbankListfun() {
      bcorpsbankList(1, 50, { pid: this.form.corpId }).then(res => {
        this.bankData = res.data.data.records.map(item => {
          item.accountBankNo = item.accountBank + " - " + item.accountNo;
          return item;
        });
        if (this.bankData.length > 0) {
          this.$set(this.form, "bankId", res.data.data.records[0].id);
          this.$set(this.form, "bankAccountName", res.data.data.records[0].accountName);
          this.$set(this.form, "bankAccountBank", res.data.data.records[0].accountBank);
          this.$set(this.form, "bankAccountNo", res.data.data.records[0].accountNo);
        }
        if (this.bankData.length == 0) {
          this.$set(this.form, "bankId", null);
          this.$set(this.form, "bankAccountName", null);
          this.$set(this.form, "bankAccountBank", null);
          this.$set(this.form, "bankAccountNo", null);
        }
      });
    },
    // 预览报表
    handleReportPreview(url, data) {
      console.log(url, 1670);
      console.log(data, 1671);
      Stimulsoft.Base.StiLicense.key =
        "6vJhGtLLLz2GNviWmUTrhSqnOItdDwjBylQzQcAOiHn0s4gy0Fr5YoUZ9V00Y0igCSFQzwEqYBh/N77k4f0fWXTHW5rqeBNLkaurJDenJ9o97TyqHs9HfvINK18Uwzsc/bG01Rq+x3H3Rf+g7AY92gvWmp7VA2Uxa30Q97f61siWz2dE5kdBVcCnSFzC6awE74JzDcJMj8OuxplqB1CYcpoPcOjKy1PiATlC3UsBaLEXsok1xxtRMQ283r282tkh8XQitsxtTczAJBxijuJNfziYhci2jResWXK51ygOOEbVAxmpflujkJ8oEVHkOA/CjX6bGx05pNZ6oSIu9H8deF94MyqIwcdeirCe60GbIQByQtLimfxbIZnO35X3fs/94av0ODfELqrQEpLrpU6FNeHttvlMc5UVrT4K+8lPbqR8Hq0PFWmFrbVIYSi7tAVFMMe2D1C59NWyLu3AkrD3No7YhLVh7LV0Tttr/8FrcZ8xirBPcMZCIGrRIesrHxOsZH2V8t/t0GXCnLLAWX+TNvdNXkB8cF2y9ZXf1enI064yE5dwMs2fQ0yOUG/xornE";
      // Stimulsoft.Base.StiLicense.Key = '6vJhGtLLLz2GNviWmUTrhSqnOItdDwjBylQzQcAOiHkcgIvwL0jnpsDqRpWg5FI5kt2G7A0tYIcUygBh1sPs7plofUOqPB1a4HBIXJB621mau2oiAIj+ysU7gKUXfjn/D5BocmduNB+ZMiDGPxFrAp3PoD0nYNkkWh8r7gBZ1v/JZSXGE3bQDrCQCNSy6mgby+iFAMV8/PuZ1z77U+Xz3fkpbm6MYQXYp3cQooLGLUti7k1TFWrnawT0iEEDJ2iRcU9wLqn2g9UiWesEZtKwI/UmEI2T7nv5NbgV+CHguu6QU4WWzFpIgW+3LUnKCT/vCDY+ymzgycw9A9+HFSzARiPzgOaAuQYrFDpzhXV+ZeX31AxWlnzjDWqpfluygSNPtGul5gyNt2CEoJD1Yom0VN9fvRonYsMsimkFFx2AwyVpPcs+JfVBtpPbTcZscnzUdmiIvxv8Gcin6sNSibM6in/uUKFt3bVgW/XeMYa7MLGF53kvBSwi78poUDigA2n12SmghLR0AHxyEDIgZGOTbNI33GWu7ZsPBeUdGu55R8w='
      Stimulsoft.Base.Localization.StiLocalization.addLocalizationFile("/reports/stimulsoft/Localization/zh-CHS.xml", true, "zh-CHS");
      Stimulsoft.Base.Localization.StiLocalization.setLocalizationFile("/reports/stimulsoft/Localization/zh-CHS.xml");
      // 工具栏
      var options = new Stimulsoft.Viewer.StiViewerOptions();
      options.height = "100%";
      options.appearance.scrollbarsMode = true; // 滚动条模式
      options.toolbar.showDesignButton = false; // 显示设计按钮
      options.toolbar.showAboutButton = false; // 显示关于按钮
      options.toolbar.showResourcesButton = false; // 显示资源按钮
      options.toolbar.showFullScreenButton = false; // 显示全屏按钮
      options.toolbar.showOpenButton = false; // 显示打开按钮
      options.appearance.showTooltips = false; // 显示工具提示
      options.appearance.showDialogsHelp = false; // 显示对话框帮助
      options.exports.showExportToDocument = false; // 显示导出到文档
      options.toolbar.showParametersButton = true; // 显示参数按钮
      options.appearance.bookmarksPrint = true; // 书签打印
      // options.toolbar.showPrintButton = false // 打印按钮是否显示   下面直接自定义控制打印弹窗是否开启

      // printDestination 参数：用于指定报表打印的目标位置，可以是打印机、PDF 文件或者直接打印到浏览器等。
      // Stimulsoft.Viewer.StiPrintDestination.Direct：表示直接打印到打印机，即将报表内容直接发送至打印机进行打印。
      // 通过设置不同的 printDestination 参数，你可以控制报表打印的行为，例如是直接打印到打印机，还是生成 PDF 文件，或者直接在浏览器中预览打印内容等。
      options.toolbar.printDestination = Stimulsoft.Viewer.StiPrintDestination.Direct;
      // htmlRenderMode html渲染模式
      options.appearance.htmlRenderMode = Stimulsoft.Report.Export.StiHtmlExportMode.Table;
      // 是创建一个 Stimulsoft 报表查看器的实例的代码
      let viewer = new Stimulsoft.Viewer.StiViewer(options, "StiViewer", false);

      // 报表
      console.log("创建一个报表实例");
      console.log();
      let report = new window.Stimulsoft.Report.StiReport();

      // 加载文件
      console.log("从url加载报表");
      // report.loadFile("/reports/stimulsoft/demos/SimpleList.mrt");
      report.load(url);

      data.pageOne = "Page : 1 of 1";
      // 处理超长数据
      if (data.hshipperDetails) {
        var consignerIndex2 = data.hshipperDetails.indexOf("\n");
        for (let i = 0; i < 4; i++) {
          consignerIndex2 = data.hshipperDetails.indexOf("\n", consignerIndex2 + 1);
        }
        if (consignerIndex2 != -1) {
          var hshipperDetails = data.hshipperDetails.substring(consignerIndex2 + 2, data.hshipperDetails.length);
          data.hshipperDetails = data.hshipperDetails.substring(0, consignerIndex2) + " *";
          data.commodityDescr += "\n*" + hshipperDetails;
        }
      }

      if (data.hconsigneeDetails) {
        var consigneeIndex2 = data.hconsigneeDetails.indexOf("\n");
        for (let i = 0; i < 3; i++) {
          consigneeIndex2 = data.hconsigneeDetails.indexOf("\n", consigneeIndex2 + 1);
        }
        if (consigneeIndex2 != -1) {
          var hconsigneeDetails = data.hconsigneeDetails.substring(consigneeIndex2 + 2, data.hconsigneeDetails.length);
          data.hconsigneeDetails = data.hconsigneeDetails.substring(0, consigneeIndex2) + " **";
          data.commodityDescr += "\n**" + hconsigneeDetails;
        }
      }

      if (data.hnotifyDetails) {
        var notifierIndex2 = data.hnotifyDetails.indexOf("\n");
        for (let i = 0; i < 3; i++) {
          notifierIndex2 = data.hnotifyDetails.indexOf("\n", notifierIndex2 + 1);
        }
        if (notifierIndex2 != -1) {
          var hnotifyDetails = data.hnotifyDetails.substring(notifierIndex2 + 2, data.hnotifyDetails.length);
          data.hnotifyDetails = data.hnotifyDetails.substring(0, notifierIndex2) + " ***";
          data.commodityDescr += "\n***" + hnotifyDetails;
        }
      }

      // 处理箱号
      if (this.isPrintTheBoxNumber) {
        data.commodityDescr += "\n.\n.\n";
      }

      // PLACE & DATE OF ISSUE
      data.placeAndDateOfIssue = "";
      if (data.issueAt) {
        data.placeAndDateOfIssue += data.issueAt;
      }
      if (data.issueDate) {
        let date = new Date(data.issueDate.replace(/-/g, "/"));
        let yyyy = date.getFullYear();
        let mmmm = date.toDateString().split(" ")[1];
        let dd = date.getDate();
        data.placeAndDateOfIssue += ", " + dd + "-" + mmmm + "-" + yyyy;
      }

      // Total number of containers or packages received by the Carriers
      if (data.preContainersList) {
        let boxMap = new Map();
        for (let boxQuantity of data.preContainersList) {
          if (boxMap.get(boxQuantity.cntrTypeCode)) {
            let v = boxMap.get(boxQuantity.cntrTypeCode);
            boxMap.set(boxQuantity.cntrTypeCode, v + boxQuantity.quantity);
          } else {
            boxMap.set(boxQuantity.cntrTypeCode, boxQuantity.quantity);
          }
        }
        let boxs = "";
        boxMap.forEach(function(value, key, map) {
          boxs += value + "x" + key + ", ";
        });
        boxs = boxs.substring(0, boxs.length - 2);

        data.boxQuantity = boxs + " CONTAINER(S) ONLY";
      }

      // Number of original B/Ls
      if (data.numberOfObl) {
        data.numberOfObl += " (" + data.numberOfOblDigit + ")";
      }

      if (data.commodityDescr) {
        var descriptionIndex2 = data.commodityDescr.indexOf("\n");
        for (let i = 0; i < 19; i++) {
          descriptionIndex2 = data.commodityDescr.indexOf("\n", descriptionIndex2 + 1);
        }
        if (descriptionIndex2 != -1) {
          data.pageOne = "Page : 1 of 2";
          data.pageTwo = "Page : 2 of 2";
          var extraLongText = data.commodityDescr.substring(descriptionIndex2 + 2, data.commodityDescr.length);
          data.commodityDescr = data.commodityDescr.substring(0, descriptionIndex2);
          data.extraLongTips = "** TO BE CONTINUED ON ATTACHED LIST **";
          data.extraLongText = extraLongText;
        }
      }

      // console.log(data.hshipperDetails, 'hshipperDetails2')

      // 创建一个 Stimulsoft 数据集（DataSet）的实例的代码
      var dataSet = new Stimulsoft.System.Data.DataSet("reportData");

      dataSet.readJson(data); // 用于将 JSON 格式的数据加载到数据集中。data 是包含报表数据的 JSON 对象。
      // 这是一个方法调用，用于在报表中注册数据源。参数 'reportData' 是数据源的名称，
      // 第二个 'reportData' 是数据源的别名，dataSet 则是之前创建的数据集实例
      report.regData("reportData", "reportData", dataSet);
      // 从模版和数据加载报表
      // loadReport(report, '', {})

      // 这是将报表对象指定给报表查看器的属性。viewer 是报表查看器的实例，而 report 是之前创建的报表对象。
      viewer.report = report;

      this.$refs.reportContainer.showContainer(
        () => {
          setTimeout(() => {
            viewer.renderHtml("reportContainer");
            this.createViewerButtons(viewer);
          }, 50);
        },
        () => {}
      );
      console.log("加载成功完成!");
    },
    createViewerButtons(viewer) {
      viewer.jsObject.collections.images["myClose.png"] =
        "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAA0ElEQVQ4ja3TO05CQRQG4A8iOwAbtYWETndAaecK7NwCKmETtJZsSBNLobEz8ZFIJQ0UnOGSm3DnYviTybzO/895DQXGWGCVGQuMEqkRcwcfuMOLalziCaf4TIe9UG9nyMJmFRzNGoRK1BU4xxx9G7cfwostciGk+x8MqgySwDXe4tU53hVV+MNtTmAoX84JGv9NYgrHyR6DV8wUSW7hItZLm36ZVoVQxsFJLOMsPOrH/h7dQwR2cdxOTEn8DtUbPGc4V2H7Vb4Yqfedf/GYSGt8VUmxgyfuBAAAAABJRU5ErkJggg==";
      const closeBtn = viewer.jsObject.SmallButton("closeBtn", "关闭", "myClose.png");
      // 增加打印弹窗配置
      const printBtn = viewer.jsObject.SmallButton("printBtn", "打印报表", "myClose.png");
      // console.log(viewer.jsObject.print(),'1013')
      // 获取 关闭按钮的dom元素位置
      const toolbarTable = viewer.jsObject.controls.toolbar.firstChild.firstChild;
      const buttonsTable = toolbarTable.rows[0].lastChild.lastChild;
      const userButtonCell = buttonsTable.rows[0].insertCell(0);
      // 获取打印按钮的位置
      const buttonsTablePrint = toolbarTable.rows[0].childNodes[0].lastChild; // 打印按钮
      const userButtonPrint = buttonsTablePrint.rows[0].childNodes[0]; // 打印按钮dom位置

      userButtonPrint.addEventListener("click", event => {
        console.log("打印点击");
        // event.preventDefault()
      });
      userButtonPrint.addEventListener("mouseover", event => {
        console.log("移入打印按钮");
        console.log(event, 1035);
      });

      userButtonCell.className = "stiJsViewerClearAllStyles";
      userButtonCell.appendChild(closeBtn); // 添加关闭节点

      // userButtonPrint.prepend(printBtn) // 在 printBtn 节点里最前面增加一个子级节点

      let that = this;
      // 关闭按钮的监听点击
      closeBtn.action = function() {
        console.log(that.$refs.ReportContainer, "1022");
        if (that.$refs.reportContainer) that.$refs.reportContainer.hideContainer();
      };

      // // // 打印按钮监听
      // printBtn.action = (e)=>{
      //     console.log('打印')
      //     window.print()
      // }
    }
  }
};
</script>

<style scoped>
::v-deep.el-form-item {
  margin-bottom: 0;
}

.bottomFlex {
  display: flex;
  align-items: center;
}

.weightfont {
  font-size: 20px;
  font-weight: bold;
}

.weightnum {
  font-size: 18px;
  font-weight: 500;
}

/deep/.el-dialog .el-dialog__body {
  padding: 0px 20px;
}
::v-deep .el-form-item__error {
  display: none;
}
</style>
