<template>
  <div class="app-container">
    <el-form ref="form" :model="form" label-width="120px" label-position="left" :inline="true">
      <el-card>
        <div v-if="id" slot="header" class="card-title">
          {{ $t("修改收款单") }}
        </div>
        <div v-else slot="header" class="card-title">
          {{ $t("新增收款单") }}
        </div>
        <!-- <el-descriptions :column="3" border>-->
        <!-- <el-descriptions-item > -->
        <el-form-item style="margin-bottom: 0; margin-top: 20px" prop="customerId" :span="4">
          <span style="margin-right: 20px"><span style="color: #ff4949">*</span>{{ $t("客户") }}</span>
          <customer-selectorpay ref="customer" v-model="form.customerId" @change="customerChange" />
        </el-form-item>
        <!--        </el-descriptions-item>
          <el-descriptions-item > -->
        <el-form-item style="margin-bottom: 0; margin-top: 20px" prop="departmentId" :span="4">
          <span style="margin-right: 20px"><span style="color: #ff4949">*</span>{{ $t("部门") }}:</span>
          <el-select v-model="form.departmentId" style="width: 300px" :placeholder="$t('请选择部门')">
            <el-option v-for="item in deptData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item style="margin-bottom: 0; margin-top: 20px" prop="salesmanId" :span="4">
          <span style="margin-right: 20px"><span style="color: #ff4949">*</span>{{ $t("业务员") }}:</span>
          <el-select v-model="form.salesmanId" filterable :placeholder="$t('请选择业务员')" @change="(v) => (form.salesmanName = creatorData.find((t) => t.id === v).nickname)">
            <el-option v-for="item in creatorData" :key="item.id" :label="item.nickname" :value="item.id" />
          </el-select>
        </el-form-item>
        <!-- </el-descriptions-item> -->
        <!-- <el-descriptions-item > -->
        <!--            <el-form-item
              :label="$t('手续费(RMB)')"
              style="margin-bottom: 0;margin-top: 20px;"
              prop="feeRate"
              :rules="{ required: true, trigger: ['blur', 'change'], message: $t('手续费不能为空') }"
            >
              <el-input
                v-model="form.feeRate"
                :placeholder="$t('请输入手续费')"
              ></el-input>
            </el-form-item> -->
        <!--          </el-descriptions-item>
          <el-descriptions-item > -->
        <el-form-item :label="$t('备注') + ':'" style="margin-bottom: 0; margin-top: 20px" label-width="55px" prop="remark">
          <el-input style="display: inline-block" v-model="form.remark" :placeholder="$t('备注')"></el-input>
        </el-form-item>
        <!-- </el-descriptions-item> -->
        <!-- </el-descriptions> -->
      </el-card>
      <el-card class="card amountCard">
        <div slot="header" class="card-title">{{ $t("应收明细") }}</div>
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['ecw:voucher:create:add']" style="padding: 10px; margin-bottom: 10px">{{ $t("添加未收客户款项") }}</el-button>
        </el-col>
        <el-table v-loading="loadings" :data="list" border show-summary :summary-method="getSummaries">
          <el-table-column :label="$t('订单号')" align="center" prop="orderNo" />
          <el-table-column :label="$t('提单号')" align="center" prop="tidanNo" />
          <el-table-column :label="$t('唛头')" align="center" prop="marks" />
          <el-table-column :label="$t('品名')" align="center" prop="title">
            <template slot-scope="scope">
              {{ scope.row.titleZh ? scope.row.titleZh + "(" + scope.row.titleEn + ")" : "" }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('箱数')" align="center" prop="num" />
          <el-table-column :label="$t('体积/重量')" align="center" prop="weight">
            <template slot-scope="scope"> {{ scope.row.volume }}/{{ scope.row.weight }} </template>
          </el-table-column>
          <el-table-column :label="$t('收入类型')" align="center" prop="feeType">
            <template slot-scope="scope">
              <dict-tag :type="DICT_TYPE.FEE_TYPE" :value="scope.row.feeType"></dict-tag>
            </template>
          </el-table-column>
          <el-table-column :label="$t('单价金额')" align="center" prop="unitPrice">
            <template slot-scope="scope">
              <span>{{ getCurrencySymbol(scope.row.currencyId) }}{{ scope.row.unitPrice }}</span>
              <!-- <dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="scope.row.currencyId" /> -->
            </template>
          </el-table-column>
          <el-table-column :label="$t('税率%')" align="center" prop="taxPoint">
            <template slot-scope="scope">
              <el-input type="text" v-model="scope.row.taxPoint" @input="changeTaxRate(scope.row, scope.$index)"></el-input>
            </template>
          </el-table-column>
          <el-table-column :label="$t('不含税金额')" align="center" prop="totalAmount">
            <template slot-scope="scope">
              <span>{{ getCurrencySymbol(scope.row.currencyId) }}{{ scope.row.totalAmount }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('含税金额')" align="center" prop="taxAmount" :formatter="formatCurrency"> </el-table-column>
          <el-table-column :label="$t('优惠金额')" align="center" prop="discountTotal">
            <template slot-scope="scope">
              <span> {{ getCurrencySymbol(scope.row.currencyId) }}{{ scope.row.discountTotal ? `${scope.row.discountTotal}` : 0 }}</span>
              <!-- <dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="scope.row.currencyId" /> -->
              <span v-if="scope.row.discountTotal">{{ scope.row.discountRemark ? "(" + scope.row.discountRemark + ")" : "" }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="actualAmount" width="120" :formatter="formatCurrency">
            <template slot="header" slot-scope="scope">
              <span :title="$t('实际金额=含税金额-优惠金额')">{{ $t("实际金额") }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="exchangeRate" :label="$t('基准币种（{currency}）汇率', { currency: getBaseCurrencynName(showCurrencyId) })" width="120">
            <template v-slot="{ row }"> {{ getCurrencySymbol(row.currencyId) }}1:{{ getCurrencySymbol(showCurrencyId) }}{{ row.exchangeRate }} </template>
          </el-table-column>
          <el-table-column
            prop="baseAmount"
            :label="
              $t('基准金额（{currency})', {
                currency: getBaseCurrencynName(showCurrencyId)
              })
            "
            width="120"
            :formatter="formatCurrency"
          >
          </el-table-column>

          <el-table-column fixed="right" :label="$t('操作')" align="center">
            <template slot-scope="scope">
              <el-button v-if="scope.row.type !== 'total'" type="text" v-hasPermi="['ecw:voucher:create:editdiscount']" @click="addDiscount(scope.row, scope.$index)">{{ scope.row.discountTotal ? $t("修改优惠") : $t("新增优惠") }}</el-button>
              <el-button v-if="scope.row.type !== 'total'" type="text" v-hasPermi="['ecw:voucher:create:deldiscount']" @click="deleteListRow(scope.$index)">{{ $t("删除") }}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <el-card class="card">
        <div slot="header" class="card-title">{{ $t("账单信息") }}</div>
        <el-table :data="form.receiptAccountList" border :key="form.receiptAccountList.length">
          <el-table-column :label="$t('应收币种')" align="center">
            <template slot-scope="scope">
              <template v-if="scope.row.type !== 'total'">
                {{ getCurrencyLabel(scope.row.currencyId) }}
              </template>
              <template v-else>
                {{ $t("核销基准币种") }}
              </template>
            </template>
          </el-table-column>
          <el-table-column :label="$t('应收金额')" align="center" prop="receivableAmount">
            <template slot-scope="scope">
              <template v-if="scope.row.type !== 'total'"> {{ getCurrencySymbol(scope.row.currencyId) }}{{ NP.round(`${NP.minus(scope.row.receivableAmount, scope.row.discountTotal || 0)}`, 0) }}{{ `${scope.row.discountTotal > 0 ? `(${scope.row.receivableAmount} - ${scope.row.discountTotal})` : ""}` }}</template>
              <template v-else> {{ getCurrencyLabel(showCurrencyId) }}</template>
            </template>
          </el-table-column>
          <el-table-column align="center">
            <template #header>
              {{ $t("基准币种（{currency}）汇率", { currency: getBaseCurrencynName(showCurrencyId) }) }}
            </template>
            <template slot-scope="scope">
              <template v-if="scope.row.type !== 'total'">
                <span v-if="showCurrencyId === scope.row.currencyId">{{ scope.row.writeOffRate }}</span>
                <el-form-item v-else label="" label-width="0" style="margin-bottom: 0" :prop="`receiptAccountList.${scope.$index}.writeOffRate`">
                  <el-input v-model="scope.row.writeOffRate" @input="() => writeOffRateChange(scope.row, scope.$index)"></el-input>
                </el-form-item>
              </template>
              <template v-else>
                {{ $t("应核销总金额") + "（" + getCurrencyLabel(showCurrencyId) + "）" }}
              </template>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="writeOffAmount">
            <template #header>
              {{ $t("基准金额") + "（" + getCurrencyLabel(showCurrencyId) + "）" }}
            </template>
            <template slot-scope="scope">
              <div>{{ getCurrencySymbol(showCurrencyId) }}{{ scope.row.writeOffAmount }}</div></template
            >
          </el-table-column>

          <el-table-column :label="$t('期望收款账户')" align="center">
            <template slot-scope="scope">
              <el-form-item v-if="scope.row.type !== 'total'" label="" label-width="0" style="margin-bottom: 0" :prop="`receiptAccountList.${scope.$index}.platformAccountId`">
                <!--                <el-select
                  v-model="scope.row.platformAccountId"
                  :placeholder="$t('请选择收款账户')"
                  @change="(platformAccountId)=>changePlatformAccountId(platformAccountId,scope.$index)"
                >
                  <el-option
                    v-for="item in bankData"
                    :key="item.id"
                    :label="item.baAccountName + '(' + item.baAccountNum + ')'"
                    :value="item.id"
                  />
                </el-select> -->
                <el-select filterable clear v-model="scope.row.platformAccountId" :placeholder="$t('请选择收款账户')" @change="(platformAccountId) => changePlatformAccountId(platformAccountId, scope.$index)" v-el-select-loadmore="loadmore" :loading="codeLoading">
                  <el-option v-for="(item, i) in bankData" :key="'opt-code' + i" :label="item.baAccountName + '(' + item.baAccountNum + ')'" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('期望收款币种')" align="center">
            <template slot-scope="scope">
              <el-form-item v-if="scope.row.type !== 'total'" label="" label-width="0" style="margin-bottom: 0" :prop="`receiptAccountList.${scope.$index}.collectionCurrencyId`">
                <el-select v-model="scope.row.collectionCurrencyId" :placeholder="$t('请选择')" @change="(val) => currencyIdChange(val, scope.row, scope.$index)">
                  <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>
            </template>
          </el-table-column>
          <el-table-column :label="$t('期望收款汇率')" align="center">
            <!--lanbm 2024-05-06 汇率保留小数增加到6位，为了方便显示，加宽此列的显示-->
            <template slot-scope="scope" style="width: 200px">
              <el-form-item v-if="scope.row.type !== 'total'" label="" label-width="0" style="margin-bottom: 0" :prop="`receiptAccountList.${scope.$index}.collectionRate`">
                <el-input v-model="scope.row.collectionRate" @input="() => rateChange(scope.row, scope.$index)"></el-input>
              </el-form-item>
              <span v-else>{{ $t("期望收费金额") }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('期望收款金额')" align="center" prop="collectionAmount">
            <template slot-scope="scope">
              <span v-if="scope.row.type !== 'total'">{{ getCurrencySymbol(scope.row.collectionCurrencyId) }}{{ scope.row.collectionAmount }}</span>
              <div v-else>
                <div v-for="itemAmount in scope.row.collectionAmount">
                  <!-- {{ itemAmount }}-- {{ $i18n.locale == "zh_CN" ? (itemAmount ? itemAmount.currencyNameZh : "") : itemAmount ? itemAmount.currencyNameEn : "" }}: -->
                  {{ getCurrencySymbol(itemAmount.currencyId) }}
                  {{ itemAmount && itemAmount.amount ? itemAmount.amount : 0 }}
                </div>
                <!--                <div v-if="scope.row.collectionAmount[1]">{{ $t('人民币') }}: {{ scope.row.collectionAmount[1].toFixed(6) }}</div>
                <div v-if="scope.row.collectionAmount[2]">{{ $t('奈拉') }}: {{ scope.row.collectionAmount[2].toFixed(6) }}</div>
                <div v-if="scope.row.collectionAmount[3]">{{ $t('西非法郎') }}: {{ scope.row.collectionAmount[3].toFixed(6) }}</div> -->
              </div>
              <!-- <dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="scope.row.currencyId" /> -->
            </template>
          </el-table-column>
        </el-table>
        <el-descriptions :column="2" border class="card">
          <el-descriptions-item :label="$t('账单汇率有效期')">
            <el-form-item label="" label-width="0" style="margin-bottom: 0" prop="rateValidateDate">
              <el-date-picker v-model="form.rateValidateDate" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" :placeholder="$t('选择日期时间')"> </el-date-picker>
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
      <el-card class="card">
        <el-form-item style="margin-bottom: 0; margin-top: 20px" prop="openInvoice">
          <span style="margin-right: 20px"><span style="color: #ff4949">*</span>{{ $t("是否需要开票") }}:</span>
          <el-select v-model="form.openInvoice" :placeholder="$t('请选择是否需要开票')">
            <el-option :value="1" :label="$t('是')"></el-option>
            <el-option :value="0" :label="$t('否')"></el-option>
          </el-select>
        </el-form-item>
      </el-card>

      <!-- 开票资料 -->
      <el-card v-if="showInvoice" class="card">
        <div slot="header" class="card-title">{{ $t("开票资料") }}</div>
        <el-descriptions :column="3" border>
          <el-descriptions-item :label="$t('发票抬头')">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="invoice"
              :rules="{
                required: true,
                trigger: ['blur', 'change'],
                message: $t('请输入发票抬头')
              }"
            >
              <el-input v-model="form.invoice"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('纳税人识别号')">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="taxpayer"
              :rules="{
                required: true,
                trigger: ['blur', 'change'],
                message: $t('请输入纳税人识别号')
              }"
            >
              <el-input v-model="form.taxpayer"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('开户行')">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="accountBank"
              :rules="{
                required: true,
                trigger: ['blur', 'change'],
                message: $t('请输入开户行')
              }"
            >
              <el-input v-model="form.accountBank"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('账号')">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="accountName"
              :rules="{
                required: true,
                trigger: ['blur', 'change'],
                message: $t('请输入账号')
              }"
            >
              <el-input v-model="form.accountName"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('开票品名')">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="projectName"
              :rules="{
                required: true,
                trigger: ['blur', 'change'],
                message: $t('请输入开票品名')
              }"
            >
              <el-input v-model="form.projectName"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('税率%')">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="taxRate"
              :rules="{
                required: true,
                trigger: ['blur', 'change'],
                message: $t('请输入税率')
              }"
            >
              <el-input v-model="form.taxRate"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('开票地址/电话')">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="addressPhone"
              :rules="{
                required: true,
                trigger: ['blur', 'change'],
                message: $t('请输入开票地址/电话')
              }"
            >
              <el-input v-model="form.addressPhone"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('开票资料备注')">
            <el-input type="textarea" rows="1" show-word-limit style="width: 78%" v-model="form.invoiceRemark" maxlength="500"></el-input>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
    </el-form>

    <div slot="header" class="bpm-title">{{ $t("审核流程") }}</div>
    <work-flow xmlkey="merge_order" v-model="form.copyUserList"></work-flow>

    <div slot="footer" style="margin: 20px 0">
      <el-button type="primary" @click="submitForm(0)" v-hasPermi="['ecw:voucher:create:sumbit']">{{ $t("提交申请") }}</el-button>
      <el-button v-if="id == 0 || form.state == 0" type="primary" :loading="saveBtnLoading" v-hasPermi="['ecw:voucher:create:save']" @click="submitForm(1)">{{ $t("保存草稿") }}</el-button>
      <el-button v-if="orderData.inWarehouseState == 207" type="primary" v-hasPermi="['ecw:voucher:create:see']" @click="$router.push(`/bpm/process-instance/detail?id=` + orderApprovalBackVO.applyingFormId)">{{ $t("审核中") }}</el-button>

      <el-button plain type="primary" @click="$store.dispatch('tagsView/delCurrentView')">{{ $t("返回") }}</el-button>
    </div>

    <!-- 添加应收明细的弹窗 -->
    <el-dialog :visible.sync="open" :title="$t('添加未收客户款项')" width="80%" append-to-body @open="getList">
      <div>
        <!-- <div slot="header" class="card-title">{{ $t('添加未收客户款项') }}</div> -->
        <!-- 搜索工作栏 -->
        <el-form v-if="open" :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="80px">
          <el-row>
            <el-form-item :label="$t('始发仓')">
              <el-select v-model="queryParams.departureId" :placeholder="$t('请选择始发地')">
                <el-option v-for="item in expoerCityList" :label="item.titleZh" :value="item.id" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('目的仓')">
              <el-select v-model="queryParams.objectiveId" :placeholder="$t('请选择始发地')">
                <el-option v-for="item in importCityList" :label="item.titleZh" :value="item.id" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('运输方式')">
              <dict-selector :type="DICT_TYPE.ECW_TRANSPORT_TYPE" v-model="queryParams.transportId" formatter="number" />
            </el-form-item>
            <el-form-item :label="$t('出货渠道')">
              <el-select v-model="queryParams.channelId" :placeholder="$t('请选择出货渠道')">
                <el-option v-for="item in channelList" :label="item.nameZh" :value="item.channelId" :key="item.channelId"></el-option>
              </el-select>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item :label="$t('报关方式')">
              <dict-selector :type="DICT_TYPE.ECW_CUSTOMS_TYPE" v-model="queryParams.customsType" />
            </el-form-item>
            <el-form-item :label="$t('控货')">
              <dict-selector :type="DICT_TYPE.INFRA_BOOLEAN_STRING" v-model="queryParams.control" />
            </el-form-item>
            <el-form-item :label="$t('客户名称')">
              <customer-selector v-model="queryParams.customerId" @change="consignor = $event" />
            </el-form-item>
          </el-row>
          <el-form-item :label="$t('订单编号')" prop="orderNo">
            <el-input v-model="queryParams.orderNo" :placeholder="$t('请输入订单编号')" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>

          <el-form-item :label="$t('提单号')" prop="tidanNo">
            <el-input v-model="queryParams.tidanNo" :placeholder="$t('请输入提单号')" clearable @keyup.enter.native="handleQuery" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">{{ $t("查询") }}</el-button>
          </el-form-item>
        </el-form>
        <div class="hintBox">{{ $t("收款单只能选择相同目的国订单") }}</div>
        <el-table ref="multipleTable" v-loading="loading1" :data="orderData" border @selection-change="handleSelectionChange" row-key="id" height="calc(100vh - 480px)">
          <el-table-column type="selection" width="55" :selectable="selectableStatus"> </el-table-column>
          <el-table-column :label="$t('订单号')" align="center" prop="orderNo" />
          <el-table-column :label="$t('提单号')" align="center" prop="tidanNo" />
          <el-table-column :label="$t('唛头')" align="center" prop="marks" />
          <el-table-column :label="$t('品名')" align="center" prop="title">
            <template slot-scope="scope">
              {{ scope.row.titleZh ? scope.row.titleZh + "(" + scope.row.titleEn + ")" : "" }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('箱数')" align="center" prop="num" />
          <el-table-column :label="$t('体积/重量')" align="center" prop="weight">
            <template slot-scope="scope"> {{ scope.row.volume }}/{{ scope.row.weight }} </template>
          </el-table-column>
          <el-table-column :label="$t('发货人')" align="center" prop="consignorName" />
          <el-table-column :label="$t('收货人')" align="center" prop="consigneeName" />
          <el-table-column :label="$t('订单状态')" align="center" prop="status">
            <template slot-scope="scope">
              <dict-tag :type="DICT_TYPE.ORDER_STATUS" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column :label="$t('收入类型')" align="center" prop="feeType">
            <template slot-scope="scope">
              <dict-tag :type="DICT_TYPE.FEE_TYPE" :value="scope.row.feeType"></dict-tag>
            </template>
          </el-table-column>
          <!-- <el-table-column :label="$t('单价美元')" align="center" prop="unitPrice" /> -->
          <el-table-column :label="$t('单价')" align="center" prop="unitPrice">
            <template slot-scope="scope">
              <span>{{ scope.row.unitPrice }}{{ getCurrencyLabel(scope.row.currencyId) }}</span>
              <!-- <dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="scope.row.currencyId" /> -->
            </template>
          </el-table-column>
          <el-table-column :label="$t('总金额')" align="center" prop="totalAmount">
            <template slot-scope="scope">
              <span>{{ scope.row.totalAmount }}{{ getCurrencyLabel(scope.row.currencyId) }}</span>
              <!-- <dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="scope.row.currencyId" /> -->
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.rows" @pagination="getList" />
        <!-- </el-card> -->
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="saveSelectList">{{ $t("确认添加") }}</el-button>
          <el-button @click="hiddenDialog">{{ $t("取消") }}</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog v-if="discountVisible" :visible.sync="discountVisible" :title="$t('优惠信息确认')" width="60%" append-to-body>
      <el-form label-width="120px">
        <el-form-item v-if="form.receiptNo" :label="$t('收款单号')">
          {{ form.receiptNo }}
        </el-form-item>
        <el-table :data="[selectListRow]" border style="margin-bottom: 22px">
          <el-table-column :label="$t('订单号')" align="center" prop="orderNo" />
          <el-table-column :label="$t('唛头')" align="center" prop="marks" />
          <el-table-column :label="$t('品名')" align="center" prop="title">
            <template slot-scope="scope">
              {{ scope.row.titleZh ? scope.row.titleZh + "(" + scope.row.titleEn + ")" : "" }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('箱数')" align="center" prop="num" />
          <el-table-column :label="$t('体积/重量')" align="center" prop="weight">
            <template slot-scope="scope"> {{ scope.row.volume }}/{{ scope.row.weight }} </template>
          </el-table-column>
          <el-table-column :label="$t('收入类型')" align="center" prop="feeType">
            <template slot-scope="scope">
              <dict-tag :type="DICT_TYPE.FEE_TYPE" :value="scope.row.feeType"></dict-tag>
            </template>
          </el-table-column>
          <el-table-column :label="$t('单价金额')" align="center" prop="unitPrice">
            <template slot-scope="scope">
              <span>{{ scope.row.unitPrice }}{{ getCurrencyLabel(scope.row.currencyId) }}</span>
              <!-- <dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="scope.row.currencyId" /> -->
            </template>
          </el-table-column>
          <el-table-column :label="$t('总金额')" align="center" prop="totalAmount">
            <template slot-scope="scope">
              <span>{{ scope.row.taxAmount }}{{ getCurrencyLabel(scope.row.currencyId) }}</span>
              <!-- <dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="scope.row.currencyId" /> -->
            </template>
          </el-table-column>
        </el-table>
        <el-form-item :label="$t('总金额')"> {{ selectListRow.taxAmount }}{{ getCurrencyLabel(selectListRow.currencyId) }} </el-form-item>
        <el-form-item :label="$t('优惠金额')">
          <el-input v-model="discountForm.discountTotal" type="number" min="0" :max="selectListRow.totalAmount" @input="checkDiscount" style="width: 300px"></el-input>
          &nbsp;&nbsp;{{ getCurrencyLabel(selectListRow.currencyId) }}
        </el-form-item>
        <el-form-item :label="$t('优惠原因')">
          <el-input v-model="discountForm.discountRemark" type="textarea" style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item :label="$t('优惠后')">
          {{ (selectListRow.taxAmount - (discountForm.discountTotal || 0)).toFixed(2) }}
          {{ getCurrencyLabel(selectListRow.currencyId) }}
        </el-form-item>
        <el-form-item v-if="opnotice" :label="$t('操作人')">
          {{ discountForm.author }}
        </el-form-item>
        <el-form-item v-if="opnotice" :label="$t('操作时间')">
          {{ discountForm.time }}
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveDiscount">{{ $t("提交") }}</el-button>
        <el-button @click="cancelDiscount">{{ $t("取消") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSimpleUsers } from "@/api/system/user"
import { DICT_TYPE } from "@/utils/dict"
import { getToken } from "@/utils/auth"
import CustomerSelector from "@/components/CustomerSelector"
import CustomerSelectorpay from "@/components/CustomerSelectorpay"
import { getBankAccountPage } from "@/api/ecw/bankAccount"
import { listSimpleDepts } from "@/api/system/dept"
import { getChannelList } from "@/api/ecw/channel"
import { getTradeCityList } from "@/api/ecw/region"
import { createReceipt, getReceivableByOrderId, getReceivableList, getReceivableItemDetail, getReceiptInfoByIds, getReceiptAccountList, getInvoicingItem, updateReceipt, updateReceivableDiscountById, getReceivableDiscountLogById } from "@/api/ecw/financial"
import { getCustomer } from "@/api/ecw/customer"
import NP from "number-precision"
import { getOrder, getDestCountryByOrderId } from "@/api/ecw/order"
import { getCurrencyPage } from "@/api/ecw/currency"
import { getExchangeRatePage } from "@/api/ecw/exchangeRate"
import ret from "bluebird/js/release/util"
import dayjs from "dayjs"
import { getUserProfile } from "@/api/system/user"
import { getWarehouseList } from "@/api/ecw/warehouse"
import WorkFlow from "@/components/WorkFlow/"
import { mapGetters } from "vuex"
import { list } from "@/api/system/loginlog"
export default {
  name: "EcwFinancialCreatcollection",
  components: {
    CustomerSelector,
    WorkFlow,
    CustomerSelectorpay
  },
  data() {
    return {
      NP,
      loadings: false,
      loading1: false,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/app-api/file/upload", // 上传的图片服务器地址
      form: {
        receiptAccountList: [],
        departmentId: "",
        salesmanId: "",
        salesmanName: ""
      },
      creatorData: [],
      list: [],
      // fileList: [],
      orderData: [],
      opnotice: false,
      dialogTableKey: 0,
      total: 0,
      headers: {
        Authorization: "Bearer " + getToken()
      },
      loading: "",
      open: false,
      bankData: [],
      params: {
        page: 1,
        rows: 100
      },
      deptData: [],
      deptArr: [],
      oadings: false,
      channelList: [],
      queryParams: {
        page: 1,
        rows: 20
      },
      multipleSelection: [],
      tradeCityList: [],
      id: 0,
      receiptId: 0,
      currencyList: [],
      saveBtnLoading: false,
      discountVisible: false,
      discountForm: {
        author: ""
      },
      selectListRow: {},
      selectListIndex: 0,
      flag: false,
      warehouseList: [],
      selectedUsers: [],
      dialogVisible: false,
      codeLoading: false,
      codePage: {
        pageNo: 1,
        pageSize: 100
      },
      pages: 1,
      rateList: [],
      userInfo: null,
      //订单编号 lanbm 2024-05-20 add
      orderId: undefined
    }
  },
  async activated() {
    let that = this
    await getUserProfile().then((res) => (that.userInfo = res.data))
    if (that.$route.query.id) {
      that.flag = true
      that.id = that.$route.query.id
      that.getReceivableData()
    } else {
      that.removeData()
      that.$set(that.form, "departmentId", that.userInfo.deptId)
      that.$set(that.discountForm, "author", that.userInfo.nickname)
      that.$set(that.form, "salesmanId", that.userInfo.id)
      that.$set(that.form, "salesmanName", that.userInfo.nickname)
    }
    if (that.$route.query.receiptId && that.$route.query.receiptId != 0) {
      that.receiptId = that.$route.query.receiptId
      that.getReceivableInfo()
    } else {
      // that.removeData()
    }
    if (that.$route.query.orderId) {
      getReceivableByOrderId({ orderId: that.$route.query.orderId }).then((response) => {
        that.list = [...response.data]
        that.list.map((v) => {
          if (!v.taxPoint) {
            v.taxAmount = v.totalAmount
          }
        })
        that.calculation()
        getOrder(that.$route.query.orderId).then((response) => {
          // console.log(response.data)
          if (response.data.customerId) {
            that.$set(that.form, "customerId", response.data.customerId)
          } else {
            if (response.data.drawee == 1) {
              that.$set(that.form, "customerId", response.data.consignorVO.customerId)
            } else if (response.data.drawee == 2) {
              that.$set(that.form, "customerId", response.data.consigneeVO.customerId)
            } else {
              if (response.data.customDraweeVOList) {
                response.data.customDraweeVOList.map((v) => {
                  if (v.name == "freight") {
                    if (v.value == 1) {
                      that.$set(that.form, "customerId", response.data.consignorVO.customerId)
                    } else {
                      that.$set(that.form, "customerId", response.data.consigneeVO.customerId)
                    }
                  }
                })
              }
            }
          }
        })
        getDestCountryByOrderId({ orderId: that.$route.query.orderId }).then((response) => {
          // console.log(response.data)
          if (response.data) that.$set(that.queryParams, "destCountry", response.data)
        })
      })
    }
  },
  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 getUserProfile().then((res) => (this.userInfo = res.data))
    // 获取汇率
    await getCurrencyPage(this.params).then((res) => (this.currencyList = res.data.list))
    await getExchangeRatePage(this.params).then((res) => (this.rateList = res.data.list))
    getWarehouseList().then((res) => (this.warehouseList = res.data))
    let that = this
    if (that.$route.query.orderId) {
      //lanbm 2024-05-20 添加订单ID
      this.orderId = that.$route.query.orderId
      await getReceivableByOrderId({ orderId: that.$route.query.orderId }).then((response) => {
        this.list = [...response.data]
        this.list.map((v) => {
          if (!v.taxPoint) {
            v.taxAmount = v.totalAmount
          }
        })
        this.calculation()
        getOrder(that.$route.query.orderId).then((response) => {
          if (response.data.customerId) {
            that.$set(that.form, "customerId", response.data.customerId)
          } else {
            if (response.data.drawee == 1) {
              that.$set(that.form, "customerId", response.data.consignorVO.customerId)
            } else if (response.data.drawee == 2) {
              that.$set(that.form, "customerId", response.data.consigneeVO.customerId)
            } else {
              if (response.data.customDraweeVOList) {
                response.data.customDraweeVOList.map((v) => {
                  if (v.name == "freight") {
                    if (v.value == 1) {
                      that.$set(that.form, "customerId", response.data.consignorVO.customerId)
                    } else {
                      that.$set(that.form, "customerId", response.data.consigneeVO.customerId)
                    }
                  }
                })
              }
            }
          }
        })
      })
      getDestCountryByOrderId({ orderId: this.$route.query.orderId }).then((response) => {
        if (response.data) this.$set(this.queryParams, "destCountry", response.data)
      })
    }
    if (that.$route.query.id) {
      this.flag = true
      this.id = this.$route.query.id
      this.getReceivableData()
    } else {
      this.discountForm.author = this.userInfo.nickname
      this.form.departmentId = this.userInfo.deptId
      this.form.salesmanId = this.userInfo.id
      this.$set(this.form, "salesmanName", this.userInfo.nickname)
    }
    if (that.$route.query.receiptId && that.$route.query.receiptId !== "0") {
      this.receiptId = this.$route.query.receiptId
      this.getReceivableInfo()
    }

    // this.getList();
    // if(that.$route.query.consignorId){
    //   this.queryParams.consignorId = this.$route.query.consignorId
    // }
    // if(that.$route.query.writeOffName){
    //   this.form.writeOffName = this.$route.query.writeOffName
    // }
    listSimpleUsers().then((res) => (that.creatorData = res.data))
    getChannelList().then((res) => (that.channelList = res.data))
    getTradeCityList().then((res) => (that.tradeCityList = res.data))
    this.getCodeList()
    listSimpleDepts().then((res) => {
      that.deptData = res.data
      // res.data.forEach((item) => {
      //   if (item.parentId == 0) {
      //     that.deptArr.push(item);
      //   } else {
      //     that.deptData.push(item);
      //   }
      // });

      // that.deptData.forEach((value) => {
      //   var dept = res.data.filter((itt) => itt.id == value.parentId);
      //   if (dept.length > 0) {
      //     value.name = dept[0].name + " | " + value.name;
      //   }
      // });
    })
  },
  computed: {
    ...mapGetters(["getCurrencySymbol", "getCurrencyData"]),
    getBaseCurrencynName() {
      return (currencyId) => {
        if (currencyId && currencyId != "XX") {
          return this.$l(this.getCurrencyData(currencyId), "title")
        } else {
          return "XX"
        }
      }
    },
    expoerCityList() {
      // return this.tradeCityList.filter((item) => item.type == 2);
      return this.warehouseList.filter((item) => item.tradeType == 2 || item.tradeType == 3)
    },
    importCityList() {
      // return this.tradeCityList.filter((item) => item.type == 1);
      return this.warehouseList.filter((item) => item.tradeType == 1 || item.tradeType == 3)
    },
    showCurrencyId() {
      // let fieldList = []
      // let groupList = []
      // this.list.map((element) => {
      //   if (fieldList.indexOf(element["currencyId"]) === -1) {
      //     fieldList.push(element["currencyId"])
      //   }
      // })
      // console.log("90129", this.list)
      // 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

      // 2.2更改基准币种的获取
      if (this.list.length > 0) {
        return this.list[0].baseCurrencyId
      } else {
        return "XX"
      }
    },
    showInvoice() {
      return this.form.openInvoice == 1
    }
  },
  methods: {
    // 禁用选中有基准币种
    selectableStatus(row, index) {
      // return true
      if (this.list.length > 0 && this.list[0].baseCurrencyId != row.baseCurrencyId) {
        return false
      } else {
        if (this.multipleSelection.length > 0 && this.multipleSelection[0].baseCurrencyId != row.baseCurrencyId) {
          return false
        } else {
          return true
        }
      }
    },
    //应收明细合计
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = this.$t("合计金额")
          return
        } else if (column.property != "unitPrice" && column.property != "notIncludedTaxAmount" && column.property != "taxAmount" && column.property != "discountTotal" && column.property != "actualAmount" && column.property != "writeOffAmount" && column.property != "notWriteOffAmount" && column.property != "baseAmount" && column.property != "writeOffAmountUsd" && column.property != "notWriteOffAmountUsd") {
          sums[index] = "NA"
          return
        } else {
          const currencySums = {}
          data.forEach((item) => {
            let currencyId = item.currencyId
            // 基准金额（XX)baseAmount   已核销金额 writeOffAmountUsd 未核销金额 notWriteOffAmountUsd 币种取 基准币种
            if (column.property == "writeOffAmountUsd" || column.property == "baseAmount" || column.property == "notWriteOffAmountUsd") {
              currencyId = item.baseCurrencyId
            }

            currencySums[currencyId] = NP.plus(currencySums[currencyId] || 0, item[column.property])
            // (currencySums[currencyId] || 0) + parseInt(item[column.property], 10)
          })
          const reducedDataList = Object.keys(currencySums).map((currencyId) => {
            return `${this.getCurrencySymbol(currencyId * 1)}${currencySums[currencyId].toString()}  `
          })
          sums[index] = reducedDataList
          return
        }
      })

      return sums
    },
    // 用于格式化货币的函数
    formatCurrency(row, column, cellValue) {
      if (column.property == "baseAmount" || column.property == "writeOffAmountUsd" || column.property == "notWriteOffAmountUsd") {
        return this.getCurrencySymbol(row.baseCurrencyId) + (cellValue || "0")
      }
      return this.getCurrencySymbol(row.currencyId) + (cellValue || "0")
    },
    // 懒加载
    loadmore() {
      this.codePage.pageNo++
      // 大于页码不请求了
      console.log(111)
      if (this.codePage.pageNo > this.pages) {
        return
      }
      this.getCodeList()
    },
    getCodeList(flag) {
      if (flag) {
        this.bankData = []
        this.codeLoading = true
      }
      setTimeout(() => {
        getBankAccountPage(this.codePage).then((res) => {
          this.codeLoading = false
          this.bankData = this.bankData.concat(res.data.list)
          this.pages = res.data.total / this.codePage.pageSize + 1
        })
      }, 200)
    },
    getReceivableData() {
      getReceiptInfoByIds({ id: this.id }).then((res) => {
        if (res.data.rateValidateDate) res.data.rateValidateDate = dayjs(res.data.rateValidateDate).format("YYYY-MM-DD HH:mm:ss")
        this.form = Object.assign({}, this.form, res.data)
        this.discountForm.author = this.userInfo.nickname
        if (!this.form.departmentId) this.form.departmentId = this.userInfo.deptId
        if (!this.form.salesmanId) this.form.salesmanId = this.userInfo.id
        if (!this.form.salesmanName) this.$set(this.form, "salesmanName", this.userInfo.nickname)
        if (res.data.invoiceId && res.data.invoiceVO) {
          this.form = {
            ...this.form,
            ...res.data.invoiceVO
          }
        }
      })
      getInvoicingItem({ id: this.id }).then((res) => {
        this.list = [...res.data]
        this.list.map((v) => {
          if (!v.taxPoint) {
            v.taxAmount = v.totalAmount
          }
        })
      })
      getReceiptAccountList({ id: this.id }).then((res) => {
        if (res.data.length > 0) {
          // totalAmount
          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)

        this.$nextTick(() => {
          // const dollarList = this.list.filter(v => v.currencyId === 1)
          // const discountDollar = dollarList.reduce((total, currentValue) => NP.plus(total, currentValue.discountTotal || 0), 0)
          // const d = this.form.receiptAccountList.find(v => v.currencyId == 1)
          // d && (d.discountTotal = discountDollar)

          // const rmbList = this.list.filter(v => v.currencyId === 2)
          // const discountRmb = rmbList.reduce((total, currentValue) => NP.plus(total, currentValue.discountTotal || 0), 0)
          // const r = this.form.receiptAccountList.find(v => v.currencyId == 2)
          // r && (r.discountTotal = discountRmb)

          // const nairaList = this.list.filter(v => v.currencyId === 3)
          // const discountNaira = nairaList.reduce((total, currentValue) => NP.plus(total, currentValue.discountTotal || 0), 0)
          // const n = this.form.receiptAccountList.find(v => v.currencyId == 3)
          // n && (n.discountTotal = discountNaira)

          // this.form.receiptAccountList.forEach((item, index) => {
          //   this.rateChange(item, index)

          // });
          if (this.form.receiptAccountList.length > 0) {
            this.editReceiptAccountList()
          }
          // this.calculation()
        })
      })
    },
    getReceivableInfo() {
      getReceivableItemDetail({ id: this.receiptId }).then((res) => {
        this.list = res.data
        this.list.map((v) => {
          if (!v.taxPoint) {
            v.taxAmount = v.totalAmount
          }
        })
        this.calculation()

        getOrder(res.data.orderId).then((response) => {
          // console.log(response.data)
          if (response.data.customerId) this.$set(this.form, "customerId", response.data.customerId)
        })
      })
    },
    getCurrencyLabel(id) {
      var 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 "XX"
    },
    checkDiscount(e) {
      if (e > this.selectListRow.totalAmount) {
        this.discountForm.discountTotal = this.selectListRow.totalAmount
      }
    },
    currencyIdChange(val, row, index) {
      row.collectionCurrencyId = val
      if (val == row.currencyId) row.collectionRate = 1
      else {
        // if (row.currencyId == 1 && val == 3) row.collectionRate = this.UStoRMB()
        // if (row.currencyId == 1 && val == 2) row.collectionRate = this.UStoNAN()
        // if (row.currencyId == 3 && val == 1) row.collectionRate = this.RMBtoUS()
        // if (row.currencyId == 3 && val == 2) row.collectionRate = this.RMBtoNAN()
        // if (row.currencyId == 2 && val == 1) row.collectionRate = this.NANtoUS()
        // if (row.currencyId == 2 && val == 3) row.collectionRate = this.NANtoRMB()
        // row.collectionRate = NP.times(this.currencyList.find(v => v.id === row.currencyId).huilv/100, this.currencyList.find(v => v.id === val).exchangeToFc/100).toFixed(6)
        row.collectionRate = this.getRate(row.currencyId, val)
      }

      this.rateChange(row, index)
    },
    //获取汇率
    getRate(sourceCurrencyId, targetCurrencyId) {
      var rate = this.rateList.find((v) => v.sourceCurrencyId === sourceCurrencyId && v.targetCurrencyId === targetCurrencyId)
      if (rate) return rate.currencyRate
      return ""
    },
    writeOffRateChange(row, index) {
      if (row.writeOffRate == 0 && parseInt(row.writeOffRate) === 0) {
        this.$modal.msgError(this.$t("汇率不能为0，请输入正确的汇率"))
      }
      if (row.writeOffRate) {
        row.writeOffAmount = NP.times(row.writeOffRate || 0, NP.minus(row.receivableAmount, row.discountTotal || 0)).toFixed(2)
      } else {
        row.writeOffAmount = ""
      }

      const writeOffAmountTotal = this.form.receiptAccountList.filter((v) => v.type !== "total").reduce((total, currentValue) => NP.plus(total, currentValue.writeOffAmount || 0), 0)

      this.list.forEach((item) => {
        if (item.currencyId == row.currencyId) {
          item.exchangeRate = row.writeOffRate

          item.baseAmount = NP.round(NP.times(row.writeOffRate || 0, item.actualAmount), 2)
        }
      })
      // this.list[index].exchangeRate = row.writeOffRate
      // this.list[index].baseAmount = row.writeOffAmount
      // console.log("listdd", this.list)

      this.form.receiptAccountList[this.form.receiptAccountList.length - 1].writeOffAmount = writeOffAmountTotal
    },
    rateChange(row, index) {
      if (row.collectionRate == 0 && parseInt(row.collectionRate) === 0) {
        this.$modal.msgError(this.$t("汇率不能为0，请输入正确的汇率"))
      }
      if (row.collectionRate) {
        row.receivableAmount && (row.collectionAmount = NP.times(row.collectionRate || 0, NP.minus(row.receivableAmount, row.discountTotal || 0)).toFixed(2))
      } else {
        row.collectionAmount = ""
      }
      this.form.receiptAccountList[index] = { ...row }

      setTimeout(() => {
        // 收款总计
        this.editReceiptAccountList()
      }, 100)
    },
    editReceiptAccountList() {
      var amountList = []
      this.currencyList.forEach((item, index) => {
        var dollarList = this.form.receiptAccountList.filter((v) => v.collectionCurrencyId == item.id)
        if (dollarList.length > 0) {
          var dollar = dollarList.reduce((total, currentValue) => NP.plus(total, currentValue.collectionAmount), 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])
    },
    //明细改变税率
    changeTaxRate(row, index) {
      var pointArr = []
      var regs = /^[0-9]+\d*(\.\d*)?$|^0?\.\d*[0-9]\d*$/
      //taxPoint 税率
      if (row.taxPoint && !regs.test(row.taxPoint)) {
        row.taxPoint = ""
        this.$modal.msgError(this.$t("输入税率格式不对"))
      } else {
        pointArr = row.taxPoint.split(".")
        if (pointArr.length > 1 && pointArr[1]) {
          row.taxPoint = Math.round(row.taxPoint * 100) / 100
        }
      }
      if (row.taxPoint) {
        var amout = NP.times(NP.divide(row.taxPoint, 100), row.totalAmount)
        row.taxAmount = NP.round(NP.plus(row.totalAmount, amout), 2)
      } else {
        row.taxAmount = row.totalAmount
      }
      // 财务2.2.  实际金额 含税金额-优惠金额
      row.actualAmount = NP.minus(row.taxAmount, row.discountTotal)
      //财务2.2 基准金额 实际金额*账单明细对应应收币种汇率（保留两位小数）
      row.baseAmount = NP.round(NP.times(row.actualAmount, row.exchangeRate), 2)
      this.list[index] = { ...row }
      let dataArrTemp = JSON.stringify(this.list)
      this.list = JSON.parse(dataArrTemp)
      if (pointArr.length > 1 && !pointArr[1]) {
        return
      } else {
        this.calculation()
      }
    },
    calculation() {
      const copyList = this.form.receiptAccountList
      this.form.receiptAccountList = []
      this.currencyList.forEach((item, index) => {
        var dollarList = this.list.filter((v) => v.currencyId === item.id)
        if (dollarList.length > 0) {
          let dollar, discountDollar
          dollar = dollarList.reduce((total, currentValue) => NP.plus(total, currentValue.taxAmount || 0), 0)
          discountDollar = dollarList.reduce((total, currentValue) => NP.plus(total, currentValue.discountTotal || 0), 0)
          var t = copyList.find((v) => v.currencyId == item.id)
          this.form.receiptAccountList.push({
            discountTotal: discountDollar,
            currencyId: item.id,
            receivableAmount: NP.round(dollar, 2),
            writeOffRate: item.id == this.showCurrencyId ? 1 : dollarList[0].exchangeRate,
            // this.getRate(item.id, this.showCurrencyId),
            platformAccountId: t?.platformAccountId || "",
            collectionCurrencyId: item.id,
            collectionRate: 1
          })
          this.calculationCount(NP.minus(dollar, discountDollar), item.id)
        }
      })

      if (this.form.receiptAccountList.length > 0) {
        // totalAmount
        const totalt = this.form.receiptAccountList.reduce((total, currentValue) => NP.plus(total, currentValue.writeOffAmount || 0), 0)
        this.form.receiptAccountList = [
          ...this.form.receiptAccountList,
          {
            type: "total",
            writeOffAmount: totalt.toFixed(2),
            collectionAmount: []
          }
        ]

        this.form.receivableTotalAmount = totalt.toFixed(2)
      }

      this.$set(this.form, "receiptAccountList", [...this.form.receiptAccountList])
    },
    calculationCount(usCount, type) {
      const index = this.form.receiptAccountList.findIndex((v) => v.currencyId == type)
      const t = this.form.receiptAccountList[index]
      if (t) {
        t.writeOffAmount = NP.times(t.writeOffRate || 0, usCount).toFixed(2)
        this.rateChange(t, index)
      }
    },
    saveDiscount() {
      console.log(this.discountForm)
      // this.selectListRow.id
      if (this.discountForm.discountTotal === 0 || !this.discountForm.discountTotal) {
        this.$modal.msgError(this.$t("优惠金额不能为空"))
        return
      }
      if (this.discountForm.discountRemark === 0 || !this.discountForm.discountRemark) {
        this.$modal.msgError(this.$t("优惠原因不能为空"))
        return
      }
      const params = {
        id: this.selectListRow.id,
        discountTotal: this.discountForm.discountTotal,
        discountRemark: this.discountForm.discountRemark,
        orderNo: this.selectListRow.orderNo,
        orderId: this.selectListRow.orderId,
        taxPoint: this.selectListRow.taxPoint,
        taxAmount: this.selectListRow.taxAmount
      }
      updateReceivableDiscountById(params).then((res) => {
        if (this.selectListRow.discountTotal) {
          this.$modal.msgSuccess(this.$t("修改成功"))
        } else {
          this.$modal.msgSuccess(this.$t("新增成功"))
        }
        // if(this.id>0){
        //    getInvoicingItem({ id: this.id }).then(res => {
        //     this.list = [...res.data]
        //     this.cancelDiscount()
        //     this.calculation()
        //   })
        // }else{
        var discount = this.list[this.selectListIndex]
        discount["discountTotal"] = this.discountForm.discountTotal
        discount["discountRemark"] = this.discountForm.discountRemark
        // 财务2.2 实际金额与基准金额变化
        // 财务2.2.  实际金额 含税金额-优惠金额
        discount["actualAmount"] = NP.minus(discount.taxAmount, discount.discountTotal)
        //财务2.2 基准金额 实际金额*账单明细对应应收币种汇率（保留两位小数）
        discount["baseAmount"] = NP.round(NP.times(discount.actualAmount, discount.exchangeRate), 2)

        setTimeout(() => {
          // getReceivableInfoByIds({ id: this.selectListRow.id }).then(res => {
          this.$set(this.list, this.selectListIndex, { ...discount })
          this.cancelDiscount()
          this.calculation()
          // })
        }, 1000)

        // }
      })
    },
    RMBtoUS() {
      return NP.divide(100, this.currencyList.find((v) => v.titleEn === "USD").huilv).toFixed(6)
    },
    NANtoUS() {
      return NP.times(this.RMBtoUS(), this.NANtoRMB()).toFixed(6)
    },
    UStoRMB() {
      return NP.divide(this.currencyList.find((v) => v.titleEn === "USD").huilv, 100).toFixed(6)
    },
    UStoNAN() {
      return NP.times(this.RMBtoNAN(), this.UStoRMB()).toFixed(6)
    },
    RMBtoNAN() {
      return NP.divide(100, this.currencyList.find((v) => v.titleEn === "NGN").huilv).toFixed(6)
    },
    NANtoRMB() {
      return NP.divide(this.currencyList.find((v) => v.titleEn === "NGN").huilv, 100).toFixed(6)
    },
    customerChange(value) {
      if (this.flag || !value) {
        this.flag = false
        return
      }
      this.form.customerName = value.payerName ? value.payerName : value.name
      this.form.customerId &&
        getCustomer(this.form.customerId).then((res) => {
          this.form = {
            ...this.form,
            openInvoice: res.data.defaultBilling ? 1 : 0,
            invoice: res.data.invoiceTitle,
            taxpayer: res.data.licenseNumber,
            accountBank: res.data.bank,
            accountName: res.data.bankNumber,
            projectName: res.data.project,
            taxRate: res.data.taxRate,
            addressPhone: `${res.data.billingAddress || ""}/${res.data.billingTell || ""}`
          }
        })
    },
    cancelDiscount() {
      this.discountVisible = false
      this.discountForm = {}
      this.selectListRow = {}
    },
    addDiscount(row, index) {
      this.discountVisible = true
      this.selectListRow = { ...row }
      console.log(this.selectListRow)
      this.selectListIndex = index
      this.$set(this.discountForm, "time", dayjs().format("YYYY-MM-DD HH:mm:ss"))
      getReceivableDiscountLogById({ id: row.id }).then((res) => {
        if (res.data?.creatorName) {
          this.$set(this.discountForm, "time", dayjs(res.data.createTime).format("YYYY-MM-DD HH:mm:ss"))
          this.$set(this.discountForm, "discountTotal", res.data.discountTotal)
          this.$set(this.discountForm, "discountRemark", res.data.discountRemark)
          this.$set(this.discountForm, "author", res.data.creatorName)
          this.opnotice = true
        } else {
          this.opnotice = false
          this.$set(this.discountForm, "discountTotal", "")
          this.$set(this.discountForm, "discountRemark", "")
          this.$set(this.discountForm, "author", "")
        }
      })
    },

    getList() {
      this.loading1 = true
      // 处理查询参数
      let params = { ...this.queryParams }
      this.addBeginAndEndTime(params, this.dateType, "createTime")
      // 执行查询
      getReceivableList(params).then((response) => {
        this.orderData = response.data.list
        this.dialogTableKey++
        this.total = response.data.total
        this.loading1 = false
        this.$nextTick(() => {
          console.log("list2", this.list)
          this.list.forEach((itm) => {
            const t = this.orderData.find((v) => v.id == itm.id)
            t && this.$refs.multipleTable.toggleRowSelection(t, true)
          })
        })
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.queryParams.customerId = this.form.customerId
      this.multipleSelection = this.list
      this.open = true
    },
    hiddenDialog() {
      this.open = false
      this.queryParams.customerId = ""
    },
    changePlatformAccountId(platformAccountId, index) {
      this.form.receiptAccountList[index].platformAccountId = platformAccountId
    },
    submitForm(addType) {
      // const params = {...this.form}
      const params = JSON.parse(JSON.stringify(this.form))
      params.addType = addType
      // params.receiptAccountList = params.receiptAccountList.map(v => Object.assign(v, {  }))
      if (!params.customerId) {
        this.saveBtnLoading = false
        this.$modal.msgError(this.$t("客户不能为空"))
        return
      }
      if (!params.departmentId) {
        this.saveBtnLoading = false
        this.$modal.msgError(this.$t("部门不能为空"))
        return
      }
      if (!params.salesmanId) {
        this.saveBtnLoading = false
        this.$modal.msgError(this.$t("业务员不能为空"))
        return
      }
      if (params.openInvoice != 0 && params.openInvoice != 1) {
        console.log(params.openInvoice)
        this.saveBtnLoading = false
        this.$modal.msgError(this.$t("请选择是否需要开票"))
        return
      }
      if (this.list && this.list.length > 0) {
        params.receivableVOList = this.list
      } else {
        this.saveBtnLoading = false
        this.$modal.msgError(this.$t("请添加未收客户款项"))
        return
      }

      // params.receiptAccountList.length = params.receiptAccountList.length - 1

      var saveStatus = true
      var writeStatus = true
      var reatStatus = true
      params.receiptAccountList.forEach((v) => {
        if (v.type != "total") {
          if (!v.platformAccountId) {
            saveStatus = false
          }
          if (!v.writeOffRate) {
            writeStatus = false
          }
          if (!v.collectionRate) {
            reatStatus = false
          }
          var bankname = this.bankData.filter((item) => item.id == v.platformAccountId)
          if (bankname.length > 0) {
            v.platformAccountName = bankname[0].baAccountName
            v.platformAccountNo = bankname[0].baAccountNum
            v.platformAccountBlankName = bankname[0].baBankName
          }
          delete v.discountTotal
          v.writeOffRate = Number(v.writeOffRate)
        }
      })
      if (!writeStatus) {
        this.$modal.msgError(this.$t("核销基准币种汇率不能为0，请输入正确的汇率"))
        return
      }
      //  v2.2. 期望收款账号改为非必填
      // if (!saveStatus) {
      //   this.$modal.msgError(this.$t("请添加收款账户"))
      //   return
      // }
      if (!reatStatus) {
        this.$modal.msgError(this.$t("期望收款汇率不能为0，请输入正确的汇率"))
        return
      }
      delete params.receivableDetail
      // v2.2 开票资料
      if (params.openInvoice == 1) {
        params.receiptInvoice = {
          accountBank: params.accountBank,
          accountName: params.accountName,
          addressPhone: params.addressPhone,
          invoice: params.invoice,
          projectName: params.projectName,
          invoiceRemark: params.invoiceRemark,
          taxRate: params.taxRate,
          taxpayer: params.taxpayer
        }
      }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (addType === 1) {
            this.saveBtnLoading = true
            params.receiptAccountList.splice(params.receiptAccountList.length - 1, 1)
            if (this.id && this.id != 0) {
              params.updateType = 0
              updateReceipt(params)
                .then((res) => {
                  this.$modal.msgSuccess(this.$t("提交成功"))
                  this.$store.dispatch("tagsView/delCurrentView")
                })
                .finally(() => {
                  this.saveBtnLoading = false
                })
            } else {
              params.currencyId = this.showCurrencyId
              createReceipt(params)
                .then((res) => {
                  this.$modal.msgSuccess(this.$t("保存成功"))
                  this.$store.dispatch("tagsView/delCurrentView")
                })
                .finally(() => {
                  this.saveBtnLoading = false
                })
            }
            return
          }
          this.saveBtnLoading = true
          params.receiptAccountList.splice(params.receiptAccountList.length - 1, 1)

          if (this.id && this.id != 0) {
            // if(params.state==0) params.state = 1
            params.updateType = 1
            //lanbm 2024-05-20 添加订单ID
            params.orderId = this.orderId
            updateReceipt(params)
              .then((res) => {
                this.$modal.msgSuccess(this.$t("修改成功"))
                this.$store.dispatch("tagsView/delCurrentView")
              })
              .finally(() => {
                this.saveBtnLoading = false
              })
          } else {
            params.currencyId = this.showCurrencyId
            //lanbm 2024-05-20 添加订单ID
            params.orderId = this.orderId
            createReceipt(params)
              .then((res) => {
                this.$modal.msgSuccess(this.$t("新增成功"))
                this.$store.dispatch("tagsView/delCurrentView")
              })
              .finally(() => {
                this.saveBtnLoading = false
              })
          }
        } else {
          console.log("error submit!!")
          return false
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    removedup(arr, batch) {
      if (!Array.isArray(arr)) {
        return arr
      }
      if (arr.length == 0) {
        return []
      }
      let obj = {}
      let uniqueArr = arr.reduce(function (total, item) {
        obj[item[batch]] ? "" : (obj[item[batch]] = true && total.push(item))
        return total
      }, [])
      return uniqueArr
    },
    saveSelectList() {
      this.multipleSelection.map((v) => {
        if (!v.taxPoint) {
          v.taxAmount = v.totalAmount
        }
      })
      if (this.list.length > 0) {
        this.list = this.list.concat(this.multipleSelection)
        this.list = this.removedup(this.list, "id")
      } else {
        this.list = this.multipleSelection
      }

      this.open = false
      this.calculation()
    },
    deleteListRow(index) {
      const list = [...this.list]
      // this.$refs.multipleTable.toggleRowSelection([list[index]], false)
      delete list[index]
      this.list = list.filter((v) => v)
      this.calculation()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    //清空数据
    removeData() {
      this.id = 0
      this.flag = false
      this.discountForm = {
        author: ""
      }
      this.$refs.customer.reset()
      this.list = []
      for (var i in this.form) {
        if (i == "receiptAccountList") {
          this.$set(this.form, i, [])
        } else {
          this.$set(this.form, i, "")
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
.card {
  margin-top: 20px;
}
.dialog-footer {
  // padding: 40px;
  text-align: left;
}
.card-title {
  font-size: 18px;
  font-weight: bold;
}
::v-deep .el-descriptions-item__label {
  width: 200px;
}
.amountCard {
  ::v-deep .el-descriptions-item__label {
    width: 20%;
  }
  ::v-deep .el-descriptions-item__content {
    width: 30%;
  }
}
.bpm-title {
  font-size: 20px;
  font-weight: bold;
  color: #666;
  margin: 20px 0;
}
.hintBox {
  font-size: 12px;
  color: #c9c9c9;
}
</style>
