<template>
  <div class="app-container">
      <el-descriptions :column="4" >
        <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 v-if="reason" :label="$t('申请理由')">{{reason}}</el-descriptions-item>
      </el-descriptions>
    <div class="btn">
      <el-table ref="multipleTable" :data="detailed" border row-key="id">
              <!-- <el-table-column :label="$t('序号')" type="index" align="center" width="50"></el-table-column> -->
              <el-table-column :label="$t('收款账户')" align="center" prop="accountName" />
              <el-table-column :label="$t('实收金额')" align="center" prop="amount" />
              <el-table-column :label="$t('实收币种')" align="center" prop="marks">
                <template slot-scope="scope">
                  {{getCurrencyLabel(scope.row.currencyId)}}
                </template>
              </el-table-column>
              <el-table-column :label="$t('汇率')" align="center" prop="rate" />
              <el-table-column align="center" prop="writeOffAmount" >
                <template #header>
                  {{ $t('兑核销基准金额') }}（{{getCurrencyLabel(showCurrencyId)}}）
                </template>
              </el-table-column>
              <el-table-column :label="$t('实收日期')" align="center" prop="amountDate">
              </el-table-column>
              <el-table-column :label="$t('水单号')" align="center" prop="billNo" />
              <el-table-column :label="$t('水单附件')" align="center" prop="attr">
                <template slot-scope="scope" v-if="scope.row.attr">
                  <div v-for="(v, i) in scope.row.attr" :key="i"><el-link :href="v.url" type="primary" target="_blank">{{ v.name }}</el-link></div>
                </template>
              </el-table-column>
            </el-table>
    </div>
    <div class="btn">
      <el-button
        size="mini"
        type="primary"
        @click="$router.push('/financial/receiptDetail?id=' + receiptId)"
        >{{ $t('查看收款单')}}</el-button>
        <el-button
          size="mini"
          type="primary"
          @click="openAddDialog=true"
          >{{ $t('查看银行实收明细')}}</el-button>
    </div>
    <el-dialog v-if="openAddDialog" :visible.sync="openAddDialog" :title="this.$t('银行实收明细详情')" width="50%" append-to-body>
          <div style="padding: 0 24px">
            <el-form ref="addForm" :model="addForm" label-width="250px">
              <el-form-item :label="$t('收款单号')+':'">{{ form.receiptNo }}</el-form-item>
              <el-form-item :label="$t('剩余应收金额')+':'">
                <template >
                  <div v-if="surplusData.length==0">0</div>
                  <div v-else>
                    <div v-for="(amount, currency) in surplusData" :key="currency">
                       <span v-if="amount"> {{amount}}{{getCurrencyLabel(currency)}}</span>
                    </div>
                  </div>
                </template>

              </el-form-item>
              <el-form-item :label="$t('收款账户')+':'" prop="accountNo">
                <span>{{ addForm.accountNo }}</span>
              </el-form-item>
              <el-form-item :label="$t('实收日期')+':'" prop="amountDate">
                <span>{{ addForm.amountDate }}</span>
              </el-form-item>
              <div style="display: flex;">
                <el-form-item :label="$t('实收')+':'" prop="amount"><span>{{ addForm.amount }}</span></el-form-item>
                <el-form-item
                  label-width="0px"
                  prop="currencyId"
                >
                <el-select
                  v-model="addForm.currencyId"
                  :placeholder="$t('请选择')"
                  :disabled="true"
                  @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>
                  <!-- <dict-selector v-if="!isView" :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" v-model="addForm.currencyId" @change="val => currencyIdChange(val)"/> -->
                  <!-- <span v-else>{{ addForm.currencyId }}</span> -->
                  <!-- <dict-tag v-else :type="DICT_TYPE.BOX_SHIPPING_PRICE_UNIT" :value="addForm.currencyId" /> -->
                </el-form-item>
              </div>
              <el-form-item
                v-if="showCurrencyId != addForm.currencyId"
                prop="rate"
              >
                <template slot="label">
                <span :title="$t('实收币种与核销基准币种一样时，无需填写汇率，不一样需要填写汇率')">{{ $t('兑核销基准币种汇率') }}（{{getCurrencyLabel(showCurrencyId)}}）</span>
                </template>
                <span>{{ addForm.rate}}</span>
              </el-form-item>
              <el-form-item
                v-if="showCurrencyId != addForm.currencyId"
              >
                <template slot="label">
                  {{ $t('兑核销基准币种金额') }}（{{getCurrencyLabel(showCurrencyId)}}）:
                </template>
                <span>{{ addForm.writeOffAmount?parseFloat(addForm.writeOffAmount).toFixed(6):'' }}</span>
              </el-form-item>
              <el-form-item
                :label="$t('水单附件')+':'"
                prop="attr"
              >
                <div v-if="addForm.attr.length>0">
                  <div v-for="(v, i) in addForm.attr" :key="i"><el-link :href="v.url" type="primary" target="_blank">{{ v.name }}</el-link></div>
                </div>
                <div v-else>{{$t('无')}}</div>
              </el-form-item>
              <el-form-item :label="$t('水单号')+':'" prop="billNo">
                <span>{{ addForm.billNo }}</span>
              </el-form-item>
            </el-form>
          </div>
        </el-dialog>
  </div>
</template>

<script>

import { getCustomer } from '@/api/ecw/customer'
import {
  getReceiptInfoByIds,
  getReceivableItem,
  getInvoicingItem,
  getReceiptAccountList,
  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: {},
      currencyList:[],
      list:[],
      detailed: [],
      detatilData:[],
      showCurrencyId:0,
      surplusData:[],
      openAddDialog:false,
      collectionAmount: [],
      addForm:{},
      receiptId:0,
      receiptItemId:0,
      reason:'',
      receiptAccountList:[]
    }
  },
  watch:{
      id(){
          this.getCurrencyData()
      },
      currencyList(){
        this.getData()
      },
      form(){
        this.getList()
        this.getListData()
      },
  },
  created() {
      if(this.id){
        this.getCurrencyData()
      }
  },
  methods: {
    getData(){
      getReceiptApprove(this.id).then(res => {
          if(res.data.receiptId){
            this.receiptId = res.data.receiptId
            this.receiptItemId = res.data.receiptItemId
            this.reason = res.data.reason
             this.getReceiptInfo()
          }
      })

    },
    // 获取汇率
   getCurrencyData(){
     getCurrencyPage(this.params).then(res => {this.currencyList = res.data.list})
   },
   getList() {
     getReceivableItem({ id: this.receiptId }).then(res => {
       this.detatilData = 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 })) : []
       }))
       this.addForm = this.detatilData.find(v=>v.id==this.receiptItemId)
       this.detailed = []
       this.detailed.push(this.addForm)
       this.getCollectionData()
     })
     
   },
   getReceiptInfo(){
       getReceiptInfoByIds({ id: this.receiptId }).then(res => {
        this.form = res.data
        getCustomer(this.form.customerId).then(res => {
          this.form.customerName = res?.data?.name
        })
      })
    },
    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 ''
    },
    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.$set(this,'collectionAmount',amountList)
        this.handleAddReceiptItem()
      })
      },
    handleAddReceiptItem() {
      // 已收
      let recepted = []
      this.detatilData.forEach(item => {
          if(!recepted[item.currencyId]){
            recepted[item.currencyId] = item.amount
          }else recepted[item.currencyId] = NP.plus(recepted[item.currencyId], item.amount)
      })
      // 应收
      let collom = []
      // 从期望收费金额中提取应收币种和金额
         this.collectionAmount.forEach(item => {
           collom[item.currencyId] = item.amount
         })
      console.log(recepted)
        recepted.forEach((amount,currency)=>{
          if(amount){
            if(collom[currency]){
              if((collom[currency]-amount)!=0) this.surplusData[currency] = +parseFloat((collom[currency]-amount).toPrecision(12))
            }else{
              this.surplusData[currency] = -amount
            }
          }

        })
         console.log(collom)
        collom.forEach((amount,currency)=>{
          if(amount){
            if(!this.surplusData[currency]){
              if(recepted[currency]){
               if((amount-recepted[currency])!=0)  this.surplusData[currency] = +parseFloat((amount-recepted[currency]).toPrecision(12))
              }else{
              this.surplusData[currency] = amount
            }
            }
          }
        })
        console.log(this.surplusData)
    },
  }
}
</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>
