<template>
  <div class="app-container">
    <el-dialog :before-close="hiddenDialog" :visible.sync="openBankReceiptsDetailItemDialog" :title="dialogTitle" width="50%" append-to-body>
      <div style="padding: 0 24px">
        <el-form :disabled="statusKey == 'view'" ref="addForm" :model="bankReceiptDetails" label-width="250px">
          <el-form-item :label="$t('流水号')">{{ bankReceiptDetails.serialNumber }}</el-form-item>
          <el-form-item :label="$t('收款单号')">{{ bankReceiptDetails.receiptNo }}</el-form-item>
          <el-form-item :label="$t('剩余应收金额')">
            <span>{{ getCurrencySymbol(bankReceiptDetails.writeOffCurrencyId) }} {{ bankReceiptDetails.syValue }} </span>
          </el-form-item>
          <el-form-item
            :label="$t('收款账户')"
            prop="accountNo"
            :rules="{
              required: true,
              trigger: ['blur', 'change'],
              message: $t('收款账户不能为空')
            }"
          >
            <el-select filterable clear v-model="bankReceiptDetails.accountId" :placeholder="$t('请选择收款账户')" style="width: 250px" @change="accountChange">
              <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="$t('实收日期')"
            prop="amountDate"
            :rules="{
              required: true,
              trigger: ['blur', 'change'],
              message: $t('实收日期不能为空')
            }"
          >
            <el-date-picker v-if="statusKey != 'view'" clearable v-model="bankReceiptDetails.amountDate" value-format="yyyy-MM-dd" format="yyyy-MM-dd" type="date" :placeholder="$t('选择实收日期')" />
            <span v-else>{{ bankReceiptDetails.amountDate }}</span>
          </el-form-item>
          <div style="display: flex">
            <el-form-item
              :label="$t('实收')"
              prop="amount"
              :rules="{
                required: true,
                trigger: ['blur', 'change'],
                message: $t('实收不能为空')
              }"
            >
              <el-input v-if="statusKey != 'view'" v-model="bankReceiptDetails.amount" style="width: 220px; margin-right: 12px" @change="setWriteOffAmount('input')"></el-input>
              <span v-else>{{ bankReceiptDetails.amount }}</span>
            </el-form-item>
            <el-form-item
              label-width="0px"
              prop="currencyId"
              :rules="{
                required: true,
                trigger: ['blur', 'change'],
                message: $t('币种不能为空')
              }"
            >
              <el-select v-model="bankReceiptDetails.currencyId" :placeholder="$t('请选择')" @change="(val) => currencyIdChange(val)">
                <el-option v-for="item in currencyList" :key="item.id" :label="$i18n.locale == 'zh_CN' ? item.titleZh : item.titleEn" :value="item.id" />
              </el-select>
            </el-form-item>
          </div>
          <el-form-item
            v-if="bankReceiptDetails.writeOffCurrencyId != bankReceiptDetails.currencyId"
            prop="rate"
            :rules="{
              required: true,
              trigger: ['blur', 'change'],
              message: $t('兑核销基准币种汇率不能为空')
            }"
          >
            <template slot="label">
              <span :title="$t('实收币种与核销基准币种一样时，无需填写汇率，不一样需要填写汇率')">{{ $t("兑核销基准币种汇率") }}（{{ getCurrencyLabel(bankReceiptDetails.writeOffCurrencyId) }}）</span>
            </template>
            <el-input v-if="statusKey != 'view'" v-model="bankReceiptDetails.rate" style="width: 220px"></el-input>
            <span v-else>{{ bankReceiptDetails.rate }}</span>
          </el-form-item>
          <el-form-item v-if="bankReceiptDetails.writeOffCurrencyId != bankReceiptDetails.currencyId">
            <template slot="label"> {{ $t("兑核销基准币种金额") }}（{{ getCurrencyLabel(bankReceiptDetails.writeOffCurrencyId) }}） </template>
            <span>{{ bankReceiptDetails.writeOffAmount ? parseFloat(bankReceiptDetails.writeOffAmount).toFixed(2) : "" }}</span>
          </el-form-item>
          <el-form-item :label="$t('水单附件')" prop="attr">
            <el-upload v-if="statusKey != 'view'" class="upload-demo" :action="uploadFileUrl" :headers="headers" :on-success="handleUploadSuccess" :before-upload="handleBeforeUpload" :on-error="handleUploadError" :before-remove="beforeRemove" :file-list="bankReceiptDetails.attr" multiple>
              <el-button size="small" type="primary">{{ $t("上传附件") }}</el-button>
            </el-upload>
            <div v-else>
              <div v-for="(v, i) in bankReceiptDetails.attr" :key="i">
                <el-link :href="v.url" type="primary" target="_blank">{{ v.name }}</el-link>
              </div>
            </div>
          </el-form-item>

          <el-form-item>
            <template slot="label"> {{ $t("备注") }} </template>
            <div>
              <el-input v-if="statusKey != 'view'" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" :placeholder="$t('请输入内容')" v-model="bankReceiptDetails.remark"></el-input>
              <span v-else>{{ bankReceiptDetails.remark }}</span>
            </div>
          </el-form-item>
          <div class="title">
            {{ $t("应收明细") }}
          </div>
          <div class="detail">
            <div class="detailItem" v-if="statusKey != 'view'">
              <el-descriptions :column="4" border class="card detailLeft" v-if="bankReceiptDetails.writeOffAmount">
                <el-descriptions-item
                  :label="
                    $t('基准金额{currency}', {
                      currency: getCurrencyLabel(bankReceiptDetails.writeOffCurrencyId)
                    })
                  "
                >
                  {{ bankReceiptDetails.writeOffAmount }}
                </el-descriptions-item>
                <el-descriptions-item :label="$t('已填写核销金额')"> {{ bankReceiptDetails.currentWriteOffAmount || 0 }} </el-descriptions-item>
                <el-descriptions-item label-class-name="warnColor" content-class-name="warnColor" :label="$t('未填写核销金额')"> {{ bankReceiptDetails.remainingWriteOffAmount || 0 }} </el-descriptions-item>、
              </el-descriptions>
              <div class="detailBtn" v-if="bankReceiptDetails.writeOffAmount">
                <el-button size="small" :disabled="statusKey == 'view'" type="primary" @click="autoFillWriteOffAmount">{{ $t("自动填写") }}</el-button>
              </div>
            </div>
            <el-table border :data="bankReceiptDetails.receivableList">
              <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="actualAmount" :label="$t('实际金额')" width="120" :formatter="formatCurrency"></el-table-column>

              <el-table-column
                prop="exchangeRate"
                :label="
                  $t('基准币种（{currency}）汇率', {
                    currency: getBaseCurrencynName(bankReceiptDetails.writeOffCurrencyId)
                  })
                "
              >
              </el-table-column>
              <el-table-column
                prop="baseAmount"
                :label="
                  $t('基准金额（{currency})', {
                    currency: getBaseCurrencynName(bankReceiptDetails.writeOffCurrencyId)
                  })
                "
                width="120"
                :formatter="formatCurrency"
              ></el-table-column>
              <el-table-column
                prop="writeOffAmountUsd"
                v-if="statusKey != 'view'"
                :label="
                  $t('已核销金额（{currency})', {
                    currency: getBaseCurrencynName(bankReceiptDetails.writeOffCurrencyId)
                  })
                "
                :formatter="formatCurrency"
              ></el-table-column>
              <el-table-column
                v-if="statusKey != 'view'"
                :label="
                  $t('剩余核销金额（{currency})', {
                    currency: getBaseCurrencynName(bankReceiptDetails.writeOffCurrencyId)
                  })
                "
                width="120"
              >
                <template v-slot="{ row }">
                  <div :class="{ warnColor: row.notWriteOffAmountUsd < 0 }">{{ getCurrencySymbol(row.baseCurrencyId) }} {{ row.notWriteOffAmountUsd }}</div>
                </template>
              </el-table-column>
              <!-- 本次核销金额（美元） -->
              <el-table-column
                width="160"
                :label="
                  $t('本次核销金额（{currency})', {
                    currency: getBaseCurrencynName(bankReceiptDetails.writeOffCurrencyId)
                  })
                "
              >
                <template slot-scope="scope">
                  <el-input-number style="width: 138px" @change="changeCurrentItemWirteOff(scope.row.id)" v-if="statusKey != 'view' && bankReceiptDetails.writeOffAmount" :min="0" :precision="2" :controls="false" v-model="scope.row.writeOffAmount"></el-input-number>
                  <span v-else>{{ scope.row.writeOffAmount }}</span>
                </template>
                <!-- writeOffAmount -->
              </el-table-column>
            </el-table>
            <!-- 应收明细列表弹窗 -->
          </div>
        </el-form>
      </div>
      <div slot="footer" v-if="statusKey != 'view'">
        <el-button type="primary" @click="saveFrom">{{ $t("编辑") }}</el-button>
        <el-button @click="hiddenDialog">{{ $t("取消") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getBankAccountPage } from "@/api/ecw/bankAccount"
import { getReceivableItem2, updateReceiptItem, receiptItemCreate, loadBankReceiptItemListByID } from "@/api/ecw/financial"
import { getExchangeRatePage } from "@/api/ecw/exchangeRate"
import { getToken } from "@/utils/auth"
import { getCurrencyPage } from "@/api/ecw/currency"
import { mapGetters } from "vuex"
import NP from "number-precision"
export default {
  name: "BankReceiptsDetailItem",
  props: {
    statusKey: {
      type: String,
      default: ""
    },
    openBankReceiptsDetailItemDialog: {
      type: Boolean,
      default: false
    },
    bankReceiptId: {
      type: [String, Number],
      default: ""
    }
  },
  watch: {
    openBankReceiptsDetailItemDialog(val, old) {
      this.bankReceiptDetails = {}
      if (val) {
        this.getBankReceiptsDetails()
      }
    },
    statusKey(val, old) {
      if (val == "edit") {
        // this.getBankReceiptsDetails()
        this.dialogTitle = this.$t("编辑银行实收明细")
      } else {
        // this.getBankReceiptsDetails()
        this.dialogTitle = this.$t("银行实收明细详情")
      }
    },
    "bankReceiptDetails.rate"() {
      this.setWriteOffAmount()
    }
  },
  data() {
    return {
      NP,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/app-api/file/upload",
      headers: {
        Authorization: "Bearer " + getToken()
      },
      bankData: [],
      currencyList: [],
      dialogTitle: "",
      rateList: [],
      bankReceiptDetails: {},
      codePage: {
        pageNo: 1,
        pageSize: 1000,
        page: 1,
        rows: 1000
      }
    }
  },
  created() {
    getCurrencyPage(this.codePage).then((res) => (this.currencyList = res.data.list))
    getExchangeRatePage(this.codePage).then((res) => (this.rateList = res.data.list))
    getBankAccountPage(this.codePage).then((res) => {
      this.bankData = res.data.list
    })
  },
  computed: {
    ...mapGetters(["getCurrencySymbol", "getCurrencyData"]),
    getBaseCurrencynName() {
      return (currencyId) => {
        if (currencyId) {
          return this.$l(this.getCurrencyData(currencyId), "title")
        }
        return "XX"
      }
    }
  },
  methods: {
    // 获取应收明细
    getReceiptDetails() {
      let id = this.bankReceiptId
      let currentTotal = 0
      loadBankReceiptItemListByID({ receiptItemId: id }).then((res) => {
        this.bankReceiptDetails.receivableList = res.data
        this.bankReceiptDetails.receivableList.forEach((item) => {
          currentTotal += item.writeOffAmount
        })
        if (this.bankReceiptDetails.writeOffAmount && currentTotal > this.bankReceiptDetails.writeOffAmount) {
          this.$modal.msgError(this.$t("本次实收基准金额小于上次填写核销金额总额,请注意"))
        }
        // this.bankReceiptDetails.receivableList.forEach((item) => {
        //  未填写实收
        this.bankReceiptDetails.remainingWriteOffAmount = NP.minus(this.bankReceiptDetails.writeOffAmount, currentTotal)
        // 已填写核销金额
        this.bankReceiptDetails.currentWriteOffAmount = currentTotal
        // })
      })
    },
    // 自动填充
    autoFillWriteOffAmount() {
      let id = this.bankReceiptId

      loadBankReceiptItemListByID({ receiptItemId: id }).then((res) => {
        let currentTotal = 0
        this.bankReceiptDetails.receivableList = res.data
        this.bankReceiptDetails.receivableList.forEach((item) => {
          currentTotal += item.writeOffAmount
        })
        if (this.bankReceiptDetails.writeOffAmount && currentTotal > this.bankReceiptDetails.writeOffAmount) {
          this.$modal.msgError(this.$t("本次实收基准金额小于上次填写核销金额总额,请注意"))
        }
        // this.bankReceiptDetails.receivableList.forEach((item) => {
        //  未填写实收
        this.bankReceiptDetails.remainingWriteOffAmount = NP.minus(this.bankReceiptDetails.writeOffAmount, currentTotal)
        // 已填写核销金额
        this.bankReceiptDetails.currentWriteOffAmount = currentTotal
        // })

        // this.bankReceiptItemList.forEach((item) => {
        //   currentTotal += item.writeOffAmount
        // })
        // if (currentTotal > this.addForm.writeOffAmount) {
        //   this.$modal.msgError(this.$t("本次实收基准金额小于上次填写核销金额总额,请注意"))
        // }
        // this.bankReceiptItemList.forEach((item) => {
        //   //  未填写实收
        //   this.addForm.remainingWriteOffAmount = NP.minus(this.addForm.writeOffAmount, currentTotal)
        //   // 已填写核销金额
        //   this.addForm.currentWriteOffAmount = currentTotal
        // })

        this.autoFillCalculate()
      })
    },
    autoFillCalculate() {
      let writeOffAmount = this.bankReceiptDetails.writeOffAmount
      // 已填写核销金额
      let totalWriteOffAmountUsd = this.bankReceiptDetails.currentWriteOffAmount
      // 未填写核销金额
      let remainingWriteOffAmount = this.bankReceiptDetails.remainingWriteOffAmount
      this.bankReceiptDetails.receivableList.forEach((item) => {
        // baseAmount 基准金额  writeOffAmountUsd  已核销金额, notWriteOffAmountUsd剩余未核销
        if (item.notWriteOffAmountUsd > 0 && writeOffAmount && writeOffAmount > 0 && writeOffAmount >= item.notWriteOffAmountUsd) {
          //  本次核销金额
          item.writeOffAmount = NP.minus(item.baseAmount, item.writeOffAmountUsd)
          // 总核销实收剩余
          writeOffAmount = NP.minus(writeOffAmount, item.writeOffAmount)
          //剩余未核销
          item.notWriteOffAmountUsd = 0

          //未填写实收
          // this.bankReceiptDetails.remainingWriteOffAmount = writeOffAmount
        } else if (writeOffAmount && writeOffAmount > 0 && writeOffAmount < item.notWriteOffAmountUsd) {
          item.writeOffAmount = writeOffAmount
          item.notWriteOffAmountUsd = NP.minus(item.baseAmount, item.writeOffAmountUsd, item.writeOffAmount)
          writeOffAmount = 0
          // this.bankReceiptDetails.remainingWriteOffAmount = writeOffAmount
        } else {
          item.writeOffAmount = 0
        }
      })

      //  未填写实收
      this.bankReceiptDetails.remainingWriteOffAmount = writeOffAmount
      // 已填写核销金额
      this.bankReceiptDetails.currentWriteOffAmount = NP.minus(this.bankReceiptDetails.writeOffAmount, writeOffAmount)
    },
    changeCurrentItemWirteOff(id) {
      let currentTotal = 0
      this.$nextTick(() => {
        this.bankReceiptDetails.receivableList.forEach((item) => {
          currentTotal += item.writeOffAmount
        })
        if (currentTotal > this.bankReceiptDetails.writeOffAmount) {
          this.$modal.msgError(this.$t("填写核销金额总额大于本次实收基准金额,请重新填写"))
        }
        this.bankReceiptDetails.receivableList.forEach((item) => {
          if (item.id == id) {
            if (currentTotal > this.bankReceiptDetails.writeOffAmount) {
              item.writeOffAmount = 0
            } else {
              //  未填写实收
              this.bankReceiptDetails.remainingWriteOffAmount = NP.minus(this.bankReceiptDetails.writeOffAmount, currentTotal)
              // 已填写核销金额
              this.bankReceiptDetails.currentWriteOffAmount = currentTotal
            }
          }
        })
      })
    },
    hiddenDialog() {
      this.$emit("update:openBankReceiptsDetailItemDialog", false)
    },
    saveFrom() {
      const params = { ...this.bankReceiptDetails }
      params.writeOffCurrencyId = this.bankReceiptDetails.writeOffCurrencyId
      params.receivableWriteOffList = []
      try {
        let totalInput = 0
        this.bankReceiptDetails.receivableList.map((item) => {
          totalInput += item.writeOffAmount
          if (!isNumberStr(item.writeOffAmount)) {
            this.$modal.msgError(this.$t(`请输入明细核销金额`))
            throw new Error("Exit loop")
          }
          if (isNumberStr(item.writeOffAmount) && item.writeOffAmount > 0) {
            params.receivableWriteOffList.push({
              receivableId: item.id,
              writeOffAmount: item.writeOffAmount
            })
          }
        })
        if (this.bankReceiptDetails.remainingWriteOffAmount != 0) {
          this.$modal.msgError(this.$t(`未填写核销金额>0 ,请检查`))
          throw new Error("Exit loop")
        }
        if (totalInput > this.bankReceiptDetails.writeOffAmount) {
          this.$modal.msgError(this.$t(`本次填写核销金额总数大于实收基准金额`))
          throw new Error("Exit loop")
        }
      } catch (e) {
        return
      }
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          // if (this.addForm.id) {
          params.attr && (params.attr = params.attr.map((v) => v.url).join(","))
          updateReceiptItem(params).then((res) => {
            this.$modal.msgSuccess(this.$t("修改成功"))
            // this.openAddDialog = false
            this.hiddenDialog()
            this.getList()
          })
        }
      })
    },
    setWriteOffAmount(key = "") {
      console.log("ksnjsnasjn")
      let pointArr = []
      let regs = /^[0-9]+\d*(\.\d*)?$|^0?\.\d*[0-9]\d*$/
      if (this.bankReceiptDetails.amount && !regs.test(this.bankReceiptDetails.amount)) {
        this.bankReceiptDetails.amount = ""
        this.$modal.msgError(this.$t("输入金额不对"))
      } else {
        if (this.bankReceiptDetails && this.bankReceiptDetails.amount) {
          pointArr = this.bankReceiptDetails.amount.toString().split(".")
          if (pointArr.length > 1 && pointArr[1]) {
            this.bankReceiptDetails.amount = Math.round(this.bankReceiptDetails.amount * 100) / 100
          }
        }
      }
      this.$set(this.bankReceiptDetails, "writeOffAmount", NP.round(NP.times(this.bankReceiptDetails.rate || 0, this.bankReceiptDetails.amount || 0), 2))
      //已填写核销金额
      this.$set(this.bankReceiptDetails, "currentWriteOffAmount", 0)
      // 剩余核销金额
      this.$set(this.bankReceiptDetails, "remainingWriteOffAmount", NP.times(this.bankReceiptDetails.rate || 0, this.bankReceiptDetails.amount || 0))

      this.getReceiptDetails()
    },
    //币种更改
    currencyIdChange(val) {
      val = Number(val)
      let rate
      if (val === this.bankReceiptDetails.writeOffCurrencyId) {
        rate = 1
      } else {
        rate = this.getRate(val, this.bankReceiptDetails.writeOffCurrencyId)
      }
      this.$set(this.bankReceiptDetails, "rate", rate)
    },
    //获取汇率
    getRate(sourceCurrencyId, targetCurrencyId) {
      let rate = this.rateList.find((v) => v.sourceCurrencyId === sourceCurrencyId && v.targetCurrencyId === targetCurrencyId)
      if (rate) return rate.currencyRate
      return ""
    },
    getCurrencyLabel(id) {
      let label = this.currencyList.filter((item) => item.id == id)
      if (label.length > 0) return this.$i18n.locale == "zh_CN" ? label[0].titleZh : label[0].titleEn
      return ""
    },
    formatCurrency(row, column, cellValue) {
      if (column.property == "writeOffAmount") {
        return this.getCurrencySymbol(row.writeOffCurrencyId) + (cellValue || "0")
      }
      return this.getCurrencySymbol(row.currencyId) + (cellValue || "0")
    },
    //银行账号变动
    accountChange(val) {
      let data = this.bankData.find((item) => item.id == val)
      this.$set(this.bankReceiptDetails, "accountName", data.baAccountName || "")
      this.$set(this.bankReceiptDetails, "accountNo", data.baAccountNum || "")
      this.$set(this.bankReceiptDetails, "accountBankName", data.baBankName || "")
    },
    getBankReceiptsDetails() {
      let id = this.bankReceiptId
      let currentTotal = 0
      getReceivableItem2(id).then((response) => {
        this.bankReceiptDetails = response.data
        if (this.bankReceiptDetails.attr === "") {
          this.bankReceiptDetails.attr = []
        }
        loadBankReceiptItemListByID({ receiptItemId: id }).then((res) => {
          this.bankReceiptDetails.receivableList = res.data
          this.bankReceiptDetails.receivableList.forEach((item) => {
            currentTotal += item.writeOffAmount
          })
          if (this.bankReceiptDetails.writeOffAmount && currentTotal > this.bankReceiptDetails.writeOffAmount) {
            this.$modal.msgError(this.$t("本次实收基准金额小于上次填写核销金额总额,请注意"))
          }
          // this.bankReceiptDetails.receivableList.forEach((item) => {
          //  未填写实收
          this.bankReceiptDetails.remainingWriteOffAmount = NP.minus(this.bankReceiptDetails.writeOffAmount, currentTotal)
          // 已填写核销金额
          this.bankReceiptDetails.currentWriteOffAmount = currentTotal
          // })
        })
      })
    },

    //上传
    handleUploadSuccess(res, file, fileList) {
      let arr = []
      setTimeout(() => {
        fileList.forEach((item) => {
          arr.push({
            name: item.name,
            url: item.response ? item.response.data : item.url
          })
        })
        this.bankReceiptDetails.attr = arr
      }, 300)
      this.loading.close()
    },
    handleBeforeUpload() {
      this.loading = this.$loading({
        lock: true,
        text: this.$t("上传中"),
        background: "rgba(0, 0, 0, 0.7)"
      })
    },
    handleUploadError() {
      this.$message({
        type: "error",
        message: this.$t("上传失败")
      })
      this.loading.close()
    },
    beforeRemove(file, fileList) {
      return this.$confirm(this.$t("确定移除") + "?").then((res) => {
        setTimeout(() => {
          this.bankReceiptDetails.attr = fileList.map((v) => ({
            name: v.name,
            url: v.response ? v.response.data : v.url
          }))
        }, 300)
      })
    }
  }
}
</script>
<style scoped>
.detailItem {
  display: flex;
}
.detailLeft {
  flex: 1;
  padding-right: 20px;
}
.detailBtn {
  margin-top: 20px;
}
::v-deep .warnColor {
  color: red;
}
</style>
