<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="card-title">{{ $t('收款单详情') }}</div>
      <el-descriptions :column="3" border>
        <el-descriptions-item :label="$t('收款单编号')">{{ form.receiptNo }}</el-descriptions-item>
        <el-descriptions-item :label="$t('状态')">
          <dict-tag :type="DICT_TYPE.ECW_RECEIPT_STATE" :value="form.state"/>
        </el-descriptions-item>
        <el-descriptions-item :label="$t('客户')">{{ form.customerName }}</el-descriptions-item>
        <el-descriptions-item :label="$t('部门')">{{ form.departmentName }}</el-descriptions-item>
        <el-descriptions-item :label="$t('业务员')">{{ form.salesmanName }}</el-descriptions-item>
        <!-- <el-descriptions-item :label="$t('手续费（RMB）')">{{ form.feeRate }}</el-descriptions-item> -->
        <el-descriptions-item :label="$t('备注')">{{ form.remark }}</el-descriptions-item>
      </el-descriptions>
    </el-card>
    <el-card class="card">
      <div slot="header" class="card-title">{{ $t('应收明细') }}</div>
      <el-table :data="list" border>
        <el-table-column :label="$t('订单号')" align="center" prop="orderNo" />
        <el-table-column :label="$t('自编号')" align="center" prop="containerNumber" />
        <el-table-column :label="$t('唛头')" align="center" prop="marks" />
        <el-table-column :label="$t('品名')" align="center" prop="title">
          <template slot-scope="scope">
            <span v-if="scope.row.feeType!=5">{{ scope.row.titleZh?(scope.row.titleZh + "(" + scope.row.titleEn + ")"):'' }}</span>
          </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">
             <span v-if="scope.row.feeType!=5"> {{ scope.row.volume + "/" + scope.row.weight }}</span>
            </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 }}</span>
            {{getCurrencyLabel(scope.row.currencyId)}}
          </template>
        </el-table-column>
        <el-table-column :label="$t('总金额')" align="center" prop="totalAmount">
          <template slot-scope="scope">
            <span>{{ scope.row.totalAmount }}</span>
            {{getCurrencyLabel(scope.row.currencyId)}}
          </template>
        </el-table-column>
        <el-table-column :label="$t('优惠金额')" align="center">
          <template slot-scope="scope">
            {{ scope.row.discountTotal ? `${scope.row.discountTotal}(${scope.row.discountRemark})` : 0 }}
          </template>
        </el-table-column>
      </el-table>
      <el-descriptions :column="2" border class="card">
        <!-- <el-descriptions-item v-for="(v, index) in form.platformAccountIdList" :label="`收款账户${index + 1}`" :key="index">
          <div style="display: flex">
            <el-button type="text" v-if="index === 0" @click="form.platformAccountIdList = [...form.platformAccountIdList, {}]">{{ $t('添加收款账户') }}</el-button>
            <el-button type="text" v-if="index > 0" @click="subtractItem(index)"><span style="color: red">{{ $t('删除') }}</span></el-button>
          </div>
        </el-descriptions-item>
         -->
        <el-descriptions-item :label="$t('是否需要开票')">
          <span>{{ form.openInvoice == 1 ? $t('需要') : $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-descriptions-item>
        <el-descriptions-item>
              <template slot="label">
                {{$t('核销基准币种')}}
                <span :title="$t('应收可能出现多个币种的情况，多个币种没法计算整个收款单的核销比例，所以增加一个中间币种，如果应收只有一个币种就使用应收币种，如果有多个币种就以美元为核销基准币种')"><i class="el-icon-question"></i></span>
<!--                  <el-tooltip class="item" effect="light" :content="$t('应收可能出现多个币种的情况，多个币种没法计算整个收款单的核销比例，所以增加一个中间币种，如果应收只有一个币种就使用应收币种，如果有多个币种就以美元为核销基准币种')" placement="top">
                    <el-button icon="el-icon-question"></el-button>
                  </el-tooltip> -->
                </template>

          {{getCurrencyLabel(showCurrencyId)}}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>
    <el-card class="card">
      <div slot="header" class="card-title">{{ $t('开票资料') }}</div>
      <el-descriptions :column="3" border>
        <el-descriptions-item :label="$t('发票抬头')">
          {{ form.invoice }}
          <!-- <el-input v-model="form.invoice"></el-input> -->
        </el-descriptions-item>
        <el-descriptions-item :label="$t('纳税人识别号')">
          {{ form.taxpayer }}
          <!-- <el-input v-model="form.taxpayer"></el-input> -->
        </el-descriptions-item>
        <el-descriptions-item :label="$t('开户行')">
          {{ form.accountBank }}
          <!-- <el-input v-model="form.accountBank"></el-input> -->
        </el-descriptions-item>
        <el-descriptions-item :label="$t('账号')">
          {{ form.accountName }}
          <!-- <el-input v-model="form.accountName"></el-input> -->
        </el-descriptions-item>
        <el-descriptions-item :label="$t('项目')">
          {{ form.projectName }}
          <!-- <el-input v-model="form.projectName"></el-input> -->
        </el-descriptions-item>
        <el-descriptions-item :label="$t('税率')+'%'">
          {{ form.taxRate }}
          <!-- <el-input v-model="form.taxRate"></el-input> -->
        </el-descriptions-item>
        <el-descriptions-item :label="$t('开票地址/电话')">
        {{ form.addressPhone }}
          <!-- <el-input v-model="form.addressPhone"></el-input> -->
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-card class="card">
      <div slot="header" class="card-title">{{ $t('收款信息') }}</div>
      <el-table :data="form.receiptAccountList" border>
        <el-table-column :label="$t('应收币种')" align="center">
          <template slot-scope="scope">
             {{getCurrencyLabel(scope.row.currencyId)}}
          </template>
        </el-table-column>
        <!-- <el-table-column :label="$t('应收金额')" align="center" prop="receivableAmount" /> -->
        <el-table-column :label="$t('应收金额')" align="center" prop="receivableAmount">
          <template slot-scope="scope" v-if="scope.row.type !== 'total'">
           <span v-if="scope.row.discountTotal&&scope.row.discountTotal>0">{{ `${scope.row.receivableAmount - scope.row.discountTotal }(${scope.row.receivableAmount} - ${scope.row.discountTotal})` }}</span>
           <span v-else>{{ `${scope.row.receivableAmount}` }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" width="220">
          <template #header>
            {{ $t('核销基准币种') }}（{{getCurrencyLabel(showCurrencyId)}}）{{ $t('汇率') }}
          </template>
          <template slot-scope="scope">
            <template v-if="scope.row.type !== 'total'">
              <span>{{ scope.row.writeOffRate }}</span>
            </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>
        </el-table-column>
        <el-table-column :label="$t('期望收款账户')" align="center">
          <template slot-scope="scope" v-if="scope.row.type !== 'total'">
            {{ `${bankData.find(v => v.id == scope.row.platformAccountId)?bankData.find(v => v.id == scope.row.platformAccountId).baAccountName:''}(${bankData.find(v => v.id == scope.row.platformAccountId)?bankData.find(v => v.id == scope.row.platformAccountId).baAccountNum:''})` }}
          </template>
        </el-table-column>

        <el-table-column :label="$t('期望收款币种')" align="center">
          <template slot-scope="scope">
            <!-- <dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="scope.row.collectionCurrencyId" /> -->
            {{getCurrencyLabel(scope.row.collectionCurrencyId)}}
          </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}.collectionRate`"
            >
              <el-input v-model="scope.row.collectionRate" @input="() => rateChange(scope.row, scope.$index)"></el-input>
            </el-form-item> -->
            <span v-if="scope.row.type !== 'total'">{{ scope.row.collectionRate }}</span>
            <span v-else>{{ $t('期望收费金额') }}
              <span :title="$t('导出账单给客户时显示的收款金额与币种')"><i class="el-icon-question"></i></span>
            </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'">{{ scope.row.collectionAmount }}</span>
            <div v-else>
              <div v-for="itemAmount in scope.row.collectionAmount">{{$i18n.locale=='zh_CN'?itemAmount.currencyNameZh:itemAmount.currencyNameEn}}: {{ itemAmount&&itemAmount.amount?itemAmount.amount:0}}</div>
<!--              <div v-if="scope.row.collectionAmount[0]">{{ $t('美元') }}: {{ scope.row.collectionAmount[0] }}</div>
              <div v-if="scope.row.collectionAmount[1]">{{ $t('人民币') }}: {{ scope.row.collectionAmount[1] }}</div>
              <div v-if="scope.row.collectionAmount[2]">{{ $t('奈拉') }}: {{ scope.row.collectionAmount[2] }}</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('账单汇率有效期')">
          {{ parseTime(form.rateValidateDate) }}
          <!-- <el-form-item
            label=""
            label-width="0"
            style="margin-bottom: 0"
            prop="rateValidateDate"
          >
            <el-date-picker
              v-model="form.rateValidateDate"
              type="datetime"
              :placeholder="$t('选择日期时间')">
            </el-date-picker>
          </el-form-item> -->
        </el-descriptions-item>
      </el-descriptions>
    </el-card>
    <el-card class="card">
      <div slot="header" class="card-title">{{ $t('银行收款明细') }}</div>
      <div>
        <!-- <el-button type="primary" v-if="form.state!=7&&form.state!=0" plain size="mini" @click="batchVerification" v-hasPermi="['ecw:payment:detail:batchWriteOff']" style="padding: 10px; margin-bottom: 10px">{{ $t('批量核销') }}</el-button> -->
        <el-button type="primary"  v-if="form.state!=7&&form.state!=0" plain size="mini" @click="handleAddReceiptItem" v-hasPermi="['ecw:payment:detail:addBank']" style="padding: 10px; margin-bottom: 10px">{{ $t('添加收款明细') }}</el-button>
      </div>
      <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 :label="$t('核销货币金额')" align="center" prop="writeOffAmount" />-->
        <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">
          <!-- <template slot-scope="scope">
            <span>{{ parseTime(scope.row.amountDate, '{y}-{m}-{d}') }}</span>
          </template> -->
        </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>
            <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-card class="card hexiaoCard">
      <el-descriptions :column="3" border>
        <el-descriptions-item >

          <!-- <el-tag>{{ verificationData.usCount.toFixed(6) }}{{$t('美元')}}</el-tag>
          <el-tag>{{ verificationData.rmbCount.toFixed(6) }}{{$t('人民币')}}</el-tag>
          <el-tag>{{ verificationData.nairaCount.toFixed(6) }}{{$t('奈拉')}}</el-tag> -->
          <template slot="label">
            {{ $t('实收已核销总金额') }}          <span :title="$t('所有银行收款明细中状态为已核销的实收金额，币种根据实收币种分类统计')"><i class="el-icon-question"></i></span>

          </template>
          <template v-if="!Object.keys(writeOffTotal).length">
            0
          </template>
          <div v-else>
            <div v-for="(amount, currency) in writeOffTotal" :key="currency">
              {{amount}}{{getCurrencyLabel(currency)}}
            </div>
          </div>

        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            {{ $t('核销基准币种已核销总金额') }}（{{getCurrencyLabel(showCurrencyId)}}）
            <span :title="$t('为了方便统计收款单核销比例，将所有银行收款明细中状态为已核销的实收金额，转换为核销基准币种的金额累加')"><i class="el-icon-question"></i></span>

          </template>
          {{ writeOffAmount}}

        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            {{ $t('总核销比例') }}（{{getCurrencyLabel(showCurrencyId)}}）
            <span :title="$t('总核销比例=核销基准币种已核销总金额/核销基准币种应收总金额')"><i class="el-icon-question"></i></span>

          </template>
          {{ WriteOffProportion }}%
        </el-descriptions-item>
      </el-descriptions>
    </el-card>
    <div style="margin: 20px 0;font-size:16px" v-if="form.financeRemark">{{$t('备注')}}:{{form.financeRemark}}</div>
    <div slot="footer" style="margin: 20px 0">
      <el-button v-if="form.state!=7&&form.state!=9&&form.state!=10&&form.state!=11&&form.state != 4&&form.state != 5 && form.state != 6" type="primary" @click="toEdit" v-hasPermi="['ecw:payment:detail:edit']">{{ $t('编辑') }}</el-button>
      <el-button v-if="form.state!=7&&form.state!=9&&form.state!=10&&form.state!=11&&form.state != 4&&form.state != 5 && form.state != 6"  type="primary" @click="verificationAll" v-hasPermi="['ecw:payment:detail:allWriteOff']">{{ $t('全部核销') }}</el-button>
      <el-button
        type="primary"
        v-if="form.state == 11"
        v-hasPermi="['ecw:voucher:cancelWriteOff']"
        @click="$router.push(`/bpm/process-instance/detail?id=`+form.bmpId)"
        >{{ $t('反核销审核详情') }}</el-button
      >
      <el-button
        type="primary"
        v-if="form.state == 10"
        v-hasPermi="['ecw:voucher:cancelWriteOff']"
        @click="$router.push(`/bpm/process-instance/detail?id=`+form.bmpId)"
        >{{ $t('全部核销审核详情') }}</el-button
      >
      <el-button
        v-if="form.state == 11"
        type="primary"
        v-hasPermi="['ecw:vocher:cancelWriteOfflNo']"
        @click="detailClickCancel(1)"
        >{{ $t('取消反核销审核') }}</el-button
      >
      <el-button
        v-if="form.state == 10"
        type="primary"
        v-hasPermi="['ecw:vocher:cancelWriteOffAll']"
        @click="detailClickCancel(2)"
        >{{ $t('取消全部核销审核') }}</el-button
      >
      <el-button
        v-if="form.state == 4 || form.state == 5 || form.state == 6"
        type="primary"
        v-hasPermi="['ecw:voucher:cancelWriteOff']"
        @click="writeOffShow()"
        >{{ $t('提交收款单反核销') }}</el-button
      >
      <el-button  plain type="primary" @click="$store.dispatch('tagsView/delCurrentView')">{{$t('返回')}}</el-button>

    </div>
    <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" v-model="addForm.accountId" :placeholder="$t('请选择收款账户')" style="width: 220px" @change="accountChange">
              <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>
              <!-- <dict-selector v-if="!isView" :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" v-model="addForm.currencyId" @change="val => currencyIdChange(val)"/> -->
              <!-- <span v-else>{{ addForm.currencyId }}</span> -->
              <!-- <dict-tag v-else :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="addForm.currencyId" /> -->
            </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">
<!--              <el-tooltip class="item" effect="light" :content="$t('实收币种与核销基准币种一样时，无需填写汇率，不一样需要填写汇率')" placement="top-start">
               <el-button> {{ $t('兑核销基准币种汇率') }}（{{getCurrencyLabel(showCurrencyId)}}）</el-button>
              </el-tooltip> -->
            <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 {
  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: 20,
      },
      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:[]
    }
  },
  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)
          }
           // 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.currencyId'(newVal) {
    //   this.currencyIdChange(newVal)
    // },
    'addForm.rate'() {
      this.setWriteOffAmount()
    },
  },
  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
      // res.data.forEach((item) => {
      //   if (item.parentId == 0) {
      //     this.deptArr.push(item);
      //   } else {
      //     this.deptData.push(item);
      //   }
      // });

      // this.deptData.forEach((value) => {
      //   var dept = this.deptArr.filter((itt) => itt.id == value.parentId);
      //   if (dept.length > 0) {
      //     value.name = dept[0].name + " | " + value.name;
      //   }
      // });
      // console.log(this.deptData)
    });
    await getBankAccountPage(this.params).then((res) => (this.bankData = res.data.list));
    if (this.$route.query.id) {
      this.id = this.$route.query.id;
      await getReceiptInfoByIds({ id: this.id }).then(res => {
        this.form = res.data
        getCustomer(this.form.customerId).then(res => {
          this.form.customerName = res?.data?.name
        })
        var dept = this.deptData.filter((itt) => itt.id == res.data.departmentId);
        // console.log(dept)
        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) {
          // totalAmount
          res.data = [...res.data, {
            type: 'total',
            writeOffAmount: res.data.reduce((total, currentValue) => NP.plus(total, currentValue.writeOffAmount || 0), 0),
            collectionAmount: []
          }]
        }
       this.$set(this.form, 'receiptAccountList', res.data)
        // 收款总计
        // const dollarList = res.data.filter(v => v.collectionCurrencyId == 1)
        // const dollar = dollarList.reduce((total, currentValue) => NP.plus(total, currentValue.collectionAmount || 0), 0)

        // const rmbList = res.data.filter(v => v.collectionCurrencyId == 3)
        // const rmb = rmbList.reduce((total, currentValue) => NP.plus(total, currentValue.collectionAmount || 0), 0)

        // const nairaList = res.data.filter(v => v.collectionCurrencyId == 2)
        // const naira = nairaList.reduce((total, currentValue) => NP.plus(total, currentValue.collectionAmount || 0), 0)

        // res.data[res.data.length -1].collectionAmount = [dollar, rmb, naira]
        // this.$set(this.form, 'receiptAccountList', [...this.form.receiptAccountList])

        // const dollarListByList = this.list.filter(v => v.currencyId === 1)
        // const discountDollar = dollarListByList.reduce((total, currentValue) => NP.plus(total, currentValue.discountTotal || 0), 0)
        // const d = res.data.find(v => v.currencyId == 1)
        // d && (d.discountTotal = discountDollar)

        // const rmbListByList = this.list.filter(v => v.currencyId === 3)
        // const discountRmb = rmbListByList.reduce((total, currentValue) => NP.plus(total, currentValue.discountTotal || 0), 0)
        // const r = res.data.find(v => v.currencyId == 3)
        // r && (r.discountTotal = discountRmb)



        var n
        // 收款总计
        var amountList =[]
        this.currencyList.forEach((item,index)=>{
          var nairaListByList = this.list.filter(v => v.currencyId === item.id)
          if(nairaListByList.length>0){
            var discountNaira = nairaListByList.reduce((total, currentValue) => NP.plus(total, currentValue.discountTotal || 0), 0)
            n = res.data.find(v => v.currencyId == item.id)
            n && (n.discountTotal = discountNaira)
          }
          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).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})
           // }

          }
        })
        this.form.receiptAccountList[this.form.receiptAccountList.length -1].collectionAmount = amountList
        this.$set(this.form, 'receiptAccountList', [...this.form.receiptAccountList])


        this.$nextTick(() => {
          // this.form.receiptAccountList.forEach((item, index) => {
          //   this.rateChange(item, index)
          // });
          if(this.form.receiptAccountList.length>0){
            this.editReceiptAccountList()
          }
        })
      })
    }

    this.getList()
  },
  methods: {
    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(){
      var amountList =[]
      this.currencyList.forEach((item,index)=>{
        var dollarList = this.form.receiptAccountList.filter(v => v.collectionCurrencyId == item.id)
        if(dollarList.length>0){
          var dollar = Math.round(dollarList.reduce((total, currentValue) => NP.plus(total, currentValue.collectionAmount), 0))
          amountList.push({currencyId:item.id,currencyNameEn:item.titleEn,currencyNameZh:item.titleZh,amount:dollar})
        }
      })
      this.form.receiptAccountList[this.form.receiptAccountList.length -1].collectionAmount = amountList
      this.$set(this.form, 'receiptAccountList', [...this.form.receiptAccountList])
    },
    setWriteOffAmount() {
      var pointArr = []
      var 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{
        // console.log(this.addForm.amount)
        // this.addForm.amount = this.addForm.amount.toFixed(2)
        // if(this.addForm&&this.addForm.amount&&this.addForm.amount.indexOf('.')>-1){
          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){
      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 ''
    },
    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
                }
                }
              }
            })
        },
    calculation() {
      // this.currencyList.forEach((item,index)=>{
      //   var verificationList = this.detailed.filter(v => v.status === 1)
      //   var dollarList = verificationList.filter(v => v.currencyId === item.id)
      //   if(dollarList.length>0){
      //     let dollar,discountDollar
      //       dollar = dollarList.reduce((total, currentValue) => NP.plus(total, currentValue.amount || 0), 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: dollar,
      //           writeOffRate: t?.writeOffRate || NP.divide(this.currencyList.find(v => v.id === item.id).huilv, this.currencyList.find(v => v.id === this.showCurrencyId).huilv).toFixed(6),
      //           platformAccountId: t?.platformAccountId || '',
      //           collectionCurrencyId: t?.collectionCurrencyId || item.id,
      //           collectionRate: t?.collectionRate || 1
      //         }
      //       )
      //       this.calculationCount(NP.minus(dollar, discountDollar), item.id)
      //   }
      // })
      // const verificationList = this.detailed.filter(v => v.status === 1)
      // const dollarList = verificationList.filter(v => v.currencyId === 1)
      // const dollar = dollarList.length > 0 ? dollarList.reduce((total, currentValue) => NP.plus(total, currentValue.amount || 0), 0) : 0
      // const rmbList = verificationList.filter(v => v.currencyId === 3)
      // const rmb = rmbList.length > 0 ? rmbList.reduce((total, currentValue) => NP.plus(total, currentValue.amount || 0), 0) : 0
      // const nairaList = verificationList.filter(v => v.currencyId === 2)
      // const naira = nairaList.length > 0 ? nairaList.reduce((total, currentValue) => NP.plus(total, currentValue.amount || 0), 0) : 0

      // const usCount = NP.plus(dollar, NP.times(this.RMBtoUS(), rmb),  NP.times(this.NANtoUS(), naira))
      // const rmbCount = NP.plus(rmb, NP.times(this.UStoRMB(), dollar),  NP.times(this.NANtoRMB(), naira))
      // const nairaCount = NP.plus(naira, NP.times(this.UStoNAN(), dollar),  NP.times(this.RMBtoNAN(), rmb))

      // this.verificationData.usCount = usCount
      // this.verificationData.rmbCount = rmbCount
      // this.verificationData.nairaCount = nairaCount
      // this.verificationData.usCount = dollar
      // this.verificationData.rmbCount = rmb
      // this.verificationData.nairaCount = naira

      // if (verificationList.indexOf(1)>-1) { // 美元
      //   this.verificationData.writtenOff = dollar
      //   this.verificationData.WriteOffProportion = NP.times(NP.divide(dollar, this.form.receivableTotalAmount), 100)
      //   const remaining = NP.minus(this.form.receivableTotalAmount, dollar)
        // this.remainingAmount = {
        //   usAmount: remaining,
        //   rmbAmount: NP.times(this.UStoRMB(), remaining),
        //   nairaAmount: NP.times(this.UStoNAN(), remaining)
        // }
      //   this.remainingAmount.usAmount = remaining
      // } else if (this.showCurrencyId === 2) { // 人民币
      //   this.verificationData.writtenOff = rmb
      //   this.verificationData.WriteOffProportion = NP.times(NP.divide(rmb, this.form.receivableTotalAmount), 100)
      //   const remaining = NP.minus(this.form.receivableTotalAmount, rmb)
        // this.remainingAmount = {
        //   usAmount: NP.times(this.RMBtoUS(), remaining),
        //   rmbAmount: remaining,
        //   nairaAmount: NP.times(this.RMBtoNAN(), remaining)
        // }
      //   this.remainingAmount.rmbAmount = remaining
      // } else if (this.showCurrencyId === 3) { // 奈拉
      //   this.verificationData.writtenOff = naira
      //   this.verificationData.WriteOffProportion = NP.times(NP.divide(naira, this.form.receivableTotalAmount), 100)
      //   const remaining = NP.minus(this.form.receivableTotalAmount, naira)
        // this.remainingAmount = {
        //   usAmount: NP.times(this.NANtoUS(), remaining),
        //   rmbAmount: NP.times(this.NANtoRMB(), remaining),
        //   nairaAmount: remaining
        // }
        // this.remainingAmount.nairaAmount = remaining
      // }
    },
    accountChange(val){
      var 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
        })
        var 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
      }
      var 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 {
        // if (this.showCurrencyId === 1 && val === 3) rate = this.RMBtoUS()
        // else if (this.showCurrencyId === 1 && val === 2) rate = this.NANtoUS()
        // else if (this.showCurrencyId === 3 && val === 1) rate = this.UStoRMB()
        // else if (this.showCurrencyId === 3 && val === 2) rate = this.NANtoRMB()
        // else if (this.showCurrencyId === 2 && val === 1) rate = this.UStoNAN()
        // else if (this.showCurrencyId === 2 && val === 3) rate = this.RMBtoNAN()
        rate = this.getRate(val,this.showCurrencyId)
      }
      this.$set(this.addForm, 'rate', rate)
    },
    //获取汇率
    getRate(sourceCurrencyId,targetCurrencyId){
      var 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}'),
          accountNo: +v.accountNo,
          rate:parseFloat(v.rate),
          attr: v.attr ? v.attr.split(',').map(t => ({ name: t.slice(t.lastIndexOf('/') + 1), url: t })) : []
        }))
        // this.calculation()
      })
    },
    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.openAddDialog = true
      this.dialogTitle = this.$t('编辑银行实收明细')
      this.saveBtnText = this.$t('提交')
      this.isView = false
      setTimeout(() => {
        this.addForm = { ...row }
        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) {
      var 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>
