<template>
  <div class="app-container">
    <el-form ref="formInvoiceEL" :model="form" label-width="120px" label-position="left">
      <el-card class="margin-top-card">
        <div slot="header" class="card-title">{{ $t("开票申请信息") }}</div>
        <el-descriptions :column="3" border>
          <el-descriptions-item :label="$t('开票编号')" v-if="$route.query.key != 'reject'">{{ form.invoiceNo }}</el-descriptions-item>
          <el-descriptions-item :label="$t('收款单编号')">
            <router-link :to="`/financial/receiptDetail?id=${form.receiptId}`" class="link-type">
              {{ form.receiptNo }}
            </router-link>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('订单号')" v-if="$route.query.key == 'reject' || $route.query.key == 'delInfo'">
            <div v-for="item in form.orderInfoList" :key="item.orderNo">
              <router-link :to="`/order/detail?orderId=${item.orderId}`" class="link-type">
                {{ item.orderNo }}
              </router-link>
            </div>
          </el-descriptions-item>

          <el-descriptions-item :label="$t('客户')" v-if="$route.query.key != 'reject'">
            <router-link :to="`/customer/query/${form.customerId}`" class="link-type">
              {{ form.customerName }}
            </router-link>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('应收总金额')"
            ><div v-for="item in form.receiptAmount" :key="item.currencyId" class="totalAmountReceivable">{{ item.currencySymbol }}{{ item.totalAmount }}</div>
          </el-descriptions-item>
          <el-descriptions-item
            v-if="$route.query.key != 'reject'"
            :label="
              $t('应收总{currency}', {
                currency: getBaseCurrencynName(form.baseCurrencyId)
              })
            "
            >{{ getCurrencySymbol(form.baseCurrencyId) }}{{ form.receivableTotalAmountUsd }}</el-descriptions-item
          >
          <el-descriptions-item
            v-if="$route.query.key != 'reject'"
            :label="
              $t('总核销比例（{currency})', {
                currency: getBaseCurrencynName(form.baseCurrencyId)
              })
            "
            >{{ form.writeOffProportion }}</el-descriptions-item
          >
          <el-descriptions-item :label="$t('已收总金额')" v-if="$route.query.key != 'reject'">
            <div v-for="item in form.receiptAmount" :key="item.currencyId" class="totalAmountReceivable">{{ item.currencySymbol }}{{ item.writeOffAmount }}</div>
          </el-descriptions-item>
          <el-descriptions-item
            v-if="$route.query.key != 'reject'"
            :label="
              $t('已收总{currency}', {
                currency: getBaseCurrencynName(form.baseCurrencyId)
              })
            "
            >{{ getCurrencySymbol(form.baseCurrencyId) }}{{ form.writeOffAmountUsd }}</el-descriptions-item
          >
          <!-- <el-descriptions-item :label="$t('开票状态')">
            <dict-tag :type="DICT_TYPE.INVOICING_STATUS" :value="form.invoicingStatus" />
          </el-descriptions-item>

          <el-descriptions-item :label="$t('开票资料状态')"> <dict-tag :type="DICT_TYPE.INVOICE_DATA_STATUS" :value="form.invoiceDataStatus" /></el-descriptions-item> -->
        </el-descriptions>
      </el-card>
      <!-- 开票资料 -->
      <el-card class="margin-top-card">
        <div slot="header" class="card-title">
          <span>{{ $t("开票资料") }}</span>
          <!--开票状态=待开票且资料状态=已提交显示驳回资料按钮  -->
          <el-button type="primary" style="float: right" size="small" v-if="$route.query.key === 'view' && form.invoicingStatus === 0 && form.invoiceDataStatus === 0" @click="refreshForReject">{{ $t("驳回资料") }}</el-button>
        </div>
        <el-descriptions :column="3" border>
          <el-descriptions-item :label="$t('发票抬头')">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="invoiceHeader"
              :rules="{
                required: true,
                trigger: ['blur', 'change'],
                message: $t('请输入发票抬头')
              }"
            >
              <el-input :disabled="$route.query.key != 'create' && $route.query.key != 'edit'" v-model="form.invoiceHeader"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('纳税人识别号')">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="taxpayer"
              :rules="{
                required: true,
                trigger: ['blur', 'change'],
                message: $t('请输入纳税人识别号')
              }"
            >
              <el-input :disabled="$route.query.key != 'create' && $route.query.key != 'edit'" style="width: 280px" v-model="form.taxpayer"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('开户行')">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="accountBank"
              :rules="{
                required: true,
                trigger: ['blur', 'change'],
                message: $t('请输入开户行')
              }"
            >
              <el-input :disabled="$route.query.key != 'create' && $route.query.key != 'edit'" v-model="form.accountBank"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('账号')">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="accountName"
              :rules="{
                required: true,
                trigger: ['blur', 'change'],
                message: $t('请输入账号')
              }"
            >
              <el-input :disabled="$route.query.key != 'create' && $route.query.key != 'edit'" v-model="form.accountName"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('开票品名')">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="invoiceItem"
              :rules="{
                required: true,
                trigger: ['blur', 'change'],
                message: $t('请输入开票品名')
              }"
            >
              <el-input :disabled="$route.query.key != 'create' && $route.query.key != 'edit'" style="width: 280px" v-model="form.invoiceItem"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('税率%')">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="taxRate"
              :rules="{
                required: true,
                trigger: ['blur', 'change'],
                message: $t('请输入税率')
              }"
            >
              <el-input-number :controls="false" :disabled="$route.query.key != 'create' && $route.query.key != 'edit'" v-model="form.taxRate"></el-input-number>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('开票地址/电话')">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="invoiceAddress"
              :rules="{
                required: true,
                trigger: ['blur', 'change'],
                message: $t('请输入开票地址/电话')
              }"
            >
              <el-input :disabled="$route.query.key != 'create' && $route.query.key != 'edit'" v-model="form.invoiceAddress"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('开票资料备注')">
            <el-form-item label="" label-width="0" style="margin-bottom: 0">
              <el-input :disabled="$route.query.key != 'create' && $route.query.key != 'edit'" style="width: 280px" v-model="form.invoiceRemark"></el-input>
            </el-form-item>
          </el-descriptions-item>

          <!-- <el-descriptions-item :label="$t('开票资料状态')">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="remark"
              :rules="{
                required: true,
                trigger: ['blur', 'change'],
                message: $t('请选择开票资料状态')
              }"
            >
              <dict-selector multiple :type="DICT_TYPE.INVOICE_DATA_STATUS" v-model="form.invoiceDataStatus" clearable />
            </el-form-item>
          </el-descriptions-item> -->
        </el-descriptions>
      </el-card>
      <!-- 开票信息 -->
      <el-card class="margin-top-card" v-if="($route.query.key == 'view' && form.invoiceNumber) || $route.query.key == 'submitInfo' || $route.query.key == 'editInfo' || $route.query.key == 'delInfo'">
        <div slot="header" class="card-title">{{ $t("开票信息") }}</div>
        <el-descriptions :column="3" border>
          <el-descriptions-item :label="$t('发票号码')">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="invoiceNumber"
              :rules="{
                required: true,
                trigger: ['blur', 'change'],
                message: $t('请输入发票号码')
              }"
            >
              <el-input :disabled="$route.query.key != 'submitInfo' && $route.query.key != 'editInfo'" v-model="form.invoiceNumber"></el-input>
            </el-form-item>
          </el-descriptions-item>

          <el-descriptions-item :label="$t('开票类型')">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="invoiceTypeId"
              :rules="{
                required: true,
                trigger: ['blur', 'change'],
                message: $t('请选择开票类型')
              }"
            >
              <dict-selector :disabled="$route.query.key != 'submitInfo' && $route.query.key != 'editInfo'" :type="DICT_TYPE.ECW_INVOICING_TYPE" v-model="form.invoiceTypeId" />
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('开票金额')">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="invoiceMoney"
              :rules="[
                {
                  required: true,
                  trigger: ['blur', 'change'],
                  message: $t('请输入开票金额')
                }
              ]"
            >
              <!-- <jd-input-number :disabled="$route.query.key != 'submitInfo' && $route.query.key != 'editInfo'" v-model="form.invoiceMoney"> </jd-input-number> -->
              <el-input-number :controls="false" :disabled="$route.query.key != 'submitInfo' && $route.query.key != 'editInfo'" v-model="form.invoiceMoney"></el-input-number>
            </el-form-item>
          </el-descriptions-item>

          <el-descriptions-item :label="$t('币种')">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="currencyId"
              :rules="{
                required: true,
                trigger: ['blur', 'change'],
                message: $t('请选择币种')
              }"
            >
              <el-select :disabled="$route.query.key != 'submitInfo' && $route.query.key != 'editInfo'" v-model="form.currencyId" :placeholder="$t('请选择币种')" clearable size="small">
                <el-option v-for="dict in currencyList" :key="dict.id" :label="$l(dict, 'title') + dict.fuhao" :value="dict.id" />
              </el-select>
            </el-form-item>
          </el-descriptions-item>

          <el-descriptions-item :label="$t('开票人')">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="invoicerId"
              :rules="{
                required: true,
                trigger: ['blur', 'change'],
                message: $t('请输入开票人')
              }"
            >
              <el-select v-model="form.invoicerId" :disabled="$route.query.key != 'submitInfo' && $route.query.key != 'editInfo'" style="width: 280px" :placeholder="$t('开票人')" clearable>
                <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="$t('开票时间')">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              prop="invoiceTime"
              :rules="{
                required: true,
                trigger: ['blur', 'change'],
                message: $t('开票时间')
              }"
            >
              <el-date-picker :disabled="$route.query.key != 'submitInfo' && $route.query.key != 'editInfo'" v-model="form.invoiceTime" type="date" placeholder="选择日期" value-format="yyyy-MM-dd HH:mm:ss"> </el-date-picker>
            </el-form-item>
          </el-descriptions-item>

          <el-descriptions-item :label="$t('开票信息备注')">
            <el-form-item label="" label-width="0" style="margin-bottom: 0">
              <el-input :disabled="$route.query.key != 'submitInfo' && $route.query.key != 'editInfo'" style="width: 280px" v-model="form.invoiceInfoRemark"></el-input>
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
      <!-- 应收明细 -->
      <el-card class="margin-top-card" v-if="$route.query.key != 'reject' && $route.query.key != 'cancel'">
        <div slot="header" class="card-title">
          <span> {{ $t("应收明细") }}</span>
          <el-button @click="controlVisibleReceivables" style="float: right; padding: 3px 0" type="text">{{ $t("隐藏") }}</el-button>
        </div>
        <el-table row-key="id" v-if="visibleReceivables" style="width: 100%" :data="receivableList" show-summary :summary-method="getSummaries" border>
          <el-table-column prop="orderNo" :label="$t('订单号')" width="150"></el-table-column>
          <el-table-column prop="tidanNo" :label="$t('提单号')" width="150" v-if="$route.query.key != 'create' && $route.query.key != 'delInfo'"></el-table-column>
          <el-table-column prop="marks" :label="$t('唛头')" width="100" v-if="$route.query.key != 'create' && $route.query.key != 'delInfo'"></el-table-column>
          <el-table-column prop="titleZh" :label="$t('品名')" width="100">
            <template slot-scope="{ row }">
              {{ $l(row, "title") }}
            </template>
          </el-table-column>
          <el-table-column prop="num" :label="$t('箱数')" width="100"></el-table-column>
          <el-table-column prop="volumeOrWeight" :label="$t('体积/重量')" width="180">
            <template slot-scope="{ row }">
              <div>{{ row.volume }}m³/{{ row.weight }}kg</div>
            </template>
          </el-table-column>
          <el-table-column prop="incomeType" :label="$t('收入类型')" width="120">
            <template slot-scope="{ row }">
              <div>
                <dict-tag :type="DICT_TYPE.FEE_TYPE" :value="row.feeType" />
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="unitPrice" :label="$t('单价金额')" width="120" :formatter="formatCurrency"></el-table-column>
          <el-table-column prop="taxPoint" :label="$t('税率%')" width="80"></el-table-column>
          <el-table-column prop="notIncludedTaxAmount" :label="$t('不含税金额')" width="120" :formatter="formatCurrency"></el-table-column>
          <el-table-column prop="taxAmount" :label="$t('含税金额')" width="120" :formatter="formatCurrency"></el-table-column>
          <el-table-column prop="discountTotal" :label="$t('优惠金额')" width="120" :formatter="formatCurrency"></el-table-column>
          <el-table-column prop="actualAmount" :label="$t('实际金额')" width="120" :formatter="formatCurrency"></el-table-column>
          <el-table-column prop="writeOffAmount" v-if="$route.query.key != 'create' && $route.query.key != 'delInfo'" :label="$t('已核销本币金额')" width="120" :formatter="formatCurrency"></el-table-column>
          <el-table-column prop="notWriteOffAmount" v-if="$route.query.key != 'create' && $route.query.key != 'delInfo'" :label="$t('未核销本币金额')" width="120" :formatter="formatCurrency"></el-table-column>
          <el-table-column
            prop="exchangeRate"
            :label="
              $t('基准币种（{currency}）汇率', {
                currency: getBaseCurrencynName(form.baseCurrencyId)
              })
            "
            width="120"
          >
          </el-table-column>
          <el-table-column
            prop="baseAmount"
            :label="
              $t('基准金额（{currency})', {
                currency: getBaseCurrencynName(form.baseCurrencyId)
              })
            "
            width="120"
            :formatter="formatCurrency"
          ></el-table-column>
          <el-table-column
            v-if="$route.query.key != 'create' && $route.query.key != 'delInfo'"
            prop="writeOffAmountUsd"
            :label="
              $t('已核销金额（{currency})', {
                currency: getBaseCurrencynName(form.baseCurrencyId)
              })
            "
            width="120"
            :formatter="formatCurrency"
          ></el-table-column>
          <el-table-column
            v-if="$route.query.key != 'create' && $route.query.key != 'delInfo'"
            prop="notWriteOffAmountUsd"
            :label="
              $t('未核销金额（{currency})', {
                currency: getBaseCurrencynName(form.baseCurrencyId)
              })
            "
            width="120"
            :formatter="formatCurrency"
          ></el-table-column>
          <el-table-column prop="writeOffProportion" v-if="$route.query.key != 'create' && $route.query.key != 'delInfo'" :label="$t('已核销比例')" width="120"></el-table-column>
        </el-table>
      </el-card>
      <!-- 最后操作人信息 -->
      <el-card class="margin-top-card" v-if="$route.query.key != 'reject' && $route.query.key != 'cancel'">
        <el-descriptions :column="4" border>
          <el-descriptions-item :label="$t('收款人')">{{ form.payee }}</el-descriptions-item>
          <el-descriptions-item :label="$t('核销人')">{{ form.writeOffUser }}</el-descriptions-item>
          <el-descriptions-item :label="$t('申请人')">{{ form.creator }}</el-descriptions-item>

          <el-descriptions-item :label="$t('申请时间')">{{ form.createTime }}</el-descriptions-item>
          <el-descriptions-item :label="$t('最后修改人')">{{ form.updater }}</el-descriptions-item>
          <el-descriptions-item :label="$t('最后修改时间')">{{ form.updateTime }}</el-descriptions-item>
          <el-descriptions-item v-if="form.cancelUserName" :label="$t('开票取消人')">{{ form.cancelUserName }}</el-descriptions-item>
          <el-descriptions-item v-if="form.cancelTime" :label="$t('开票取消时间')">{{ form.cancelTime }}</el-descriptions-item>
        </el-descriptions>
      </el-card>
      <!-- 驳回/取消资料 -->
      <el-card class="margin-top-card" v-if="visibleRejectOrcancelCard">
        <div slot="header" class="card-title">{{ $t(`${rejectOrCancelLabel}信息`) }}</div>
        <div class="infoBox">
          <el-form-item
            :label="$t(`${rejectOrCancelLabel}备注`)"
            prop="remark"
            :rules="{
              required: true,
              trigger: ['blur', 'change'],
              message: $t('请输入备注')
            }"
          >
            <el-input style="width: 280px" v-model="form.remark"></el-input>
          </el-form-item>

          <el-form-item :label="$t('通知人')" :rules="[{ required: true, message: '请选择通知人', trigger: ['blur', 'change'] }]">
            <el-select style="width: 280px" v-model="form.notifyUserIdList" multiple :placeholder="$t('通知人')" clearable>
              <el-option v-for="item in creatorData" :key="item.id" :label="item.nickname" :value="item.id" />
            </el-select>
          </el-form-item>
        </div>
      </el-card>
      <!-- 删除开票信息 -->
      <el-card class="margin-top-card" v-if="$route.query.key == 'delInfo'">
        <div class="infoBox">
          <el-form-item
            :label="$t(`删除开票备注`)"
            prop="remark"
            :rules="{
              required: true,
              trigger: ['blur', 'change'],
              message: $t('请输入备注')
            }"
          >
            <el-input style="width: 280px" v-model="form.remark"></el-input>
          </el-form-item>
        </div>
      </el-card>

      <!-- 日志信息 -->
      <el-card class="margin-top-card" v-if="$route.query.key == 'view'">
        <div class="infoBox">
          <div slot="header" class="card-title">{{ $t("日志信息") }}</div>
          <div class="box-table">
            <el-table v-loading="loading" :data="invoiceLogList" border class="card" row-key="id">
              <el-table-column :label="$t('环节')" align="center">
                <template slot-scope="scope">
                  <dict-tag :type="DICT_TYPE.INVOICEING_LINK" :value="scope.row.invoicingLink" />
                </template>
              </el-table-column>
              <el-table-column :label="$t('操作人')" align="center" prop="operator" />
              <el-table-column :label="$t('操作时间')" align="center" prop="createTime" />
              <el-table-column :label="$t('备注')" align="center" prop="remark" />
            </el-table>
          </div>
        </div>
      </el-card>
      <!-- 操作按钮 -->
      <div class="btnBox">
        <el-button type="primary" @click="goBack" plain>{{ $t("返回") }}</el-button>
        <el-button type="primary" v-if="$route.query.key === 'create'" @click="submitInvoiceForm('create')">{{ $t("提交申请") }}</el-button>
        <el-button type="primary" v-if="$route.query.key === 'edit'" @click="submitInvoiceForm('edit')">{{ $t("确认修改开票申请") }}</el-button>
        <el-button type="primary" v-if="$route.query.key === 'reject'" @click="rejectOrCancleInvoiceData">{{ $t("确认驳回资料") }}</el-button>
        <el-button type="primary" v-if="$route.query.key === 'cancel'" @click="rejectOrCancleInvoiceData">{{ $t("确认取消开票") }}</el-button>
        <el-button type="primary" v-if="$route.query.key === 'submitInfo'" @click="submitInvoiceFormInfo">{{ $t("提交开票") }}</el-button>
        <el-button type="primary" v-if="$route.query.key === 'editInfo'" @click="submitInvoiceFormInfo">{{ $t("修改开票信息") }}</el-button>
        <el-button type="primary" v-if="$route.query.key === 'delInfo'" @click="delInvoiceFormInfo">{{ $t("删除开票信息") }}</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import { loadReceiptInvoiceInfo, createInvoiceApplication, loadINVInfoByInvoiceId, updateInvoiceApplication, rejectInvoiceApplication, cancelInvoiceApplication, updateInvoiceApplicationInfo, delInvoiceApplication } from "@/api/ecw/financial"
import { getNowDateTime } from "@/utils/ruoyi"
import { listSimpleUsers } from "@/api/system/user"
import { DICT_TYPE } from "@/utils/dict"
import { mapGetters } from "vuex"
import JdInputNumber from "@/views/ecw/customer/components/jd-input-number.vue"
export default {
  components: {
    JdInputNumber
  },
  data() {
    return {
      currencyList: this.$store.state.staticData.currencyList,
      creatorData: [], //业务员列表
      rejectOrCancelLabel: "驳回",
      visibleRejectOrcancelCard: false,
      visibleReceivables: false,
      form: {},
      invoiceLogList: [],
      receivableList: []
    }
  },
  mounted() {
    this.getReceiptInvoiceInfo()
    listSimpleUsers().then((res) => (this.creatorData = res.data))
  },
  watch: {
    "$route.query.key": {
      handler(val) {
        switch (val) {
          case "reject":
            this.rejectOrCancelLabel = "驳回"
            this.visibleRejectOrcancelCard = true
            break
          case "cancel":
            this.rejectOrCancelLabel = "取消"
            this.visibleRejectOrcancelCard = true
            break
          default:
            this.visibleRejectOrcancelCard = false
            break
        }
        // if (val) {
        //   this.queryParams.rewardCode = val
        // }
      },
      immediate: true
    }
  },
  computed: {
    ...mapGetters(["getCurrencySymbol", "getCurrencyData", "name", "userId"]),
    getBaseCurrencynName() {
      return (currencyId) => {
        if (currencyId) {
          return this.$l(this.getCurrencyData(currencyId), "title")
        }
        return "XX"
      }
    }
  },

  methods: {
    goBack() {
      this.$router.go(-1)
    },
    // 刷新当前到驳回状态
    refreshForReject() {
      this.$router.push("invoiceOperate?id=" + this.$route.query.id + "&key=reject")
    },
    async validateFormResult() {
      return await this.$refs["formInvoiceEL"].validate()
    },
    // delete invoice info
    async delInvoiceFormInfo() {
      const result = await this.validateFormResult()
      if (result) {
        let params = {
          remark: this.form.remark,
          id: this.form.id
        }
        await this.$modal.confirm(this.$t("确认删除开票信息吗?"))
        const data = await delInvoiceApplication(params)
        if (data.code === 0) {
          this.$message({
            message: this.$t("成功"),
            type: "success"
          })
          this.goBack()
        }
      }
    },
    //驳回取消资料
    async rejectOrCancleInvoiceData() {
      const result = await this.validateFormResult()
      let apiFuncName = rejectInvoiceApplication
      if (result) {
        if (this.$route.query.key == "cancel") {
          apiFuncName = cancelInvoiceApplication
        }
        let params = {
          remark: this.form.remark,
          id: this.form.id,
          notifyUserIdList: this.form.notifyUserIdList
        }
        await this.$modal.confirm(this.$t(`确认${this.rejectOrCancelLabel}开票资料吗?`))
        const data = await apiFuncName(params)
        if (data.code === 0) {
          this.$message({
            message: this.$t("成功"),
            type: "success"
          })
          this.goBack()
        }
      }
    },
    //提交开票--提交的是开票信息
    async submitInvoiceFormInfo() {
      const result = await this.validateFormResult()

      if (result) {
        let params = {
          invoiceNumber: this.form.invoiceNumber,
          invoiceTypeId: this.form.invoiceTypeId,
          invoiceMoney: this.form.invoiceMoney,
          currencyId: this.form.currencyId,
          id: this.form.id,
          invoicerId: this.form.invoicerId,
          invoiceTime: this.form.invoiceTime,
          invoiceInfoRemark: this.form?.invoiceInfoRemark || ""
        }
        await this.$modal.confirm(this.$t(`确认提交开票吗?`))
        const data = await updateInvoiceApplicationInfo(params)
        if (data.code === 0) {
          this.$message({
            message: this.$t("成功"),
            type: "success"
          })
          this.goBack()
        }
      }
    },
    //提交开票申请
    submitInvoiceForm(key) {
      this.$refs["formInvoiceEL"].validate((valid) => {
        if (valid) {
          const params = {
            invoiceHeader: this.form.invoiceHeader, //发票抬头
            taxpayer: this.form.taxpayer, //纳税人识别号
            accountBank: this.form.accountBank, //开户行
            accountName: this.form.accountName, //账号
            invoiceItem: this.form.invoiceItem, // 开票品名
            taxRate: this.form.taxRate, //税率%
            invoiceAddress: this.form.invoiceAddress, // 	开票地址/电话字段合二为一
            invoiceRemark: this.form.invoiceRemark || "", //备注
            receiptId: this.form.receiptId //收款单id
          }
          let createOrEditFunc = createInvoiceApplication //创建开票
          let confirmLabel = "创建"
          if (key == "edit") {
            params.id = this.$route.query.id
            createOrEditFunc = updateInvoiceApplication //更新开票资料
            confirmLabel = "更新"
          }
          this.$modal.confirm(this.$t(`确认${confirmLabel}开票资料吗?`)).then((result) => {
            createOrEditFunc(params).then((res) => {
              console.log("FORMiNFO1", res)
              if (res.code === 0) {
                this.$message({
                  message: this.$t("成功"),
                  type: "success"
                })
                this.$router.push({ path: "/financial/receivable/voucher" })
              }
            })
          })
        } else {
          console.log("error submit!!")
          return false
        }
      })
    },
    //应收明细显示隐藏
    controlVisibleReceivables() {
      this.visibleReceivables = !this.visibleReceivables
    },

    // 获取开票信息
    async getReceiptInvoiceInfo() {
      let params = {}
      let loadInvoiceFuncName = loadReceiptInvoiceInfo
      if (this.$route.query.key === "create") {
        //通过收款单id
        params = { receiptId: this.$route.query.id }
      } else {
        //开票id
        params = { id: this.$route.query.id }
        loadInvoiceFuncName = loadINVInfoByInvoiceId
      }

      const { data } = await loadInvoiceFuncName(params)
      this.form = data
      this.receivableList = data?.receivableList
      this.invoiceLogList = data?.invoiceLog
      if (this.$route.query.key === "create") {
        this.form.creator = this.name
        this.form.taxRate = undefined
      } else {
        console.log("edwedfnwevjc", this.userId)
        this.form.invoicerId = this.userId
        this.form.invoiceTime = getNowDateTime()
      }
      if (!this.form?.currencyId) {
        this.form.invoiceMoney = undefined
        this.form.currencyId = 3
      }
      this.$nextTick(() => {
        this.$refs["formInvoiceEL"].clearValidate()
      })
    },
    // 用于格式化货币的函数
    formatCurrency(row, column, cellValue) {
      if (column.property == "baseAmount" || column.property == "writeOffAmountUsd" || column.property == "notWriteOffAmountUsd") {
        return this.getCurrencySymbol(row.baseCurrencyId) + (cellValue || "0")
      }
      return this.getCurrencySymbol(row.currencyId) + (cellValue || "0")
    },

    //合计金额
    getSummaries(param) {
      const { columns, data } = param
      console.log("edcfbnsdjbnwode", param)
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = this.$t("合计金额")
          return
        } else if (column.property != "unitPrice" && column.property != "notIncludedTaxAmount" && column.property != "taxAmount" && column.property != "discountTotal" && column.property != "actualAmount" && column.property != "writeOffAmount" && column.property != "notWriteOffAmount" && column.property != "baseAmount" && column.property != "writeOffAmountUsd" && column.property != "notWriteOffAmountUsd") {
          sums[index] = "NA"
          return
        } else {
          const currencyIdList = Array.from(new Set(data.map((item) => item.currencyId)))
          // if (index == 7) {
          const currencySums = {}
          data.forEach((item) => {
            let currencyId = item.currencyId
            // 基准金额（XX)baseAmount   已核销金额 writeOffAmountUsd 未核销金额 notWriteOffAmountUsd 币种取 基准币种
            if (column.property == "writeOffAmountUsd" || column.property == "baseAmount" || column.property == "notWriteOffAmountUsd") {
              currencyId = item.baseCurrencyId
            }

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

      return sums
    }
  }
}
</script>

<style lang="scss" scoped>
.margin-top-card {
  margin-top: 20px;
}
.btnBox {
  padding-top: 80px;
  padding-bottom: 20px;
}
.card-title {
  font-size: 18px;
  font-weight: bold;
}
</style>
