<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="fuhao">
        <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="fuhao">
        <el-input
          v-model="queryParams.fuhao"
          placeholder="创建人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="fuhao">
        <el-date-picker
          v-model="queryParams.sDate"
          type="month"
          style="width: 150px"
          value-format="yyyy-MM"
          clearable
          placeholder="请输起始月"
        />
        <el-date-picker
          v-model="queryParams.eDate"
          type="month"
          style="width: 150px"
          value-format="yyyy-MM"
          clearable
          placeholder="请输截止月"
        />
      </el-form-item>
      <el-form-item label="提交审批时间" prop="titleZh">
        <el-date-picker
          v-model="queryParams.sDate"
          type="month"
          style="width: 150px"
          value-format="yyyy-MM"
          clearable
          placeholder="请输起始月"
        />
        <el-date-picker
          v-model="queryParams.eDate"
          type="month"
          style="width: 150px"
          value-format="yyyy-MM"
          clearable
          placeholder="请输截止月"
        />
      </el-form-item>
      <el-form-item label="审批通过时间" prop="titleZh">
        <el-date-picker
          v-model="queryParams.sDate"
          type="month"
          style="width: 150px"
          value-format="yyyy-MM"
          clearable
          placeholder="请输起始月"
        />
        <el-date-picker
          v-model="queryParams.eDate"
          type="month"
          style="width: 150px"
          value-format="yyyy-MM"
          clearable
          placeholder="请输截止月"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          @click="handleAdd"
          v-hasPermi="['report:vz:create']"
        >
          {{ $t("批量提交审核") }}</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          v-show="false"
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['my:test:export']"
        >
          {{ $t("导出") }}</el-button
        >
      </el-col>
      <el-col :span="1.5"> </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <el-card class="card">
      <el-table
        ref="multipleTable"
        :data="detailed"
        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="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.attr">
            <div v-for="(v, i) in scope.row.attr" :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" 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
              v-if="scope.row.status == 0"
              type="text"
              @click="detailClick(scope.row)"
              v-hasPermi="['ecw:payment:detail:detail']"
              >{{ $t("详情") }}</el-button
            >
            <!--核销 改 提交 lanbm 2024-05-29 -->
            <el-button
              v-if="scope.row.status == 0"
              type="text"
              @click="
                $router.push(`bankDetail?id=` + id + `&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>
    </el-card>

    <el-dialog :title="detailTitle" :visible.sync="detailShow" width="30%">
      <div class="cancel_content">
        <span>{{ $t("申请理由") }}</span>
        <el-input
          type="textarea"
          :rows="6"
          v-model="detailReason"
          :placeholder="$t('请输入取消理由')"
        ></el-input>
      </div>
      <span slot="footer" class="dialog-footers">
        <el-button type="primary" @click="detailWriteOffClick()">{{
          $t("提交")
        }}</el-button>
        <el-button @click="detailShow = false">{{ $t("取消") }}</el-button>
      </span>
    </el-dialog>
    <el-dialog :title="$t('收款单反核销')" :visible.sync="wiffShow" width="30%">
      <div class="cancel_content">
        <span>{{ $t("申请理由") }}</span>
        <el-input
          type="textarea"
          :rows="6"
          v-model="wiffRemark"
          :placeholder="$t('请输入理由')"
        ></el-input>
      </div>
      <span slot="footer" class="dialog-footers">
        <el-button type="primary" @click="writeOffClick()">{{
          $t("提交反核销")
        }}</el-button>
        <el-button @click="wiffShow = false">{{ $t("取消") }}</el-button>
      </span>
    </el-dialog>
    <el-dialog
      v-if="openAddDialog"
      :visible.sync="openAddDialog"
      :title="dialogTitle"
      width="50%"
      append-to-body
    >
      <div style="padding: 0 24px">
        <el-form ref="addForm" :model="addForm" label-width="250px">
          <el-form-item :label="$t('收款单号')">{{
            form.receiptNo
          }}</el-form-item>
          <el-form-item :label="$t('剩余应收金额')">
            <template v-if="surplusData.length == 0"> 0 </template>
            <div v-else>
              <div v-for="(amount, currency) in surplusData" :key="currency">
                <span v-if="amount">
                  {{ amount }}{{ getCurrencyLabel(currency) }}</span
                >
              </div>
            </div>
          </el-form-item>
          <el-form-item
            :label="$t('收款账户')"
            prop="accountNo"
            :rules="{
              required: true,
              trigger: ['blur', 'change'],
              message: $t('收款账户不能为空'),
            }"
          >
            <el-select
              v-if="!isView"
              filterable
              clear
              v-model="addForm.accountId"
              :placeholder="$t('请选择收款账户')"
              style="width: 220px"
              @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>
            <span v-else
              >{{ addForm.accountNo
              }}{{ "(" + addForm.accountName + ")" }}</span
            >
          </el-form-item>
          <el-form-item
            :label="$t('实收日期')"
            prop="amountDate"
            :rules="{
              required: true,
              trigger: ['blur', 'change'],
              message: $t('实收日期不能为空'),
            }"
          >
            <el-date-picker
              v-if="!isView"
              clearable
              v-model="addForm.amountDate"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
              type="date"
              :placeholder="$t('选择实收日期')"
            />
            <span v-else>{{ addForm.amountDate }}</span>
          </el-form-item>
          <div style="display: flex">
            <el-form-item
              :label="$t('实收')"
              prop="amount"
              :rules="{
                required: true,
                trigger: ['blur', 'change'],
                message: $t('实收不能为空'),
              }"
            >
              <el-input
                v-if="!isView"
                v-model="addForm.amount"
                style="width: 220px; margin-right: 12px"
                @input="setWriteOffAmount"
              ></el-input>
              <span v-else>{{ addForm.amount }}</span>
            </el-form-item>
            <el-form-item
              label-width="0px"
              prop="currencyId"
              :rules="{
                required: true,
                trigger: ['blur', 'change'],
                message: $t('币种不能为空'),
              }"
            >
              <el-select
                v-model="addForm.currencyId"
                :placeholder="$t('请选择')"
                :disabled="isView"
                @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>
          </div>
          <el-form-item
            v-if="showCurrencyId != addForm.currencyId"
            prop="rate"
            :rules="{
              required: true,
              trigger: ['blur', 'change'],
              message: $t('兑核销基准币种汇率不能为空'),
            }"
          >
            <template slot="label">
              <span
                :title="
                  $t(
                    '实收币种与核销基准币种一样时，无需填写汇率，不一样需要填写汇率'
                  )
                "
                >{{ $t("兑核销基准币种汇率") }}（{{
                  getCurrencyLabel(showCurrencyId)
                }}）</span
              >
            </template>
            <el-input
              v-if="!isView"
              v-model="addForm.rate"
              style="width: 220px"
            ></el-input>
            <span v-else>{{ addForm.rate }}</span>
          </el-form-item>
          <el-form-item v-if="showCurrencyId != addForm.currencyId">
            <template slot="label">
              {{ $t("兑核销基准币种金额") }}（{{
                getCurrencyLabel(showCurrencyId)
              }}）
            </template>
            <span>{{
              addForm.writeOffAmount
                ? parseFloat(addForm.writeOffAmount).toFixed(2)
                : ""
            }}</span>
          </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="addForm.attr"
              multiple
            >
              <el-button size="small" type="primary">{{
                $t("上传附件")
              }}</el-button>
            </el-upload>
            <div v-else>
              <div v-for="(v, i) in addForm.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-if="!isView"
              v-model="addForm.billNo"
              style="width: 220px"
            ></el-input>
            <span v-else>{{ addForm.billNo }}</span>
          </el-form-item>
        </el-form>
        <div slot="footer" v-if="!isView">
          <el-button type="primary" @click="saveFrom">{{
            saveBtnText
          }}</el-button>
          <el-button @click="hiddenDialog">{{ $t("取消") }}</el-button>
        </div>
      </div>
    </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 :title="$t('取消审核')" :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-footer">
        <el-button type="primary" @click="cancelWriteOffClick()">{{
          $t("提交")
        }}</el-button>
        <el-button @click="cancelShow = false">{{ $t("取消") }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
  
  <script>
import helpIcon from "@/assets/images/help.png";
import { getBankAccountPage } from "@/api/ecw/bankAccount";
import { getToken } from "@/utils/auth";
import { listSimpleDepts } from "@/api/system/dept";
import { getCustomer } from "@/api/ecw/customer";
import { getExchangeRatePage } from "@/api/ecw/exchangeRate";
import { getPageList, test } from "@/api/report/bankReceiptDetail";

import {
  getReceiptInfoByIds,
  getInvoicingItem,
  receiptItemCreate,
  getReceivableItem,
  deleteReceiptItem,
  receiptItemVerification,
  receiptItemVerificationCancel,
  updateReceiptItem,
  receiptItemBatchVerification,
  receiptItemAllVerification,
  getReceiptAccountList,
  financeReceiptWriteOff,
  financeReceiptItemWriteOffNo,
  cancelFinanceReceiptItemWriteOff,
  cancelFinanceReceiptItemWriteOffNo,
  cancelFinanceReceiptWriteOffNo,
  cancelFinanceReceiptWriteOff,
  financeReceiptWriteOffNo,
} from "@/api/ecw/financial";
import { getCurrencyPage } from "@/api/ecw/currency";
import NP from "number-precision";

export default {
  data() {
    return {
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/app-api/file/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      id: 0,
      form: {},
      list: [],
      detailedList: [],
      openAddDialog: false,
      bankData: [],
      params: {
        page: 1,
        rows: 100,
      },
      addForm: {},
      detailed: [],
      deptData: [],
      deptArr: [],
      dialogTitle: this.$t("添加银行实收明细"),
      saveBtnText: this.$t("添加"),
      isView: false,
      multipleSelection: [],
      currencyList: [],
      verificationData: {
        usCount: 0,
        rmbCount: 0,
        nairaCount: 0,
        writtenOff: 0,
        WriteOffProportion: 0,
      },
      remainingAmount: {
        usAmount: 0,
        rmbAmount: 0,
        nairaAmount: 0,
      },
      surplusData: [],
      dialogVisible: false,
      reason: "",
      cancelShow: false,
      cancelTitle: "",
      cancelReason: "",
      cancelType: 1,
      detailReason: "",
      detailTitle: "",
      detailShow: false,
      detailIndex: 1,
      wiffShow: false,
      wiffRemark: "",
      rateList: [],
      codePage: {
        pageNo: 1,
        pageSize: 20,
      },
      pages: 1,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        receiptNo: undefined, //收款单编号
        orderNo: undefined, //订单编号
        tidanNo: undefined, //提单编号
      },
    };
  },
  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;
    },
    // 已核销总金额
    writeOffTotal() {
      let total = {};
      this.detailed.forEach((item) => {
        if (item.status) {
          if (!total[item.currencyId]) {
            total[item.currencyId] = item.amount;
          } else
            total[item.currencyId] = NP.plus(
              total[item.currencyId],
              item.amount
            );
        }
      });
      return total;
    },
    // 已核销总金额
    writeOffAmount() {
      let total = 0;
      this.detailed.forEach((item) => {
        if (item.status) {
          total = NP.plus(total, item.writeOffAmount);
        }
      });

      return total.toFixed(2);
    },
    //显示反审核反核销弹窗
    writeOffShow() {
      this.wiffRemark = "";
      this.wiffShow = true;
    },
    WriteOffProportion() {
      let total = 0;
      if (!this.form.receiptAccountList) return 0;
      let amountTotal = this.form.receiptAccountList.find(
        (item) => item.type == "total"
      ).writeOffAmount;

      this.detailed.forEach((item) => {
        if (item.status) {
          total = NP.plus(total, item.writeOffAmount);
        }
      });

      let portion = NP.divide(total, amountTotal);
      console.log(portion);
      if (!portion) return 0;
      return (portion * 100).toFixed(2);
    },
  },
  watch: {
    "addForm.rate"() {
      this.setWriteOffAmount();
    },
  },
  directives: {
    "el-select-loadmore": {
      bind(el, binding) {
        const SELECTWRAP_DOM = el.querySelector(
          ".el-select-dropdown .el-select-dropdown__wrap"
        );
        SELECTWRAP_DOM.addEventListener("scroll", function () {
          const condition =
            this.scrollHeight - this.scrollTop <= this.clientHeight;
          if (condition) {
            binding.value();
          }
        });
      },
    },
  },
  async created() {
    // 获取汇率
    await getCurrencyPage(this.params).then(
      (res) => (this.currencyList = res.data.list)
    );
    await getExchangeRatePage(this.params).then(
      (res) => (this.rateList = res.data.list)
    );
    await listSimpleDepts().then((res) => {
      this.deptData = res.data;
    });
    await getBankAccountPage(this.codePage).then((res) => {
      this.bankData = res.data.list;
      this.pages = res.data.total / this.codePage.pageSize + 1;
    });
    if (this.$route.query.id) {
      this.id = this.$route.query.id;
      await getReceiptInfoByIds({ id: this.id }).then((res) => {
        this.form = res.data;
        let dept = this.deptData.filter(
          (itt) => itt.id == res.data.departmentId
        );
        if (dept.length > 0) {
          this.form.departmentName = dept[0].name;
        }
      });
      await getInvoicingItem({ id: this.id }).then((res) => {
        this.list = [...res.data];
      });
      getReceiptAccountList({ id: this.id }).then((res) => {
        if (res.data.length > 0) {
          res.data = [
            ...res.data,
            {
              type: "total",
              writeOffAmount: res.data
                .reduce(
                  (total, currentValue) =>
                    NP.plus(total, currentValue.writeOffAmount || 0),
                  0
                )
                .toFixed(2),
              collectionAmount: [],
            },
          ];
        }
        this.$set(this.form, "receiptAccountList", res.data);
        // 收款总计

        let num;
        let amountList = [];
        this.currencyList.forEach((item, index) => {
          let nairaListByList = this.list.filter(
            (v) => v.currencyId === item.id
          );
          if (nairaListByList.length > 0) {
            let discountNaira = nairaListByList.reduce(
              (total, currentValue) =>
                NP.plus(total, currentValue.discountTotal || 0),
              0
            );
            num = res.data.find((v) => v.currencyId == item.id);
            num && (num.discountTotal = discountNaira);
          }
          let dollarList = this.form.receiptAccountList.filter(
            (v) => v.collectionCurrencyId == item.id
          );
          if (dollarList.length > 0) {
            let dollar = dollarList
              .reduce(
                (total, currentValue) =>
                  NP.plus(total, currentValue.collectionAmount || 0),
                0
              )
              .toFixed(2);
            // if(n && n.discountTotal&&n.discountTotal>0){
            //   amountList.push({currencyName:item.titleZh, currencyId: item.id, amount:(dollar-n.discountTotal).toFixed(2)})
            // }else{
            amountList.push({
              currencyId: item.id,
              currencyNameEn: item.titleEn,
              currencyNameZh: item.titleZh,
              amount: dollar || 0,
            });
            // }
          }
        });
        this.form.receiptAccountList[
          this.form.receiptAccountList.length - 1
        ].collectionAmount = amountList;
        this.$set(this.form, "receiptAccountList", [
          ...this.form.receiptAccountList,
        ]);

        this.$nextTick(() => {
          if (this.form.receiptAccountList.length > 0) {
            this.editReceiptAccountList();
          }
        });
      });
    }

    this.getList();
  },
  methods: {
    // 懒加载
    loadmore() {
      this.codePage.pageNo++;
      // 大于页码不请求了
      console.log(111);
      if (this.codePage.pageNo > this.pages) {
        return;
      }
      this.getCodeList();
    },
    getCodeList() {
      setTimeout(() => {
        getBankAccountPage(this.codePage).then((res) => {
          this.bankData = this.bankData.concat(res.data.list);
          this.pages = res.data.total / this.codePage.pageSize + 1;
        });
      }, 200);
    },
    rateChange(row, index) {
      if (row.collectionRate) {
        row.receivableAmount &&
          (row.collectionAmount = Math.round(
            NP.times(
              row.collectionRate || 0,
              NP.minus(row.receivableAmount, row.discountTotal || 0)
            )
          ));
      } else {
        row.collectionAmount = "";
      }
      // row.receivableAmount && (row.collectionAmount = NP.times(row.collectionRate || 0, NP.minus(row.receivableAmount, row.discountTotal||0)).toFixed(2))
      this.form.receiptAccountList[index] = { ...row };
    },
    editReceiptAccountList() {
      let amountList = [];
      this.currencyList.forEach((item, index) => {
        let dollarList = this.form.receiptAccountList.filter(
          (v) => v.collectionCurrencyId == item.id
        );
        if (dollarList.length > 0) {
          let dollar = dollarList.reduce(
            (total, currentValue) =>
              NP.plus(total, currentValue.collectionAmount || 0),
            0
          );
          amountList.push({
            currencyId: item.id,
            currencyNameEn: item.titleEn,
            currencyNameZh: item.titleZh,
            amount: dollar.toFixed(2),
          });
        }
      });
      this.form.receiptAccountList[
        this.form.receiptAccountList.length - 1
      ].collectionAmount = amountList;
      this.$set(this.form, "receiptAccountList", [
        ...this.form.receiptAccountList,
      ]);
    },
    setWriteOffAmount() {
      let pointArr = [];
      let regs = /^[0-9]+\d*(\.\d*)?$|^0?\.\d*[0-9]\d*$/;
      if (this.addForm.amount && !regs.test(this.addForm.amount)) {
        this.addForm.amount = "";
        this.$modal.msgError(this.$t("输入金额不对"));
      } else {
        if (this.addForm && this.addForm.amount) {
          pointArr = this.addForm.amount.toString().split(".");
          if (pointArr.length > 1 && pointArr[1]) {
            this.addForm.amount = Math.round(this.addForm.amount * 100) / 100;
          }
        }
      }
      this.$set(
        this.addForm,
        "writeOffAmount",
        NP.times(this.addForm.rate || 0, this.addForm.amount || 0)
      );
    },
    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 "";
    },
    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;
            }
          }
        }
      });
    },
    accountChange(val) {
      let data = this.bankData.find((item) => item.id == val);
      this.$set(this.addForm, "accountName", data.baAccountName || "");
      this.$set(this.addForm, "accountNo", data.baAccountNum || "");
      this.$set(this.addForm, "accountBankName", data.baBankName || "");
    },
    RMBtoUS() {
      return NP.divide(
        100,
        this.currencyList.find((v) => v.titleEn === "USD").huilv
      );
    },
    NANtoUS() {
      return NP.times(this.RMBtoUS(), this.NANtoRMB());
    },
    UStoRMB() {
      return NP.divide(
        this.currencyList.find((v) => v.titleEn === "USD").huilv,
        100
      );
    },
    UStoNAN() {
      return NP.times(this.RMBtoNAN(), this.UStoRMB());
    },
    RMBtoNAN() {
      return NP.divide(
        100,
        this.currencyList.find((v) => v.titleEn === "NGN").huilv
      );
    },
    NANtoRMB() {
      return NP.divide(
        this.currencyList.find((v) => v.titleEn === "NGN").huilv,
        100
      );
    },
    //显示反核销弹窗
    showCancel(index) {
      this.selectIndex = index;
      this.reason = "";
      this.dialogVisible = true;
    },
    writeOffClick() {
      if (!this.wiffRemark) {
        this.$modal.msgError(this.$t("请输入申请理由"));
        return;
      }
      this.$modal
        .confirm(this.$t("您确认要反核销吗") + "?")
        .then(() => {
          financeReceiptWriteOffNo({
            receiptId: this.id,
            receiptNo: this.form.receiptNo,
            remark: this.wiffRemark,
          }).then((res) => {
            this.getReceiptInfoData();
            this.$message.success(this.$t("提交成功"));
            this.wiffShow = false;
            // this.$store.dispatch('tagsView/delCurrentView')
          });
        })
        .catch(() => {
          this.wiffShow = false;
        });
    },
    //显示取消审核弹窗
    detailClickCancel(type) {
      this.detailIndex = type;
      this.detailReason = "";
      if (this.detailIndex == 1) {
        this.detailTitle = this.$t("取消反核销审核");
      } else {
        this.detailTitle = this.$t("取消全部核销审核");
      }
      this.detailShow = true;
    },
    //取消审核弹窗
    cancelClick(index, type) {
      this.selectIndex = index;
      this.cancelType = type;
      this.cancelReason = "";
      this.cancelShow = true;
    },
    //取消审核
    detailWriteOffClick() {
      if (!this.detailReason) {
        this.$modal.msgError(this.$t("请输入申请理由"));
        return;
      }
      if (this.detailIndex == 1) {
        cancelFinanceReceiptWriteOffNo({
          receiptId: this.id,
          remark: this.detailReason,
        }).then((res) => {
          this.detailShow = false;
          this.getReceiptInfoData();
          this.$message.success(this.$t("提交成功"));
        });
      } else {
        cancelFinanceReceiptWriteOff({
          receiptId: this.id,
          remark: this.detailReason,
        }).then((res) => {
          this.detailShow = false;
          this.getReceiptInfoData();
          this.$message.success(this.$t("提交成功"));
        });
      }
    },
    getReceiptInfoData() {
      getReceiptInfoByIds({ id: this.id }).then((res) => {
        this.form = res.data;
        getCustomer(this.form.customerId).then((res) => {
          this.form.customerName = res?.data?.name;
        });
        let dept = this.deptData.filter(
          (itt) => itt.id == res.data.departmentId
        );
        // console.log(dept)
        if (dept.length > 0) {
          this.form.departmentName = dept[0].name;
        }
      });
    },
    //取消审核
    cancelWriteOffClick() {
      if (!this.cancelReason) {
        this.$modal.msgError(this.$t("请输入申请理由"));
        return;
      }
      let receiptItemId = this.detailed[this.selectIndex].id;
      if (this.cancelType == 1) {
        cancelFinanceReceiptItemWriteOff({
          receiptItemId: receiptItemId,
          remark: this.cancelReason,
        }).then((res) => {
          this.cancelShow = false;
          this.getList();
          this.$message.success(this.$t("提交成功"));
        });
      } else {
        cancelFinanceReceiptItemWriteOffNo({
          receiptItemId: receiptItemId,
          remark: this.cancelReason,
        }).then((res) => {
          this.cancelShow = false;
          this.getList();
          this.$message.success(this.$t("提交成功"));
        });
      }
    },
    currencyIdChange(val) {
      val = Number(val);
      let rate;
      if (val === this.showCurrencyId) {
        rate = 1;
      } else {
        rate = this.getRate(val, this.showCurrencyId);
      }
      this.$set(this.addForm, "rate", rate);
    },
    //获取汇率
    getRate(sourceCurrencyId, targetCurrencyId) {
      let rate = this.rateList.find(
        (v) =>
          v.sourceCurrencyId === sourceCurrencyId &&
          v.targetCurrencyId === targetCurrencyId
      );
      if (rate) return rate.currencyRate;
      return "";
    },
    getList() {
      /*
      getReceivableItem({ id: this.id }).then((res) => {
        this.detailed = res.data.map((v) => ({
          ...v,
          amountDate: this.parseTime(v.amountDate, "{y}-{m}-{d}"),
          rate: parseFloat(v.rate),
          attr: v.attr
            ? v.attr
                .split(",")
                .map((t) => ({ name: t.slice(t.lastIndexOf("/") + 1), url: t }))
            : [],
        }));
      });*/
      this.loading = true;
      // 处理查询参数
      let params = { ...this.queryParams };
      // 执行查询
      getPageList(params).then((response) => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    saveFrom() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          if (this.addForm.id) {
            const params = { ...this.addForm };
            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.addForm };
          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();
          });
        }
      });
    },
    toEdit() {
      return this.$router.push("creatCollection?id=" + this.id);
    },
    detailClick(row) {
      this.getsurplusData();
      this.openAddDialog = true;
      this.dialogTitle = this.$t("银行实收明细详情");
      this.isView = true;
      setTimeout(() => {
        this.addForm = { ...row };
        this.setWriteOffAmount();
      }, 0);
    },
    editClick(row) {
      this.getsurplusData();
      this.openAddDialog = true;
      this.dialogTitle = this.$t("编辑银行实收明细");
      this.saveBtnText = this.$t("提交");
      this.isView = false;
      setTimeout(() => {
        this.addForm = { ...row };
        let bank = this.bankData.find(
          (v) => v.baAccountNum == this.addForm.accountNo
        );
        if (bank) this.addForm.accountId = bank.id;
        this.setWriteOffAmount();
      }, 0);
    },
    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(() => {});
    },
    verificationClick(row) {
      const id = row.id;
      this.$modal
        .confirm(this.$t("您确认要核销吗") + "?")
        .then(function () {
          return receiptItemVerification(id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$t("核销成功"));
        })
        .catch(() => {});
    },
    //银行明细反核销
    verificationCancelClick() {
      if (!this.reason) {
        this.$modal.msgError(this.$t("请输入申请理由"));
        return;
      }
      const id = this.detailed[this.selectIndex].id;
      this.$modal
        .confirm(this.$t("您确认要反核销吗") + "?")
        .then(() => {
          financeReceiptItemWriteOffNo({
            receiptId: this.id,
            receiptNo: this.form.receiptNo,
            receiptItemId: id,
            remark: this.reason,
          }).then((res) => {
            this.getList();
            this.$message.success(this.$t("提交成功"));
            this.dialogVisible = false;
          });
        })
        .catch(() => {
          this.dialogVisible = false;
        });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    batchVerification() {
      if (this.multipleSelection.length === 0) {
        this.$modal.msgError(this.$t("请选择需要核销的收款明细"));
        return;
      }
      const params = { ids: this.multipleSelection.map((v) => v.id).join(",") };
      this.$modal
        .confirm(this.$t("您确认要核销吗" + "?"))
        .then(function () {
          return receiptItemBatchVerification(params);
        })
        .then(() => {
          this.multipleSelection.forEach((row) => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
          this.getList();
          this.$modal.msgSuccess(this.$t("核销成功"));
        })
        .catch(() => {});
    },
    verificationAll() {
      if (!this.detailed || this.detailed.length == 0) {
        this.$modal.msgError(
          this.$t(
            "当前收款单未添加银行收款明细，无法全部核销，请添加银行收款单明细，并核销所有实收明细后再进行全部核销"
          )
        );
        return;
      }
      this.$modal
        .confirm(this.$t("您确认要全部核销吗" + "?"))
        .then(() => {
          return financeReceiptWriteOff({
            receiptId: this.id,
            receiptNo: this.form.receiptNo,
          });
        })
        .then(() => {
          this.$modal.msgSuccess(this.$t("核销成功"));
          this.$store.dispatch("tagsView/delCurrentView");
        })
        .catch(() => {});
    },
    hiddenDialog() {
      this.openAddDialog = false;
    },
    handleAddReceiptItem() {
      this.getsurplusData();
      this.addForm = {};
      this.openAddDialog = true;
      this.isView = false;
      this.dialogTitle = this.$t("添加银行实收明细");
      this.saveBtnText = this.$t("添加");
    },
    handleUploadSuccess(res, file, fileList) {
      let arr = [];
      setTimeout(() => {
        fileList.forEach((item) => {
          arr.push({
            name: item.name,
            url: item.response ? item.response.data : item.url,
          });
        });
        this.addForm.attr = arr;
      }, 300);
      this.loading.close();
    },
    handleBeforeUpload() {
      this.loading = this.$loading({
        lock: true,
        text: this.$t("上传中"),
        background: "rgba(0, 0, 0, 0.7)",
      });
    },
    handleUploadError() {
      this.$message({
        type: "error",
        message: this.$t("上传失败"),
      });
      this.loading.close();
    },
    beforeRemove(file, fileList) {
      return this.$confirm(this.$t("确定移除") + "?").then((res) => {
        setTimeout(() => {
          this.addForm.attr = fileList.map((v) => ({
            name: v.name,
            url: v.response ? v.response.data : v.url,
          }));
        }, 300);
      });
    },
  },
};
</script>
  
  <style scoped lang="scss">
.app-container {
  ::v-deep .el-descriptions-item__label {
    width: 200px;
  }
  ::v-deep .el-tag + .el-tag {
    margin-left: 8px;
  }
}
.card {
  margin-top: 20px;
}
.dialog-footer {
  padding: 40px;
}
.card-title {
  font-size: 18px;
  font-weight: bold;
}
.hexiaoCard {
  ::v-deep .el-descriptions-item__label {
    width: 11%;
  }
  ::v-deep .el-descriptions-item__content {
    width: 22%;
  }
}
.cancel_content {
  display: flex;
  // align-items: center;
  flex-direction: column;
  // padding-top: 20px;
}
.cancel_content span {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 10px;
}
</style>
  