<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="marks" />
        <el-table-column :label="$t('品名')" align="center" prop="title">
          <template slot-scope="scope">
            {{ 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" />
        <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>
            <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 }}</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">
          <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, {}]">添加收款账户</el-button>
            <el-button type="text" v-if="index > 0" @click="subtractItem(index)"><span style="color: red">删除</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="请选择是否需要开票"
          >
            <el-option :value="1" label="需要"></el-option>
            <el-option :value="0" label="不需要"></el-option>
          </el-select> -->
        </el-descriptions-item>
        <el-descriptions-item :label="$t('核销基准币种')">
          <dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="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>
      <div>
        <el-button type="primary" plain size="mini" @click="batchVerification" style="padding: 10px; margin-bottom: 10px">{{ $t('批量核销') }}</el-button>
        <el-button type="primary" plain size="mini" @click="handleAddReceiptItem" 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">
            <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="rate" />
        <el-table-column :label="$t('核销货币金额')" align="center" prop="writeOffAmount" />
        <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">
            <span>{{ scope.row.status == 0 ? $t('待核销') : $t('已核销') }}</span>
          </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" type="text" @click="deleteClick(scope.row)">{{ $t('删除') }}</el-button>
            <el-button type="text" @click="detailClick(scope.row)">{{ $t('详情') }}</el-button>
            <el-button v-if="scope.row.status == 0" type="text" @click="verificationClick(scope.row)">{{ $t('核销') }}</el-button>
            <el-button v-if="scope.row.status == 1" type="text" @click="verificationCancelClick(scope.row)">{{ $t('反核销') }}</el-button>
            <el-button v-if="scope.row.status == 0" type="text" @click="editClick(scope.row)">{{ $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>
        <el-table-column :label="$t('应收币种')" align="center">
          <template slot-scope="scope">
            <dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="scope.row.currencyId" />
          </template>
        </el-table-column>
        <!-- <el-table-column label="应收金额" align="center" prop="receivableAmount" /> -->
        <el-table-column :label="$t('应收金额')" align="center" prop="receivableAmount">
          <template slot-scope="scope" v-if="scope.row.type !== 'total'">
            {{ `${scope.row.receivableAmount - scope.row.discountTotal}(${scope.row.receivableAmount} - ${scope.row.discountTotal})` }}
          </template>
        </el-table-column>
        <el-table-column align="center" width="220">
          <template #header>
            {{ $t('核销基准币种') }}（<dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="showCurrencyId" />）{{ $t('汇率') }}
          </template>
          <template slot-scope="scope">
            <template v-if="scope.row.type !== 'total'">
              <span>{{ scope.row.writeOffRate }}</span>
            </template>
            <template v-else>
              {{ $t('应收总金额') }}（<dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="showCurrencyId" />）
            </template>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="writeOffAmount">
          <template #header>
            {{ $t('核销基准金额') }}（<dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="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).baAccountName}(${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" />
          </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>
          </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-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="选择日期时间">
            </el-date-picker>
          </el-form-item> -->
        </el-descriptions-item>
      </el-descriptions>
    </el-card>
    <el-card class="card hexiaoCard">
      <el-descriptions :column="3" border>
        <!-- <template v-for="(item, index) in form.receivableDetailList">
          <el-descriptions-item :label="index === 0 ? '应收总金额' : ''" :key="index+3">
            {{ item.amount }}
            <dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="index + 1" />
          </el-descriptions-item>
          <el-descriptions-item :key="index">
            <template v-if="showCurrencyId !== item.currencyId" slot="label">
              汇率（<dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="showCurrencyId" />）
            </template>
            <span v-if="showCurrencyId !== item.currencyId">{{ item.rate }}</span>
          </el-descriptions-item>
        </template> -->
        <!-- <el-descriptions-item>
          <template slot="label">
            应收总金额（<dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="showCurrencyId" />）
          </template>
          {{ form.receivableTotalAmount }}
        </el-descriptions-item> -->

        <el-descriptions-item :label="$t('已核销总金额')">
          <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>

        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            {{ $t('已核销金额') }}（<dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="showCurrencyId" />）
          </template>
          {{ verificationData.writtenOff.toFixed(6) }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            {{ $t('已核销比例') }}（<dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="showCurrencyId" />）
          </template>
          {{ parseFloat(verificationData.WriteOffProportion/100).toFixed(2) }}%
        </el-descriptions-item>
      </el-descriptions>
    </el-card>
    <div slot="footer" style="margin: 20px 0">
      <el-button type="primary" @click="toEdit">{{ $t('编辑') }}</el-button>
      <el-button type="primary" @click="verificationAll">{{ $t('全部核销') }}</el-button>
    </div>
    <el-dialog v-if="openAddDialog" :visible.sync="openAddDialog" :title="dialogTitle" width="40%" append-to-body>
      <div style="padding: 0 24px">
        <el-form ref="addForm" :model="addForm" label-width="150px">
          <el-form-item :label="$t('收款单号')">{{ form.receiptNo }}</el-form-item>
          <el-form-item :label="$t('剩余应收金额')">
            <div>
              <div>{{ remainingAmount.usAmount.toFixed(6) }}{{ $t('美元') }}</div>
              <div>{{ remainingAmount.rmbAmount.toFixed(6) }}{{ $t('人民币') }}</div>
              <div>{{ remainingAmount.nairaAmount.toFixed(6) }}{{ $t('奈拉') }}</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.accountNo" :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 }}</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('币种不能为空') }"
            >
              <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">
              {{ $t('汇率') }}（<dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="showCurrencyId" />）
            </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('金额') }}（<dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="showCurrencyId" />）
            </template>
            <span>{{ addForm.writeOffAmount?parseFloat(addForm.writeOffAmount).toFixed(6):'' }}</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"
            :rules="{ required: true, trigger: ['blur', 'change'], message: $t('水单号不能为空') }"
          >
            <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>
  </div>
</template>

<script>
import { getBankAccountPage } from "@/api/ecw/bankAccount";
import { getToken } from "@/utils/auth";
import { getCustomer } from '@/api/ecw/customer'
import {
  getReceiptInfoByIds,
  getInvoicingItem,
  receiptItemCreate,
  getReceivableItem,
  deleteReceiptItem,
  receiptItemVerification,
  receiptItemVerificationCancel,
  updateReceiptItem,
  receiptItemBatchVerification,
  receiptItemAllVerification,
  getReceiptAccountList
} 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: [],
      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
      }
    }
  },
  computed: {
    showCurrencyId() {
      let fieldList = [];
      let groupList=[];
      this.list.map((element)=>{
        if(fieldList.indexOf(element['currencyId'])===-1){
          fieldList.push(element['currencyId'])
        }
      })
      for(let i=0;i<fieldList.length;i++){
        let arr = this.list.filter((element)=>{
          return element['currencyId']===fieldList[i];
        })
        groupList.push({
          currencyId:arr[0].currencyId,
          list:arr
        })
      }
      if (groupList.length === 1) return groupList[0].currencyId
      else return 1
    }
  },
  watch: {
    // 'addForm.currencyId'(newVal) {
    //   this.currencyIdChange(newVal)
    // },
    'addForm.rate'() {
      this.setWriteOffAmount()
    },
  },
  async created() {
    // 获取汇率
    await getCurrencyPage(this.params).then(res => this.currencyList = res.data.list)
    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
        })
      })
      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: [0, 0, 0]
          }]
        }
        // 收款总计
        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 == 2)
        const rmb = rmbList.reduce((total, currentValue) => NP.plus(total, currentValue.collectionAmount || 0), 0)

        const nairaList = res.data.filter(v => v.collectionCurrencyId == 3)
        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 === 2)
        const discountRmb = rmbListByList.reduce((total, currentValue) => NP.plus(total, currentValue.discountTotal || 0), 0)
        const r = res.data.find(v => v.currencyId == 2)
        r && (r.discountTotal = discountRmb)

        const nairaListByList = this.list.filter(v => v.currencyId === 3)
        const discountNaira = nairaListByList.reduce((total, currentValue) => NP.plus(total, currentValue.discountTotal || 0), 0)
        const n = res.data.find(v => v.currencyId == 3)
        n && (n.discountTotal = discountNaira)


        this.$set(this.form, 'receiptAccountList', [...res.data])
        this.$nextTick(() => {
          // this.form.receiptAccountList.forEach((item, index) => {
          //   this.rateChange(item, index)
          // });
        })
      })
    }

    this.getList()
  },
  methods: {
    setWriteOffAmount() {
      this.$set(this.addForm, 'writeOffAmount', NP.times(this.addForm.rate || 0, this.addForm.amount || 0))
    },
    calculation() {
      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 === 2)
      const rmb = rmbList.length > 0 ? rmbList.reduce((total, currentValue) => NP.plus(total, currentValue.amount || 0), 0) : 0
      const nairaList = verificationList.filter(v => v.currencyId === 3)
      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

      if (this.showCurrencyId === 1) { // 美元
        this.verificationData.writtenOff = usCount
        this.verificationData.WriteOffProportion = NP.times(NP.divide(usCount, this.form.receivableTotalAmount), 100)
        const remaining = NP.minus(this.form.receivableTotalAmount, usCount)
        this.remainingAmount = {
          usAmount: remaining,
          rmbAmount: NP.times(this.UStoRMB(), remaining),
          nairaAmount: NP.times(this.UStoNAN(), remaining)
        }
      } else if (this.showCurrencyId === 2) { // 人民币
        this.verificationData.writtenOff = rmbCount
        this.verificationData.WriteOffProportion = NP.times(NP.divide(rmbCount, this.form.receivableTotalAmount), 100)
        const remaining = NP.minus(this.form.receivableTotalAmount, rmbCount)
        this.remainingAmount = {
          usAmount: NP.times(this.RMBtoUS(), remaining),
          rmbAmount: remaining,
          nairaAmount: NP.times(this.RMBtoNAN(), remaining)
        }
      } else if (this.showCurrencyId === 3) { // 奈拉
        this.verificationData.writtenOff = nairaCount
        this.verificationData.WriteOffProportion = NP.times(NP.divide(nairaCount, this.form.receivableTotalAmount), 100)
        const remaining = NP.minus(this.form.receivableTotalAmount, nairaCount)
        this.remainingAmount = {
          usAmount: NP.times(this.NANtoUS(), remaining),
          rmbAmount: NP.times(this.NANtoRMB(), remaining),
          nairaAmount: remaining
        }
      }
    },
    accountChange(val){
      var data = this.bankData.find(item=>item.id==val)
      this.$set(this.addForm,'accountName',data.baAccountName)
    },
    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)
    },
    currencyIdChange(val) {
      val = Number(val)
      let rate
      if(val === this.showCurrencyId) {
        rate = 1
      } else {
        if (this.showCurrencyId === 1 && val === 2) rate = this.RMBtoUS()
        else if (this.showCurrencyId === 1 && val === 3) rate = this.NANtoUS()
        else if (this.showCurrencyId === 2 && val === 1) rate = this.UStoRMB()
        else if (this.showCurrencyId === 2 && val === 3) rate = this.NANtoRMB()
        else if (this.showCurrencyId === 3 && val === 1) rate = this.UStoNAN()
        else if (this.showCurrencyId === 3 && val === 2) rate = this.RMBtoNAN()
      }
      this.$set(this.addForm, 'rate', rate)
    },
    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).toFixed(6),
          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.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(row) {
      const id = row.id;
      this.$modal
        .confirm(this.$t('您确认要反核销吗?'))
        .then(function () {
          return receiptItemVerificationCancel(id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$t('反核销成功'));
        })
        .catch(() => {});
    },
    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() {
      this.$modal
        .confirm(this.$t('您确认要全部核销吗?'))
        .then(() => {
          return receiptItemAllVerification(this.id);
        })
        .then(() => {
          this.$modal.msgSuccess(this.$t('核销成功'));
          this.$router.back();
        })
        .catch(() => {});
    },
    hiddenDialog() {
      this.openAddDialog = false
    },
    handleAddReceiptItem() {
      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%;
  }
}
</style>
