<template>
  <div>
    <div class="app-container">
      <el-descriptions :column="5" >
        <el-descriptions-item :label="$t('收款单编号')">{{ form.receiptNo }}</el-descriptions-item>
        <el-descriptions-item :label="$t('客户')">{{ form.customerName }}</el-descriptions-item>
        <el-descriptions-item :label="$t('创建时间')">
          <template >
            <span>{{ parseTime(form.createTime, '{y}-{m}-{d}') }}</span>
          </template></el-descriptions-item>
        <el-descriptions-item :label="$t('业务员')">{{ form.salesmanName }}</el-descriptions-item>
        <el-descriptions-item :label="$t('期望收款金额')">
          <template>
              <div v-for="itemAmount in collectionAmount" :key="itemAmount.currencyNameZh">{{$i18n.locale=='zh_CN'?itemAmount.currencyNameZh:itemAmount.currencyNameEn}}: {{ itemAmount.amount}}</div>
          </template>
        </el-descriptions-item>
        <el-descriptions-item v-if="reason" :label="$t('申请理由')">{{reason}}</el-descriptions-item>
      </el-descriptions>

      </div>
      <el-descriptions :column="3" border>
        <el-descriptions-item >
          <template slot="label">
            {{ $t('实收已核销总金额') }}
            <span :title="$t('所有银行收款明细中状态为已核销的实收金额，币种根据实收币种分类统计')"><i class="el-icon-question"></i></span>
          </template>
          <template v-if="!Object.keys(writeOffTotal).length">
            0
          </template>
          <div v-else>
            <div v-for="(amount, currency) in writeOffTotal" :key="currency">
              {{amount}}{{getCurrencyLabel(currency)}}
            </div>
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            {{ $t('核销基准币种已核销总金额') }}（{{getCurrencyLabel(showCurrencyId)}}）
            <span :title="$t('为了方便统计收款单核销比例，将所有银行收款明细中状态为已核销的实收金额，转换为核销基准币种的金额累加')"><i class="el-icon-question"></i></span>
          </template>
          {{ writeOffAmount}}

        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            {{ $t('总核销比例') }}（{{getCurrencyLabel(showCurrencyId)}}）
            <span :title="$t('总核销比例=核销基准币种已核销总金额/核销基准币种应收总金额')"><i class="el-icon-question"></i></span>

          </template>
          {{ WriteOffProportion }}%
        </el-descriptions-item>
      </el-descriptions>
      <div style="margin: 20px 0;font-size:16px" v-if="form.financeRemark">{{$t('备注')}}:{{form.financeRemark}}</div>
    <div class="btn">
      <el-button
        size="mini"
        type="primary"
        @click="$router.push('/financial/receiptDetail?id=' + receiptId)"
        >{{ $t('查看收款单')}}</el-button>
    </div>
  </div>
</template>

<script>

import { getCustomer } from '@/api/ecw/customer'
import {
  getReceiptInfoByIds,
  getInvoicingItem,
  getReceiptAccountList,
  getReceivableItem,
  getReceiptApprove
} from "@/api/ecw/financial";
import { getCurrencyPage } from "@/api/ecw/currency";
import NP from 'number-precision'


export default {
  props:{
      id: [String, Number]
  },
  data() {
    return {
      form: {},
      collectionAmount: [],
      currencyList:[],
      list:[],
      writeOffAmounts:0,
      detailed:[],
      showCurrencyId:0,
      receiptId:0,
      reason:''
    }
  },
  watch:{
      id(){
          this.getCurrencyData()
      },
      currencyList(){
        this.getData()
      },
      form(){
        this.getListData()
      },
      list(){
        this.getList()
        this.getCollectionData()
      }
  },
  created() {
      if(this.id){
        this.getCurrencyData()
      }
  },
  computed: {
    // 已核销总金额
    writeOffTotal(){
      let total = {}
      this.detailed.forEach(item => {
        if(item.status){
          if(!total[item.currencyId]){
            total[item.currencyId] = item.amount
          }else total[item.currencyId] = NP.plus(total[item.currencyId], item.amount)
        }
      })
      return total
    },
    // 已核销总金额
    writeOffAmount(){
      let total = 0
      this.detailed.forEach(item => {
        if(item.status){
          total = NP.plus(total, item.writeOffAmount)
        }
      })
      return total.toFixed(2)
    },
    WriteOffProportion(){
        let total = 0
        if(!this.writeOffAmounts) return 0
        let amountTotal = this.writeOffAmounts
        this.detailed.forEach(item => {
          if(item.status){
            total = NP.plus(total, item.writeOffAmount)
          }
        })
      let portion = NP.divide(total,amountTotal)
      return (portion*100).toFixed(2)
    }
  },
  methods: {
    getData(){
      getReceiptApprove(this.id).then(res => {
          if(res.data.receiptId){
            this.receiptId = res.data.receiptId
            this.reason = res.data.reason
             this.getReceiptInfo()
          }
      })

    },
    getList() {
      getReceivableItem({ id: this.receiptId }).then(res => {
        this.detailed = res.data.map(v => ({
          ...v,
          amountDate: this.parseTime(v.amountDate, '{y}-{m}-{d}'),
          accountNo: +v.accountNo,
          rate:parseFloat(v.rate).toFixed(6),
          attr: v.attr ? v.attr.split(',').map(t => ({ name: t.slice(t.lastIndexOf('/') + 1), url: t })) : []
        }))
      })
    },
    // 获取汇率
   getCurrencyData(){
     getCurrencyPage(this.params).then(res => {this.currencyList = res.data.list})
   },
   getReceiptInfo(){
       getReceiptInfoByIds({ id: this.receiptId }).then(res => {
        this.form = res.data
        getCustomer(this.form.customerId).then(res => {
          this.form.customerName = res?.data?.name
        })
      })
    },
    getListData(){
      getInvoicingItem({ id: this.receiptId }).then(res => {
        this.list = [...res.data]
        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
            })
          }
          this.showCurrencyId = 1
          if (groupList.length === 1) this.showCurrencyId = groupList[0].currencyId
      })
    },
    getCollectionData(){
      getReceiptAccountList({ id: this.receiptId }).then(res => {
        var n
        // 收款总计
        var amountList =[]
        this.currencyList.forEach((item,index)=>{
          var nairaListByList = this.list.filter(v => v.currencyId === item.id)
          if(nairaListByList.length>0){
            var discountNaira = nairaListByList.reduce((total, currentValue) => NP.plus(total, currentValue.discountTotal || 0), 0)
            n = res.data.find(v => v.currencyId == item.id)
            n && (n.discountTotal = discountNaira)
          }
          var dollarList = res.data.filter(v => v.collectionCurrencyId == item.id)

          if(dollarList.length>0){
            var dollar = dollarList.reduce((total, currentValue) => NP.plus(total, currentValue.collectionAmount), 0).toFixed(2)
             amountList.push({currencyId:item.id,currencyNameEn:item.titleEn,currencyNameZh:item.titleZh,amount:dollar})
          }

        })
        this.writeOffAmounts = res.data.reduce((total, currentValue) => NP.plus(total, currentValue.writeOffAmount || 0), 0),
        console.log(this.writeOffAmounts)
        this.$set(this,'collectionAmount',amountList)
      })
      },
      getCurrencyLabel(id){
        var 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 ''
      },
    }
}
</script>

<style scoped lang="scss">
  .btn{
    margin-top: 20px;
  }
  .app-container {
    ::v-deep .el-descriptions-item__label {
      font-size:16px;
      font-weight:600;
    }
    ::v-deep .el-descriptions-item__content {
      font-size:16px;
      font-weight:600;
    }
  }
</style>
