<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="120px"
    >
      <el-form-item label="收款单编号" prop="receiptNo">
        <el-input
          v-model="queryParams.receiptNo"
          placeholder="收款单编号"
          clearable
        />
      </el-form-item>
      <el-form-item label="订单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="订单号"
          clearable
        />
      </el-form-item>
      <el-form-item label="提单号" prop="tidanNo">
        <el-input
          v-model="queryParams.tidanNo"
          placeholder="提单号"
          clearable
        />
      </el-form-item>
      <el-form-item label="创建人" prop="creator">
        <el-input
          v-model="queryParams.creator"
          placeholder="创建人"
          clearable
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createDate">
        <el-date-picker
          v-model="queryParams.sDate1"
          type="date"
          style="width: 150px"
          value-format="yyyy-MM-dd"
          clearable
          placeholder="请输起始月"
        />
        <el-date-picker
          v-model="queryParams.eDate1"
          type="date"
          style="width: 150px"
          value-format="yyyy-MM-dd"
          clearable
          placeholder="请输截止月"
        />
      </el-form-item>
      <el-form-item label="提交审批时间" prop="spDate">
        <el-date-picker
          v-model="queryParams.sDate2"
          type="date"
          style="width: 150px"
          value-format="yyyy-MM-dd"
          clearable
          placeholder="请输起始月"
        />
        <el-date-picker
          v-model="queryParams.eDate2"
          type="date"
          style="width: 150px"
          value-format="yyyy-MM-dd"
          clearable
          placeholder="请输截止月"
        />
      </el-form-item>
      <el-form-item label="审批通过时间" prop="tgDate">
        <el-date-picker
          v-model="queryParams.sDate3"
          type="date"
          style="width: 150px"
          value-format="yyyy-MM-dd"
          clearable
          placeholder="请输起始月"
        />
        <el-date-picker
          v-model="queryParams.eDate3"
          type="date"
          style="width: 150px"
          value-format="yyyy-MM-dd"
          clearable
          placeholder="请输截止月"
        />
      </el-form-item>
      <el-form-item label="实收日期" prop="ssDate">
        <el-date-picker
          v-model="queryParams.sDate4"
          type="date"
          style="width: 150px"
          value-format="yyyy-MM-dd"
          clearable
          placeholder="请输起始月"
        />
        <el-date-picker
          v-model="queryParams.eDate4"
          type="date"
          style="width: 150px"
          value-format="yyyy-MM-dd"
          clearable
          placeholder="请输截止月"
        />
      </el-form-item>
      <el-form-item :label="$t('收款账户')" prop="accountNo">
        <el-select
          filterable
          clear
          v-model="queryParams.accountNo"
          :placeholder="$t('请选择收款账户')"
          style="width: 220px"
          v-el-select-loadmore="loadmore"
        >
          <el-option
            v-for="item in bankData"
            :key="item.id"
            :label="item.baAccountName"
            :value="item.baAccountName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="creator">
        <el-select
          v-model="queryParams.status"
          clearable
          style="width: 100px"
        >
        <el-option
            v-for="dict in getDictDatas(DICT_TYPE.RECEIPT_ITEM_STATE)"
            :key="dict.value"
            :label="isChinese ? dict.label : dict.labelEn"
            :value="parseInt(dict.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        <el-button type="primary" @click="handleAdd">
          {{ $t("批量提交审核") }}</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5"> </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <el-table
      ref="multipleTable"
      v-loading="loading"
      :data="list"
      border
      row-key="id"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" :reserve-selection="true">
      </el-table-column>
      <el-table-column
        :label="$t('序号')"
        type="index"
        align="center"
        width="50"
      ></el-table-column>
      <el-table-column
        :label="$t('收款单编号')"
        align="center"
        prop="receiptNo"
      >
        <template slot-scope="scope">
          <span style="color: #1890ff" @click="paymentDetail1(scope.row)">{{
            scope.row.receiptNo
          }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('订单编号')" align="center" prop="orderNo">
        <template slot-scope="scope">
          <span style="color: #1890ff" @click="paymentDetail2(scope.row)">{{
            scope.row.orderNo
          }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('提单编号')" align="center" prop="tidanNo">
        <template slot-scope="scope">
          <span style="color: #1890ff" @click="paymentDetail3(scope.row)">{{
            scope.row.tidanNo
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('收款账户')"
        align="center"
        prop="accountName"
      />
      <el-table-column :label="$t('实收金额')" align="center" prop="amount" />
      <el-table-column :label="$t('实收币种')" align="center" prop="marks">
        <template slot-scope="scope">
          {{ getCurrencyLabel(scope.row.currencyId) }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('汇率')" align="center" prop="rate" />
      <el-table-column align="center" prop="writeOffAmount">
        <template #header>
          {{ $t("兑核销基准金额") }}({{ getCurrencyLabel(showCurrencyId) }})
        </template>
      </el-table-column>
      <el-table-column :label="$t('实收日期')" align="center" prop="amountDate">
      </el-table-column>
      <el-table-column :label="$t('水单号')" align="center" prop="billNo" />
      <el-table-column :label="$t('水单附件')" align="center" prop="attr">
        <template slot-scope="scope" v-if="scope.row.attrList">
          <div v-for="(v, i) in scope.row.attrList" :key="i">
            <el-link :href="v.url" type="primary" target="_blank">{{
              v.name
            }}</el-link>
          </div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('状态')" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag
            :type="DICT_TYPE.RECEIPT_ITEM_STATE"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column :label="$t('创建人')" align="center" prop="creator" />
      <el-table-column
        :label="$t('创建时间')"
        align="center"
        prop="createTime"
      />
      <el-table-column
        :label="$t('提交审批人')"
        align="center"
        prop="createBpm"
      />
      <el-table-column
        :label="$t('提交审批时间')"
        align="center"
        prop="createTimeBpm"
      />
      <el-table-column
        :label="$t('审批通过时间')"
        align="center"
        prop="updateTimeBpm"
      />
      <el-table-column :label="$t('操作')" align="center" width="200">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status == 0"
            v-hasPermi="['ecw:payment:detail:delete']"
            type="text"
            @click="deleteClick(scope.row)"
            >{{ $t("删除") }}</el-button
          >
          <el-button
            type="text"
            @click="detailClick(scope.row)"
            v-hasPermi="['ecw:payment:detail:detail']"
            >{{ $t("详情") }}</el-button
          >
          <el-button
            v-if="scope.row.status == 0"
            type="text"
            @click="
              $router.push(
                `bankDetail?id=` +
                  scope.row.receiptId +
                  `&bankId=` +
                  scope.row.id
              )
            "
            v-hasPermi="['ecw:payment:detail:writeOff']"
            >{{ $t("提交") }}</el-button
          >
          <el-button
            v-if="scope.row.status == 1"
            type="text"
            @click="showCancel(scope.$index)"
            v-hasPermi="['ecw:payment:detail:cancelWriteOff']"
            >{{ $t("反核销") }}</el-button
          >

          <el-button
            v-if="scope.row.status == 0"
            type="text"
            @click="editClick(scope.row)"
            v-hasPermi="['ecw:payment:detail:bankEdit']"
            >{{ $t("编辑") }}</el-button
          >
          <el-button
            v-if="scope.row.status == 2"
            type="text"
            @click="cancelClick(scope.$index, 1)"
            v-hasPermi="['ecw:payment:detail:cancelDetailApproval']"
            >{{ $t("取消审核") }}</el-button
          >
          <el-button
            v-if="scope.row.status == 3"
            type="text"
            @click="cancelClick(scope.$index, 2)"
            v-hasPermi="['ecw:payment:detail:cancelWriteOffNo']"
            >{{ $t("取消反核销审核") }}</el-button
          >
          <el-button
            v-if="scope.row.status == 3 || scope.row.status == 2"
            type="text"
            @click="
              $router.push(`/bpm/process-instance/detail?id=` + scope.row.bmpId)
            "
            v-hasPermi="['ecw:payment:detail:approval']"
            >{{ $t("审核详情") }}</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog :title="cancelTitle" :visible.sync="cancelShow" width="30%">
      <div class="cancel_content">
        <span>{{ $t("申请理由") }}</span>
        <el-input
          type="textarea"
          :rows="6"
          v-model="cancelReason"
          :placeholder="$t('请输入取消理由')"
        ></el-input>
      </div>
      <span slot="footer" class="dialog-footers">
        <el-button type="primary" @click="cancelWriteOffClick()">{{
          $t("提交")
        }}</el-button>
        <el-button @click="cancelShow = false">{{ $t("取消") }}</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :title="$t('收款单银行实收明细反核销-未提交')"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <div class="cancel_content">
        <span>{{ $t("申请理由") }}</span>
        <el-input
          type="textarea"
          :rows="6"
          v-model="reason"
          :placeholder="$t('请输入理由')"
        ></el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="verificationCancelClick()">{{
          $t("提交反核销")
        }}</el-button>
        <el-button @click="dialogVisible = false">{{ $t("取消") }}</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :visible.sync="openAddDialog"
      :title="dialogTitle"
      width="50%"
      append-to-body
    >
      <el-form ref="form" :model="form" label-width="250px">
        <el-form-item :label="$t('收款单号')">
          <el-input
            disabled
            v-model="form.receipt_no"
            style="width: 220px"
          ></el-input>
        </el-form-item>

        <el-form-item :label="$t('剩余应收金额')">
          <span> {{ form.syValue }}</span>
        </el-form-item>
        <el-form-item :label="$t('收款账户')" prop="accountNo">
          <el-select
            :disabled="isEdit"
            filterable
            clear
            v-model="form.accountId"
            :placeholder="$t('请选择收款账户')"
            style="width: 250px"
            @change="accountChange"
            v-el-select-loadmore="loadmore"
          >
            <el-option
              v-for="item in bankData"
              :key="item.id"
              :label="item.baAccountName + '(' + item.baAccountNum + ')'"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('实收日期')" prop="amountDate">
          <el-date-picker
            :disabled="isEdit"
            v-model="form.amountDate"
            type="date"
            style="width: 150px"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>

        <el-form-item :label="$t('实收')" prop="amount">
          <el-input
            v-model="form.amount"
            :disabled="isEdit"
            style="width: 100px"
          ></el-input>

          <el-select
            v-model="form.currencyId"
            :disabled="isEdit"
            :placeholder="$t('请选择')"
            @change="(val) => currencyIdChange(val)"
          >
            <el-option
              v-for="item in currencyList"
              :key="item.id"
              :label="$i18n.locale == 'zh_CN' ? item.titleZh : item.titleEn"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item prop="rate">
          <template slot="label">
            <span
              :title="
                $t(
                  '实收币种与核销基准币种一样时,无需填写汇率,不一样需要填写汇率'
                )
              "
              >{{ $t("兑核销基准币种汇率") }}({{
                getCurrencyLabel(showCurrencyId)
              }})</span
            >
          </template>
          <el-input
            v-model="form.rate"
            :disabled="isEdit"
            style="width: 220px"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <template slot="label">
            {{ $t("兑核销基准币种金额") }}({{
              getCurrencyLabel(showCurrencyId)
            }})
          </template>
          <el-input
            :disabled="isEdit"
            v-model="form.writeOffAmount"
            style="width: 220px"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('水单附件')" prop="attr">
          <el-upload
            v-if="!isView"
            class="upload-demo"
            :action="uploadFileUrl"
            :headers="headers"
            :on-success="handleUploadSuccess"
            :before-upload="handleBeforeUpload"
            :on-error="handleUploadError"
            :before-remove="beforeRemove"
            :file-list="form.attr"
            multiple
          >
            <el-button size="small" type="primary">{{
              $t("上传附件")
            }}</el-button>
          </el-upload>
          <div v-else>
            <div v-for="(v, i) in form.attr" :key="i">
              <el-link :href="v.url" type="primary" target="_blank">{{
                v.name
              }}</el-link>
            </div>
          </div>
        </el-form-item>
        <el-form-item :label="$t('水单号')" prop="billNo">
          <el-input
            v-model="form.billNo"
            :disabled="isEdit"
            style="width: 220px"
          ></el-input>
        </el-form-item>
        <!--lanbm 2024-06-12 add-->
        <el-form-item :label="$t('创建人')" v-show="isEdit" prop="creator">
          <el-input
            v-model="form.creator"
            style="width: 220px"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('创建时间')" v-show="isEdit" prop="createTime">
          <el-input
            v-model="form.createTime"
            style="width: 220px"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('最后更新人')" v-show="isEdit" prop="updater">
          <el-input         
            v-model="form.updater"
            style="width: 220px"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('最后更新时间')" v-show="isEdit" prop="updateTime">
          <el-input
            v-model="form.updateTime"
            style="width: 220px"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('提交审批人')" v-show="isEdit" prop="createBpm">
          <el-input
            v-model="form.createBpm"
            style="width: 220px"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('审批通过时间')" v-show="isEdit" prop="updateTimeBpm">
          <el-input
            v-model="form.updateTimeBpm"
            style="width: 220px"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" v-show="!isEdit" @click="saveFrom">{{
          saveBtnText
        }}</el-button>
        <el-button @click="hiddenDialog">{{ $t("取消") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  
<script>
import { getPageList } from "@/api/report/bankReceiptDetail";
import { getReceivableItem2 } from "@/api/ecw/financial";
import Treeselect from "@riophae/vue-treeselect";
import "@/assets/styles/vue-treeselect.css";
import { getBankAccountPage } from "@/api/ecw/bankAccount";
import { getCurrencyPage } from "@/api/ecw/currency";
import { getToken } from "@/utils/auth";
import { getExchangeRatePage } from "@/api/ecw/exchangeRate";
import {
  deleteReceiptItem, //删除收款单明细
  updateReceiptItem,
  receiptItemCreate,
  financeReceiptItemWriteOff2,
  cancelFinanceReceiptApproval,
  cancelFinanceReceiptApprovalNo,
  cancelFinanceReceiptWriteOffNo,
  cancelFinanceReceiptWriteOff,
  financeReceiptItemWriteOffNo,
} from "@/api/ecw/financial";

//2024-05-14 银行收款明细列表
export default {
  name: "ReportBankReceiptDetailsIndex",
  components: {
    Treeselect,
  },
  data() {
    return {
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/app-api/file/upload",
      //上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      // 遮罩层
      loading: true,
      UpLoading: undefined,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      list: [],
      // 弹出层标题
      title: "",
      //是否显示弹出层
      open: false,
      form: {},
      dialogVisible: false,
      reason: "", //审核理由
      cancelShow: false,
      cancelTitle: "",
      cancelReason: "",
      cancelIndex: 0,
      selectIndex: 0,
      dialogTitle: this.$t("添加银行实收明细"),
      saveBtnText: this.$t("添加"),
      isView: false,
      openAddDialog: false,
      surplusData: [],
      addForm: {},
      detailed: [],
      deptData: [],
      deptArr: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        receiptNo: undefined, //收款单编号
        orderNo: undefined, //订单编号
        tidanNo: undefined, //提单编号
        sDate1: undefined,
        eDate1: undefined, //收款明细创建日期
        sDate2: undefined,
        eDate2: undefined, //提交审批日期
        sDate3: undefined,
        eDate3: undefined, //审批通过日期
        sDate4: undefined,
        eDate4: undefined, //实收日期
        creator: undefined, //创建人
        accountNo: undefined, //收款账号 lanbm 2024-06-12 add
        status:undefined,//审批状态 lanbm 2024-06-13 add
      },
      params: {
        page: 1,
        rows: 100,
      },
      currencyList: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      //选中数组
      ids: [],
      // 表单参数
      form: {},
      isEdit: false, //是否编辑
      bankData: [],
      codePage: {
        pageNo: 1,
        pageSize: 20,
      },
      pages: 1,
      rateList: [],
    };
  },
  async created() {
    await getBankAccountPage(this.codePage).then((res) => {
      this.bankData = res.data.list;
      this.pages = res.data.total / this.codePage.pageSize + 1;
    });

    // 获取汇率
    await getExchangeRatePage(this.params).then(
      (res) => (this.rateList = res.data.list)
    );

    //币种
    await getCurrencyPage(this.params).then(
      (res) => (this.currencyList = res.data.list)
    );
    this.getList();
  },
  computed: {
    showCurrencyId() {
      let fieldList = [];
      let groupList = [];
      this.list.map((element) => {
        if (fieldList.indexOf(element["currencyId"]) === -1) {
          fieldList.push(element["currencyId"]);
        }
      });
      for (let i = 0; i < fieldList.length; i++) {
        let arr = this.list.filter((element) => {
          return element["currencyId"] === fieldList[i];
        });
        groupList.push({
          currencyId: arr[0].currencyId,
          list: arr,
        });
      }
      if (groupList.length === 1) return groupList[0].currencyId;
      else return 1;
    },
  },
  watch: {
    "form.rate"() {
      this.setWriteOffAmount();
    },
  },
  methods: {
    isChinese() {
      //基础函数,判断系统显示语言是中文还是英文
      return this.$i18n.locale === "zh_CN";
    },
    // 懒加载
    loadmore() {
      this.codePage.pageNo++;
      // 大于页码不请求了
      if (this.codePage.pageNo > this.pages) {
        return;
      }
      this.getCodeList();
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 处理查询参数
      let params = { ...this.queryParams };
      // 执行查询
      getPageList(params).then((response) => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    currencyIdChange(val) {
      val = Number(val);
      let rate;
      if (val === this.showCurrencyId) {
        rate = 1;
      } else {
        rate = this.getRate(val, 1);
      }
      this.$set(this.form, "rate", rate);
      var sR = (rate * this.form.amount).toFixed(6);
      this.$set(this.form, "writeOffAmount", sR);
    },
    accountChange(val) {
      let data = this.bankData.find((item) => item.id == val);
      this.$set(this.form, "accountName", data.baAccountName || "");
      this.$set(this.form, "accountNo", data.baAccountNum || "");
      this.$set(this.form, "accountBankName", data.baBankName || "");
    },
    //获取汇率
    getRate(sourceCurrencyId, targetCurrencyId) {
      //let json1 = JSON.stringify(this.rateList);
      //alert(json1);
      let rate = this.rateList.find(
        (v) =>
          v.sourceCurrencyId === sourceCurrencyId &&
          v.targetCurrencyId === targetCurrencyId
      );
      if (rate) return rate.currencyRate;
      return "";
    },
    /** 表单重置 */
    reset() {
      this.queryParams = {
        pageNo: 1,
        pageSize: 10,
        receiptNo: undefined, //收款单编号
        orderNo: undefined, //订单编号
        tidanNo: undefined, //提单编号
        sDate1: undefined,
        eDate1: undefined, //收款明细创建日期
        sDate2: undefined,
        eDate2: undefined, //提交审批日期
        sDate3: undefined,
        eDate3: undefined, //审批通过日期
        creator: undefined, //创建人
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.reset();
    },
    hiddenDialog() {
      this.openAddDialog = false;
    },
    saveFrom() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.id) {
            const params = { ...this.form };
            /*
            params.attr &&
              (params.attr = params.attr.map((v) => v.url).join(","));
              */

            updateReceiptItem(params).then((res) => {
              this.$modal.msgSuccess(this.$t("修改成功"));
              this.openAddDialog = false;
              this.getList();
            });
            return;
          }
          const params = { ...this.form };
          params.attr &&
            (params.attr = params.attr.map((v) => v.url).join(","));
          params.receiptId = this.id;
          receiptItemCreate(params).then((res) => {
            this.$modal.msgSuccess(this.$t("新增成功"));
            this.openAddDialog = false;
            this.getList();
          });
        }
      });
    },
    //银行明细反核销
    verificationCancelClick() {
      if (!this.reason) {
        this.$modal.msgError(this.$t("请输入申请理由"));
        return;
      }
      //银行收款明细ID
      const s_id = this.list[this.selectIndex].id;
      //收款单ID
      const s_receiptId = this.list[this.selectIndex].receiptId;
      const s_receiptNo = this.list[this.selectIndex].receiptNo;
      this.$modal
        .confirm(this.$t("您确认要反核销吗") + "?")
        .then(() => {
          financeReceiptItemWriteOffNo({
            receiptId: s_receiptId, //收款单ID
            receiptNo: s_receiptNo, //收款单编号
            receiptItemId: s_id, //银行收款明细项ID
            remark: this.reason,
          }).then((res) => {
            this.getList();
            this.$message.success(this.$t("提交成功"));
            this.dialogVisible = false;
          });
        })
        .catch(() => {
          this.dialogVisible = false;
        });
    },
    //取消审核
    cancelWriteOffClick() {
      if (!this.cancelReason) {
        this.$modal.msgError(this.$t("请输入申请理由"));
        return;
      }
      //银行收款明细ID
      const s_id = this.list[this.selectIndex].id;
      //收款单ID
      var s_receiptId = this.list[this.selectIndex].receiptId;
      if (this.cancelIndex == 1) {
        //取消审核
        cancelFinanceReceiptApproval({
          receiptId: s_receiptId,
          remark: this.cancelReason,
        }).then((res) => {
          this.cancelShow = false;
          this.getList();
          this.$message.success(this.$t("提交成功"));
        });
      } else if (this.cancelIndex == 2) {
        //取消反审核
        cancelFinanceReceiptApprovalNo({
          receiptId: s_receiptId,
          remark: this.cancelReason,
        }).then((res) => {
          this.cancelShow = false;
          this.getList();
          this.$message.success(this.$t("提交成功"));
        });
      } else if (this.cancelIndex == 3) {
        //取消反核销审核
        cancelFinanceReceiptWriteOffNo({
          receiptId: s_receiptId,
          remark: this.cancelReason,
        }).then((res) => {
          this.cancelShow = false;
          this.getList();
          this.$message.success(this.$t("提交成功"));
        });
      } else {
        //取消全部核销审核
        cancelFinanceReceiptWriteOff({
          receiptId: s_receiptId,
          remark: this.cancelReason,
        }).then((res) => {
          this.cancelShow = false;
          this.getList();
          this.$message.success(this.$t("提交成功"));
        });
      }
    },
    //显示反核销弹窗
    showCancel(index) {
      this.selectIndex = index;
      this.reason = "";
      this.dialogVisible = true;
    },
    //显示取消审核弹窗
    cancelClick(index, type) {
      this.selectIndex = index;
      this.cancelIndex = type;
      this.cancelReason = "";
      if (this.cancelIndex == 1) {
        this.cancelTitle = this.$t("取消审核");
      } else if (this.cancelIndex == 2) {
        this.cancelTitle = this.$t("取消反审核");
      } else if (this.cancelIndex == 3) {
        this.cancelTitle = this.$t("取消反核销审核");
      } else {
        this.cancelTitle = this.$t("取消全部核销审核");
      }
      this.cancelShow = true;
    },
    /** 批量提交审核 */
    handleAdd() {
      if (this.ids.length == 0) {
        this.$message.error(this.$t("请选择需要批量提交的收款明细。"));
        return;
      }
      let objDataList = [];
      for (var i = 0; i < this.ids.length; i++) {
        //选中项中都是待提交的记录
        if (this.ids[i].status != 0) {
          this.$message.error(this.$t("选择中有不符合提交条件的收款明细。"));
          return;
        }
        var objData = {
          receiptId: this.ids[i].receiptId, //收款单ID
          receiptNo: this.ids[i].receiptNo, //收款单编号
          receiptItemId: this.ids[i].id, //收款明细ID
        };
        objDataList.push(objData);
      }
      this.$modal
        .confirm(this.$t("您确认要提交审核吗" + "?"))
        .then(() => {
          financeReceiptItemWriteOff2(objDataList).then((res) => {
            this.$message.success(this.$t("提交成功"));
            //刷新列表
            this.getList();
          });
        })
        .catch(() => {});
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return;
        }

        // 修改的提交
        if (this.form.id != null) {
          update(this.form).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        create(this.form).then((response) => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    paymentDetail1(row) {
      //到收款单详情 lanbm 2024-05-18 add
      const id = row.receiptId;
      return this.$router.push("/financial/receiptDetail?id=" + id);
    },
    paymentDetail2(row) {
      //到订单详情 lanbm 2024-05-18 add
      const id = row.id;
      return this.$router.push("/financial/receiptDetail?id=" + id);
    },
    paymentDetail3(row) {
      //到提单详情 lanbm 2024-05-18 add
      const id = row.id;
      return this.$router.push("/financial/receiptDetail?id=" + id);
    },
    getCurrencyLabel(id) {
      let label = this.currencyList.filter((item) => item.id == id);
      if (label.length > 0)
        return this.$i18n.locale == "zh_CN"
          ? label[0].titleZh
          : label[0].titleEn;
      return "";
    },
    handleSelectionChange(selection) {
      //表格多选函数 lanbm 2024-05-30 add
      this.ids = [];
      this.ids = selection;
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    getsurplusData() {
      // 已收
      this.surplusData = [];
      let recepted = [];
      this.detailed.forEach((item) => {
        if (!recepted[item.currencyId]) {
          recepted[item.currencyId] = item.amount;
        } else
          recepted[item.currencyId] = NP.plus(
            recepted[item.currencyId],
            item.amount
          );
      });
      // 应收
      let collom = [];
      // 从期望收费金额中提取应收币种和金额
      this.form.receiptAccountList
        .find((item) => item.type == "total")
        .collectionAmount.forEach((item) => {
          collom[item.currencyId] = item.amount;
        });
      recepted.forEach((amount, currency) => {
        if (amount) {
          if (collom[currency]) {
            if (collom[currency] - amount != 0)
              this.surplusData[currency] = +parseFloat(
                (collom[currency] - amount).toPrecision(12)
              );
          } else {
            this.surplusData[currency] = -amount;
          }
        }
      });
      collom.forEach((amount, currency) => {
        if (amount) {
          if (!this.surplusData[currency]) {
            if (recepted[currency]) {
              if (amount - recepted[currency] != 0)
                this.surplusData[currency] = +parseFloat(
                  (amount - recepted[currency]).toPrecision(12)
                );
            } else {
              this.surplusData[currency] = amount;
            }
          }
        }
      });
    },
    detailClick(row) {
      //查看详情
      let id = row.id;
      this.isEdit = true;
      getReceivableItem2(id).then((response) => {
        this.form = response.data;
        //收款单号
        this.form.receipt_no = row.receiptNo;
        //实收币种
        this.form.currencyName = this.getCurrencyLabel(row.currencyId);
        //水单附件 分解附件路径
        this.form.attr = response.data.attr
          ? response.data.attr
              .split(",")
              .map((t) => ({ name: t.slice(t.lastIndexOf("/") + 1), url: t }))
          : [];
        this.openAddDialog = true;
        this.dialogTitle = this.$t("银行实收明细详情");
        this.isView = true;
      });
    },
    editClick(row) {
      let id = row.id;
      this.isEdit = false;
      getReceivableItem2(id).then((response) => {
        this.form = response.data;
        //收款单号
        this.form.receipt_no = row.receiptNo;
        //实收币种
        this.form.currencyName = this.getCurrencyLabel(row.currencyId);
        //水单附件
        this.form.attr = row.attr;

        let bank = this.bankData.find(
          (v) => v.baAccountNum == this.form.accountNo
        );
        if (bank) this.form.accountId = bank.id;

        this.openAddDialog = true;
        this.dialogTitle = this.$t("编辑银行实收明细");
        this.saveBtnText = this.$t("提交");
        this.isView = false;
      });
    },
    deleteClick(row) {
      const id = row.id;
      this.$modal
        .confirm(this.$t("是否确认删除该收款单") + "?")
        .then(function () {
          return deleteReceiptItem(id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$t("删除成功"));
        })
        .catch(() => {});
    },
    handleUploadSuccess(res, file, fileList) {
      let arr = [];
      setTimeout(() => {
        fileList.forEach((item) => {
          arr.push({
            name: item.name,
            url: item.response ? item.response.data : item.url,
          });
        });
        this.form.attr = arr;
      }, 300);
      this.UpLoading.close();
    },
    handleBeforeUpload() {
      this.UpLoading = this.$loading({
        lock: true,
        text: this.$t("上传中"),
        background: "rgba(0, 0, 0, 0.7)",
      });
    },
    handleUploadError() {
      this.$message({
        type: "error",
        message: this.$t("上传失败"),
      });
      this.UpLoading.close();
    },
    beforeRemove(file, fileList) {
      return this.$confirm(this.$t("确定移除") + "?").then((res) => {
        setTimeout(() => {
          this.form.attr = fileList.map((v) => ({
            name: v.name,
            url: v.response ? v.response.data : v.url,
          }));
        }, 300);
      });
    },
  },
};
</script>