<template>
  <div class="app-container">
    <el-form
        ref="form"
        :model="form"
        label-width="120px"
        label-position="left"
      >
      <el-card>
        <div v-if="id" slot="header" class="card-title">修改收款单</div>
        <div v-else slot="header" class="card-title">新增收款单</div>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="客户">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="customerId"
              :rules="{ required: true, trigger: ['blur', 'change'], message: '客户不能为空' }"
            >
              <customer-selector
                v-model="form.customerId"
                @change="customerChange"
              />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="部门">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="departmentId"
              :rules="{ required: true, trigger: ['blur', 'change'], message: '部门不能为空' }"
            >
              <el-select
                v-model="form.departmentId"
                style="width: 300px"
                placeholder="请选择部门"
              >
                <el-option
                  v-for="item in deptData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="业务员">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="salesmanId"
              :rules="{ required: true, trigger: ['blur', 'change'], message: '客户不能为空' }"
            >
              <el-select v-model="form.salesmanId" placeholder="请选择业务员" @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 label="手续费(RMB)">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="feeRate"
              :rules="{ required: true, trigger: ['blur', 'change'], message: '手续费不能为空' }"
            >
              <el-input
                v-model="form.feeRate"
                placeholder="请输入手续费"
              ></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="备注">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="remark"
              :rules="{ required: true, trigger: ['blur', 'change'], message: '备注不能为空' }"
            >
              <el-input v-model="form.remark" placeholder="备注"></el-input>
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
      <el-card class="card">
        <div slot="header" class="card-title">订单信息</div>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            style="padding: 10px; margin-bottom: 10px"
            >添加未收客户款项</el-button
          >
        </el-col>
        <el-table v-loading="loadings" :data="list" border>
          <el-table-column label="订单号" align="center" prop="orderNo" />
          <el-table-column label="唛头" align="center" prop="marks" />
          <el-table-column label="品名" align="center" prop="title">
            <template slot-scope="scope">
              {{ scope.row.titleZh + "(" + scope.row.titleEn + ")" }}
            </template>
          </el-table-column>
          <el-table-column label="箱数" align="center" prop="num" />
          <el-table-column label="体积/重量" align="center" prop="weight" />
          <!-- <el-table-column label="发货人" align="center" prop="consignorName" />
          <el-table-column label="收货人" align="center" prop="consigneeName" /> -->
          <!-- <el-table-column label="订单状态" 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="收款类型" align="center" prop="paymentType">
            <template slot-scope="scope">
              <dict-selector :type="DICT_TYPE.PAYMENT_TYPE" v-model="scope.row.paymentType"></dict-selector>
            </template>
          </el-table-column> -->
          <el-table-column label="收入类型" 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="单价金额" 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="总金额" 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="核销比例" align="center" prop="totalAmount">
            <template slot-scope="scope">
              <span>{{ scope.row.totalAmount }}%</span>
            </template>
          </el-table-column> -->
          <!-- <el-table-column label="已收金额" 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="本次实收金额" align="center" prop="amount">
            <template slot-scope="scope">
              <el-input v-model="scope.row.amount">
                <template slot="append">
                  <dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="scope.row.currencyId" />
                </template>
              </el-input>
            </template>
          </el-table-column> -->
        </el-table>
        <el-descriptions :column="1" border class="card">
          <el-descriptions-item v-for="(v, index) in form.receiptAccountList" :label="`收款账户${index + 1}`" :key="index">
            <div style="display: flex">
              <el-form-item
                label=""
                label-width="0"
                style="margin-bottom: 0; margin-right: 12px"
                :prop="`receiptAccountList[${index}].platformAccountId`"
                :rules="{ required: true, trigger: ['blur', 'change'], message: '请选择收款账户' }"
              >
                <el-select
                  v-model="v.platformAccountId"
                  placeholder="请选择收款账户"
                >
                  <el-option
                    v-for="item in bankData"
                    :key="item.id"
                    :label="item.baAccountName + '(' + item.baAccountNum + ')'"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                label=""
                label-width="0"
                style="margin-bottom: 0; margin-right: 12px"
                :prop="`receiptAccountList[${index}].currencyId`"
                :rules="{ required: true, trigger: ['blur', 'change'], message: '请选择币种' }"
              >
                <dict-selector
                  :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT"
                  v-model="v.currencyId"
                />
              </el-form-item>
              <el-button type="text" v-if="index === 0" @click="form.receiptAccountList = [...form.receiptAccountList, {}]">添加收款账户</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="是否需要开票">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="openInvoice"
              :rules="{ required: true, trigger: ['blur', 'change'], message: '请选择是否需要开票' }"
            >
              <el-select
                v-model="form.openInvoice"
                placeholder="请选择是否需要开票"
              >
                <el-option :value="1" label="需要"></el-option>
                <el-option :value="0" label="不需要"></el-option>
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="核销基准币种">
            <dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="showCurrencyId" />
          </el-descriptions-item>
        </el-descriptions>
          <!-- <div class="card">
            <el-form-item
              label="收款附件"
              label-width="120px"
              style="margin-bottom: 0; width: 33%; display: inline-block"
              prop="wenjian"
            >
              <el-upload
                class="upload-demo"
                :action="uploadFileUrl"
                :headers="headers"
                :on-success="handleUploadSuccess"
                :before-upload="handleBeforeUpload"
                :on-error="handleUploadError"
                :before-remove="beforeRemove"
                multiple
              >
                <el-button size="small" type="primary">上传附件</el-button>
              </el-upload>
            </el-form-item>
            <el-form-item
              label="水单号:"
              label-width="120px"
              style="
                margin-bottom: 0;
                width: 31%;
                margin-left: 2%;
                display: inline-block;
              "
              prop="waterBillNo"
              required
              error="水单号不能为空"
            >
              <el-input
                v-model="form.waterBillNo"
                maxlength="200"
                placeholder="请输入水单号"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="实收日期:"
              label-width="120px"
              style="
                margin-bottom: 0;
                width: 31%;
                margin-left: 2%;
                display: inline-block;
              "
              prop="payedAt"
              required
              error="实收日期不能为空"
            >
              <el-date-picker
                clearable
                v-model="form.payedAt"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
                type="date"
                placeholder="选择实收日期"
              />
            </el-form-item>
          </div> -->
      </el-card>
      <el-card v-if="showInvoice" class="card">
        <div slot="header" class="card-title">开票资料</div>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="发票抬头">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="invoice"
              :rules="{ required: true, trigger: ['blur', 'change'], message: '请输入发票抬头' }"
            >
              <el-input v-model="form.invoice"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="纳税人识别号">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="taxpayer"
              :rules="{ required: true, trigger: ['blur', 'change'], message: '请输入纳税人识别号' }"
            >
              <el-input v-model="form.taxpayer"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="开户行">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="accountBank"
              :rules="{ required: true, trigger: ['blur', 'change'], message: '请输入开户行' }"
            >
              <el-input v-model="form.accountBank"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="账号">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="accountName"
              :rules="{ required: true, trigger: ['blur', 'change'], message: '请输入账号' }"
            >
              <el-input v-model="form.accountName"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="项目">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="projectName"
              :rules="{ required: true, trigger: ['blur', 'change'], message: '请输入项目' }"
            >
              <el-input v-model="form.projectName"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="税率%">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="taxRate"
              :rules="{ required: true, trigger: ['blur', 'change'], message: '请输入税率' }"
            >
              <el-input v-model="form.taxRate"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="开票地址/电话">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="addressPhone"
              :rules="{ required: true, trigger: ['blur', 'change'], message: '请输入开票地址/电话' }"
            >
              <el-input v-model="form.addressPhone"></el-input>
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
      <el-card class="card amountCard">
        <el-descriptions :column="2" 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>
              <el-form-item
                v-if="showCurrencyId !== item.currencyId"
                label=""
                label-width="0"
                style="margin-bottom: 0"
                :prop="`receivableDetailList[${index}].rate`"
                :rules="{ required: true, trigger: ['blur', 'change'], message: '请输入汇率' }"
              >
                <el-input v-model="item.rate" style="width: 220px" @input="calculationCount(form.receivableTotalAmount)"></el-input>
              </el-form-item>
            </el-descriptions-item>
          </template>
          <!-- <el-descriptions-item label="">-</el-descriptions-item>
          <el-descriptions-item>
            <template v-if="showCurrencyId !== 2" slot="label">
              汇率（<dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="showCurrencyId" />）
            </template>
            <el-form-item
              v-if="showCurrencyId !== 2"
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="addressPhone"
              required
              error="请输入汇率"
            >
              <el-input v-model="form.addressPhone"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="">-</el-descriptions-item>
          <el-descriptions-item>
            <template v-if="showCurrencyId !== 3" slot="label">
              汇率（<dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="showCurrencyId" />）
            </template>
            <el-form-item
              v-if="showCurrencyId !== 3"
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="taxRate"
              required
              error="请输入汇率"
            >
              <el-input v-model="form.taxRate"></el-input>
            </el-form-item>
          </el-descriptions-item> -->
          <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>
      </el-card>
    </el-form>
    <div slot="footer" style="margin: 20px 0">
      <el-button type="primary" @click="submitForm(1)">保 存</el-button>
      <el-button type="primary" @click="submitForm(0)">{{ id ? '修 改' : '新 增' }}</el-button>
    </div>
    <el-dialog
      :visible.sync="open"
      title="添加未收客户款项"
      width="80%"
      append-to-body
      @open="getList"
    >
      <div>
        <!-- <div slot="header" class="card-title">添加未收客户款项</div> -->
        <!-- 搜索工作栏 -->
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          label-width="80px"
        >
          <el-row>
            <el-form-item label="始发城市">
              <el-select
                v-model="queryParams.departureId"
                placeholder="请选择始发地"
              >
                <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="目的城市">
              <el-select
                v-model="queryParams.objectiveId"
                placeholder="请选择始发地"
              >
                <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="运输方式">
              <dict-selector
                :type="DICT_TYPE.ECW_TRANSPORT_TYPE"
                v-model="queryParams.transportId"
                formatter="number"
              />
            </el-form-item>
            <el-form-item label="出货渠道">
              <el-select
                v-model="queryParams.channelId"
                placeholder="请选择出货渠道"
              >
                <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="报关方式">
              <dict-selector
                :type="DICT_TYPE.ECW_CUSTOMS_TYPE"
                v-model="queryParams.customsType"
              />
            </el-form-item>
            <el-form-item label="控货">
              <dict-selector
                :type="DICT_TYPE.INFRA_BOOLEAN_STRING"
                v-model="queryParams.control"
              />
            </el-form-item>
            <el-form-item label="客户名称">
              <customer-selector
                v-model="queryParams.consignorId"
                @change="consignor = $event"
              />
            </el-form-item>
          </el-row>
          <el-form-item label="订单编号" prop="orderNo">
            <el-input
              v-model="queryParams.orderNo"
              placeholder="请输入订单编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="自编号" prop="orderNo">
            <el-input
              v-model="queryParams.orderNo"
              placeholder="请输入自编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery"
              >查询</el-button
            >
          </el-form-item>
        </el-form>
        <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" :reserve-selection="true"> </el-table-column>
          <el-table-column label="订单号" align="center" prop="orderNo" />
          <el-table-column label="唛头" align="center" prop="marks" />
          <el-table-column label="品名" align="center" prop="title">
            <template slot-scope="scope">
              {{ scope.row.titleZh + "(" + scope.row.titleEn + ")" }}
            </template>
          </el-table-column>
          <el-table-column label="箱数" align="center" prop="num" />
          <el-table-column label="体积/重量" align="center" prop="weight" />
          <el-table-column label="发货人" align="center" prop="consignorName" />
          <el-table-column label="收货人" align="center" prop="consigneeName" />
          <el-table-column label="订单状态" 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="收入类型" 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="单价美元" align="center" prop="unitPrice" />
        </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">确认添加</el-button>
          <el-button @click="hiddenDialog">取 消</el-button>
        </div>
      </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 { 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, getReceivableList, getReceivableInfoByIds, getReceiptInfoByIds, getReceiptAccountList, getInvoicingItem, updateReceipt } from "@/api/ecw/financial";
import {getCustomer} from '@/api/ecw/customer'
import NP from 'number-precision'
import { getCurrencyPage } from "@/api/ecw/currency";
import ret from "bluebird/js/release/util";

export default {
  name: "CreatCollection",
  components: {
    CustomerSelector,
  },
  data() {
    return {
      loadings: false,
      loading1: false,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/app-api/file/upload", // 上传的图片服务器地址
      form: {
        receiptAccountList: [{}],
        receivableDetailList: [
          { amount: 0, currencyId: 1, rate: 0 },
          { amount: 0, currencyId: 2, rate: 0 },
          { amount: 0, currencyId: 3, rate: 0 }
        ]
      },
      creatorData: [],
      list: [],
      // fileList: [],
      orderData: [],
      total: 0,
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      loading: "",
      open: false,
      bankData: [],
      params: {
        page: 1,
        rows: 20,
      },
      deptData: [],
      deptArr: [],
      oadings: false,
      channelList: [],
      queryParams: {
        page: 1,
        rows: 20,
      },
      multipleSelection: [],
      tradeCityList: [],
      id: 0,
      receiptId: 0,
      currencyList: []
    };
  },
  async created() {
    // 获取汇率
    await getCurrencyPage(this.params).then(res => this.currencyList = res.data.list)

    let that = this;
    if (that.$route.query.id) {
      this.id = this.$route.query.id;
      getReceiptInfoByIds({ id: this.id }).then(res => {
        this.form = Object.assign({}, this.form, res.data)
      })
      getInvoicingItem({ id: this.id }).then(res => {
        this.list = [...res.data]
      })
      getReceiptAccountList({ id: this.id }).then(res => {
        this.$set(this.form, 'receiptAccountList', [...res.data])
      })
    }
    if (that.$route.query.receiptId && that.$route.query.receiptId !== '0') {
      this.receiptId = this.$route.query.receiptId;
      getReceivableInfoByIds({ id: this.receiptId }).then(res => {
        this.list = [{...res.data}]
        // this.$set(this.form, 'supplierId', res.data.supplierId)
        this.calculation()
      })
    }

    // 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));
    getBankAccountPage(that.params).then(
      (res) => (that.bankData = res.data.list)
    );
    listSimpleDepts().then((res) => {
      res.data.forEach((item) => {
        if (item.parentId == 0) {
          that.deptArr.push(item);
        } else {
          that.deptData.push(item);
        }
      });

      that.deptData.forEach((value) => {
        var dept = that.deptArr.filter((itt) => itt.id == value.parentId);
        if (dept.length > 0) {
          value.name = dept[0].name + " | " + value.name;
        }
      });
    });
  },
  computed: {
    expoerCityList() {
      return this.tradeCityList.filter((item) => item.type == 2);
    },
    importCityList() {
      return this.tradeCityList.filter((item) => item.type == 1);
    },
    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
    },
    showInvoice() {
      return this.form.openInvoice == 1
    }
  },
  methods: {
    calculation() {
      const dollarList = this.list.filter(v => v.currencyId === 1)
      const dollar = dollarList.length > 0 ? dollarList.reduce((total, currentValue) => NP.plus(total, currentValue.totalAmount || 0), 0) : 0
      const rmbList = this.list.filter(v => v.currencyId === 2)
      const rmb = rmbList.length > 0 ? rmbList.reduce((total, currentValue) => NP.plus(total, currentValue.totalAmount || 0), 0) : 0
      const nairaList = this.list.filter(v => v.currencyId === 3)
      const naira = nairaList.length > 0 ? nairaList.reduce((total, currentValue) => NP.plus(total, currentValue.totalAmount || 0), 0) : 0
      if (this.showCurrencyId === 1) { // 美元
        const usCount = NP.plus(dollar, NP.times(this.RMBtoUS(), rmb),  NP.times(this.NANtoUS(), naira))
        this.form.receivableDetailList[0].rate = 1
        this.form.receivableDetailList[0].amount = usCount
        this.form.receivableDetailList[1].rate || (this.form.receivableDetailList[1].rate = this.UStoRMB())
        this.form.receivableDetailList[2].rate || (this.form.receivableDetailList[2].rate = this.UStoNAN())
        this.form.receivableTotalAmount = usCount
        this.calculationCount(usCount)
      } else if (this.showCurrencyId === 2) { // 人民币
        const rmbCount = NP.plus(rmb, NP.times(this.UStoRMB(), dollar),  NP.times(this.NANtoRMB(), naira))
        this.form.receivableDetailList[1].rate = 1
        this.form.receivableDetailList[1].amount = usCount
        this.form.receivableDetailList[0].rate || (this.form.receivableDetailList[0].rate = this.RMBtoUS())
        this.form.receivableDetailList[2].rate || (this.form.receivableDetailList[2].rate = this.RMBtoNAN())
        this.form.receivableTotalAmount = rmbCount
        this.calculationCount(rmbCount)
      } else if (this.showCurrencyId === 3) { // 奈拉
        const nairaCount = NP.plus(naira, NP.times(this.UStoNAN(), dollar),  NP.times(this.RMBtoNAN(), rmb))
        this.form.receivableDetailList[2].rate = 1
        this.form.receivableDetailList[2].amount = nairaCount
        this.form.receivableDetailList[0].rate || (this.form.receivableDetailList[0].rate = this.NANtoUS())
        this.form.receivableDetailList[1].rate || (this.form.receivableDetailList[1].rate = this.NANtoRMB())
        this.form.receivableTotalAmount = nairaCount
        this.calculationCount(nairaCount)
      }
    },
    calculationCount(usCount) {
      if (this.showCurrencyId === 1) {
        this.form.receivableDetailList[2].amount = NP.times(this.form.receivableDetailList[2].rate, usCount)
        this.form.receivableDetailList[1].amount = NP.times(this.form.receivableDetailList[1].rate, usCount)
      } else if (this.showCurrencyId === 2) {
        this.form.receivableDetailList[2].amount = NP.times(this.form.receivableDetailList[2].rate, usCount)
        this.form.receivableDetailList[0].amount = NP.times(this.form.receivableDetailList[0].rate, usCount)
      } else if (this.showCurrencyId === 3) {
        this.form.receivableDetailList[1].amount = NP.times(this.form.receivableDetailList[1].rate, usCount)
        this.form.receivableDetailList[0].amount = NP.times(this.form.receivableDetailList[0].rate, usCount)
      }
    },
    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)
    },
    customerChange(value) {
      this.form.customerName = value.name
      this.form.customerId && getCustomer(this.form.customerId).then(res => {
        this.form = {
          ...this.form,
          invoice: this.form.invoice || res.data.invoiceTitle,
          taxpayer: this.form.taxpayer || res.data.licenseNumber,
          accountBank: this.form.accountBank || res.data.bank,
          accountName: this.form.accountName || res.data.bankNumber,
          projectName: this.form.projectName || res.data.project,
          taxRate: this.form.taxRate || res.data.taxRate,
          addressPhone: this.form.addressPhone || `${res.data.billingAddress || ''}/${res.data.billingTell || ''}`,
        }
      })
    },
    subtractItem(index) {
      this.form.receiptAccountList.splice(index, 1)
      this.$set(this.form, 'receiptAccountList', [...this.form.receiptAccountList])
    },
    getReceivableListByIds() {
      
    },
    getList() {
      this.loading1 = true;
      // 处理查询参数
      let params = { ...this.queryParams };
      this.addBeginAndEndTime(params, this.dateType, "createTime");
      // 执行查询
      getReceivableList(params).then((response) => {
        this.orderData = response.data.list;
        this.total = response.data.total;
        this.loading1 = false;
        this.$nextTick(() => {
          this.list.forEach(itm => {
            const t = this.orderData.find(v => v.id == itm.id)
            t && this.$refs.multipleTable.toggleRowSelection(t, true)
          })
        })
      });
    },
    // beforeRemove(file, fileList) {
    //   return this.$confirm(`确定移除？`).then(res => {
    //     setTimeout(() => {
    //       this.fileList = fileList.map(v => v.response.data)
    //     }, 300)
    //   });
    // },
    // handleUploadSuccess(res, file, fileList) {
    //   var arr = [];
    //   fileList.forEach((item) => {
    //     arr.push(item.response.data);
    //   });
    //   this.fileList = arr;
    //   this.loading.close();
    // },
    // handleBeforeUpload() {
    //   this.loading = this.$loading({
    //     lock: true,
    //     text: "上传中",
    //     background: "rgba(0, 0, 0, 0.7)",
    //   });
    // },
    // handleUploadError() {
    //   this.$message({
    //     type: "error",
    //     message: "上传失败",
    //   });
    //   this.loading.close();
    // },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
    },
    hiddenDialog() {
      this.open = false;
    },
    submitForm(addType) {
      const params = {...this.form, addType}
      params.receiptAccountList = params.receiptAccountList
      delete params.receivableDetail
      if (this.list && this.list.length > 0) {
        params.receivableVOList = this.list
      }
      if (params.receivableVOList.length === 0) {
        this.$modal.msgError("请添加未收客户款项");
        return
      }
      if (addType === 1) {
        let fieldsToValidate = ['customerId', 'departmentId', 'salesmanId']; // 部分字段校验 保存草稿用
        Promise.all(
          fieldsToValidate.map((field) => {
            return new Promise((resolve, reject) => {
              this.$refs['form'].validateField(field, (errorMessage) => {
                resolve(errorMessage);
              });
            });
          })
        ).then((errorMessages) => {
          let valid = errorMessages.every((errorMessage) => {
            return errorMessage == '';
          });
          if (valid) {
            if (this.id && this.id !== '0') {
              updateReceipt(params).then(res => {
                this.$modal.msgSuccess("修改成功");
                this.$router.back();
              })
            } else {
              createReceipt(params).then(res => {
                this.$modal.msgSuccess("保存成功");
                this.$router.back();
              })
            }
          }
        });
        return
      }
       this.$refs.form.validate ((valid)=>{
        if (valid) {
          // const params = {...this.form, addType}
          // params.receiptAccountList = params.receiptAccountList
          // delete params.receivableDetail
          // if (this.list && this.list.length > 0) {
          //   params.receivableVOList = this.list
          // }
          // // params.fileList = this.fileList.join(',')
          // if (params.receivableVOList.length === 0) {
          //   this.$modal.msgError("请添加未收客户款项");
          //   return
          // }
          if (this.id && this.id !== '0') {
            updateReceipt(params).then(res => {
              this.$modal.msgSuccess("修改成功");
              this.$router.back();
            })
          } else {
            createReceipt(params).then(res => {
              this.$modal.msgSuccess("新增成功");
              this.$router.back();
            })
          }
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    saveSelectList() {
      this.list = this.multipleSelection
      this.open = false;
      this.calculation()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
    },
  },
};
</script>

<style scoped lang="scss">
.card {
  margin-top: 20px;
}
.dialog-footer {
  padding: 40px;
}
.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%;
  }
}
</style>
