<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="card-title">收款单详情</div>
      <el-descriptions :column="3" border>
        <el-descriptions-item label="收款单编号">{{ form.receiptNo }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <dict-tag :type="DICT_TYPE.ECW_RECEIPT_STATE" :value="form.state"/>
        </el-descriptions-item>
        <el-descriptions-item label="客户">{{ form.customerName }}</el-descriptions-item>
        <el-descriptions-item label="部门">{{ form.departmentName }}</el-descriptions-item>
        <el-descriptions-item label="业务员">{{ form.salesmanName }}</el-descriptions-item>
        <el-descriptions-item label="手续费（RMB）">{{ form.feeRate }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ form.remark }}</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 :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.platformAccountIdList" :label="`收款账户${index + 1}`" :key="index">
          <div style="display: flex">
            <!-- <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0; margin-right: 12px"
              :prop="`platformAccountIdList[${index}].platformAccountId`"
              required
              error="请选择收款账户"
            >
              <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="`platformAccountIdList[${index}].currencyId`"
              required
              error="请选择币种"
            >
              <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.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="是否需要开票">
          <span>{{ form.openInvoice == 1 ? '需要' : '不需要' }}</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="核销基准币种">
          <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">开票资料</div>
      <el-descriptions :column="3" border>
        <el-descriptions-item label="发票抬头">
          {{ form.invoice }}
          <!-- <el-input v-model="form.invoice"></el-input> -->
        </el-descriptions-item>
        <el-descriptions-item label="纳税人识别号">
          {{ form.taxpayer }}
          <!-- <el-input v-model="form.taxpayer"></el-input> -->
        </el-descriptions-item>
        <el-descriptions-item label="开户行">
          {{ form.accountBank }}
          <!-- <el-input v-model="form.accountBank"></el-input> -->
        </el-descriptions-item>
        <el-descriptions-item label="账号">
          {{ form.accountName }}
          <!-- <el-input v-model="form.accountName"></el-input> -->
        </el-descriptions-item>
        <el-descriptions-item label="项目">
          {{ form.projectName }}
          <!-- <el-input v-model="form.projectName"></el-input> -->
        </el-descriptions-item>
        <el-descriptions-item label="税率%">
          {{ form.taxRate }}
          <!-- <el-input v-model="form.taxRate"></el-input> -->
        </el-descriptions-item>
        <el-descriptions-item label="开票地址/电话">
        {{ 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">银行收款明细</div>
      <div>
        <el-button type="primary" plain size="mini" @click="batchVerification" style="padding: 10px; margin-bottom: 10px">批量核销</el-button>
        <el-button type="primary" plain size="mini" @click="handleAddReceiptItem" style="padding: 10px; margin-bottom: 10px">添加收款明细</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="序号" type="index" align="center" width="50"></el-table-column>
        <el-table-column label="收款账户" align="center" prop="accountName" />
        <el-table-column label="实收金额" align="center" prop="amount" />
        <el-table-column label="实收币种" 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="汇率" align="center" prop="rate" />
        <el-table-column label="核销货币金额" align="center" prop="writeOffAmount" />
        <el-table-column label="实收日期" 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="水单号" align="center" prop="billNo" />
        <el-table-column label="水单附件" align="center" prop="attr">
          <template slot-scope="scope" v-if="scope.row.attr">
            <el-link v-for="(v, i) in scope.row.attr" :href="v.url" :key="i" type="primary" target="_blank">{{ v.name }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <span>{{ scope.row.status == 0 ? '待核销' : '已核销' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button v-if="scope.row.status == 0" type="text" @click="deleteClick(scope.row)">删除</el-button>
            <el-button type="text">详情</el-button>
            <el-button v-if="scope.row.status == 0" type="text" @click="verificationClick(scope.row)">核销</el-button>
            <el-button v-if="scope.row.status == 1" type="text" @click="verificationCancelClick(scope.row)">反核销</el-button>
            <el-button v-if="scope.row.status == 0" type="text" @click="editClick(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card class="card">
      <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>
            <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="已核销总金额">
          <el-tag>{{ verificationData.usCount }}美元</el-tag>
          <el-tag>{{ verificationData.rmbCount }}人民币</el-tag>
          <el-tag>{{ verificationData.nairaCount }}奈拉</el-tag>
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            已核销金额（<dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="showCurrencyId" />）
          </template>
          {{ verificationData.writtenOff }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            已核销比例（<dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="showCurrencyId" />）
          </template>
          {{ verificationData.WriteOffProportion }}%
        </el-descriptions-item>
      </el-descriptions>
    </el-card>
    <div slot="footer" style="margin: 20px 0">
      <el-button type="primary" @click="toEdit">编 辑</el-button>
      <el-button type="primary" @click="verificationAll">全部核销</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="收款单号">{{ form.receiptNo }}</el-form-item>
          <el-form-item label="剩余应收金额">
            <div>
              <div>{{ remainingAmount.usAmount }}美元</div>
              <div>{{ remainingAmount.rmbAmount }}人民币</div>
              <div>{{ remainingAmount.nairaAmount }}奈拉</div>
            </div>
          </el-form-item>
          <el-form-item label="收款账户" required prop="accountNo" error="收款账户不能为空">
            <el-select v-model="addForm.accountNo" placeholder="请选择收款账户" style="width: 220px">
              <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="实收日期"
            prop="amountDate"
            required
            error="实收日期不能为空"
          >
            <el-date-picker
              clearable
              v-model="addForm.amountDate"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
              type="date"
              placeholder="选择实收日期"
            />
          </el-form-item>
          <div style="display: flex;">
            <el-form-item
              label="实收"
              prop="amount"
              required
              error="实收不能为空"
            >
              <el-input v-model="addForm.amount" style="width: 220px; margin-right: 12px"></el-input>
            </el-form-item>
            <el-form-item
              label-width="0px"
              prop="currencyId"
              required
              error="币种不能为空"
            >
              <dict-selector :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" v-model="addForm.currencyId" />
            </el-form-item>
          </div>
          <el-form-item
            v-if="showCurrencyId != addForm.currencyId"
            prop="rate"
            required
            error="汇率不能为空"
          >
            <template slot="label">
              汇率（<dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="showCurrencyId" />）
            </template>
            <el-input v-model="addForm.rate" style="width: 220px"></el-input>
          </el-form-item>
          <el-form-item
            v-if="showCurrencyId != addForm.currencyId"
          >
            <template slot="label">
              金额（<dict-tag :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="showCurrencyId" />）
            </template>
            <!-- <el-input v-model="addForm.rate"></el-input> -->
          </el-form-item>
          <el-form-item
            label="收款附件"
            prop="attr"
          >
            <el-upload
              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">上传附件</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item
            label="水单号"
            prop="billNo"
            required
            error="水单号不能为空"
          >
            <el-input v-model="addForm.billNo" style="width: 220px"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button type="primary" @click="saveFrom">{{ saveBtnText }}</el-button>
          <el-button @click="hiddenDialog">取 消</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
} 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: '添加收款明细',
      saveBtnText: '添 加',
      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)
    }
  },
  async created() {
    // 获取汇率
    await getCurrencyPage(this.params).then(res => this.currencyList = 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]
      })
    }
    getBankAccountPage(this.params).then((res) => (this.bankData = res.data.list));
    this.getList()
  },
  methods: {
    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
        }
      }
    },
    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)
      if(val === this.showCurrencyId) {
        this.addForm.rate = 1
      } else {
        if (this.showCurrencyId === 1 && val === 2) this.addForm.rate = this.RMBtoUS()
        else if (this.showCurrencyId === 1 && val === 3) this.addForm.rate = this.NANtoUS()
        else if (this.showCurrencyId === 2 && val === 1) this.addForm.rate = this.UStoRMB()
        else if (this.showCurrencyId === 2 && val === 3) this.addForm.rate = this.NANtoRMB()
        else if (this.showCurrencyId === 3 && val === 1) this.addForm.rate = this.UStoNAN()
        else if (this.showCurrencyId === 3 && val === 2) this.addForm.rate = this.RMBtoNAN()
      }
    },
    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,
          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.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.openAddDialog = false
            this.getList()
          })
        }
      })
      
    },
    toEdit() {
      return this.$router.push("creatCollection?id=" + this.id);
    },
    editClick(row) {
      this.openAddDialog = true
      this.dialogTitle = '编辑收款明细'
      this.saveBtnText = '提 交'
      setTimeout(() => {
        this.addForm = { ...row }
      }, 0)
    },
    deleteClick(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除该收款单?').then(function() {
        return deleteReceiptItem(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    verificationClick(row) {
      const id = row.id;
      this.$modal
        .confirm("您确认要核销吗？")
        .then(function () {
          return receiptItemVerification(id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("核销成功");
        })
        .catch(() => {});
    },
    verificationCancelClick(row) {
      const id = row.id;
      this.$modal
        .confirm("您确认要反核销吗？")
        .then(function () {
          return receiptItemVerificationCancel(id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("反核销成功");
        })
        .catch(() => {});
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    batchVerification() {
      if (this.multipleSelection.length === 0) {
        this.$modal.msgError("请选择需要核销的收款明细！");
        return
      }
      const params = { ids: this.multipleSelection.map(v => v.id).join(',') }
      this.$modal
        .confirm("您确认要核销吗？")
        .then(function () {
          return receiptItemBatchVerification(params);
        })
        .then(() => {
          this.multipleSelection.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
          this.getList();
          this.$modal.msgSuccess("核销成功");
        })
        .catch(() => {});
    },
    verificationAll() {
      this.$modal
        .confirm("您确认要全部核销吗？")
        .then(function () {
          return receiptItemAllVerification(this.id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("核销成功");
        })
        .catch(() => {});
    },
    hiddenDialog() {
      this.openAddDialog = false
    },
    handleAddReceiptItem() {
      this.addForm = {}
      this.openAddDialog = true
      this.dialogTitle = '添加收款明细'
      this.saveBtnText = '添 加'
    },
    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: "上传中",
        background: "rgba(0, 0, 0, 0.7)",
      });
    },
    handleUploadError() {
      this.$message({
        type: "error",
        message: "上传失败",
      });
      this.loading.close();
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除？`).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;
}
</style>