<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="card-title">{{ $t('银行实收明细详情') }}</div>
          <el-form ref="addForm" :data="addForm" label-width="250px">
            <el-form-item :label="$t('收款单号')">{{ form.receiptNo }}</el-form-item>
            <el-form-item :label="$t('剩余应收金额')">
              <template v-if="surplusData.length==0"> 0</template>
              <div v-if="surplusData.length>0">
                <div v-for="(amount, currency) in surplusData" :key="currency">
                   <span v-if="amount"> {{amount}}{{getCurrencyLabel(currency)}}</span>
                </div>
              </div>
            </el-form-item>
            <el-form-item :label="$t('收款账户')" prop="accountNo">
              <span>{{ addForm.accountNo}}{{'('+addForm.accountName+')' }}</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">
                <span>({{getCurrencyLabel(addForm.currencyId)}})</span>
              </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(2):'' }}</span>
            </el-form-item>
            <el-form-item :label="$t('水单附件')" prop="attr">
              <div>
                <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>
            </el-form-item>
            <el-form-item :label="$t('水单号')" prop="billNo">
              <span>{{ addForm.billNo }}</span>
            </el-form-item>
          </el-form>
    </el-card>
    <div slot="header" class="bpm-title">{{ $t('审核流程') }}</div>
     <work-flow  xmlkey="merge_order" v-model="selectedUsers"></work-flow>

     <div slot="footer" style="margin: 20px 0">
       <el-button type="primary" @click="submitForm(0)">{{$t('提交审核')}}</el-button>
       <el-button type="primary"  @click="$store.dispatch('tagsView/delCurrentView')">{{ $t('关闭') }}</el-button>
     </div>
  </div>
</template>

<script>
  import { getReceivableItem ,getInvoicingItem,getReceiptAccountList,getReceiptInfoByIds,financeReceiptItemWriteOff} from "@/api/ecw/financial";
  import { getCurrencyPage } from "@/api/ecw/currency";
  import WorkFlow from '@/components/WorkFlow/'
  import NP from 'number-precision'

  export default {
    components: {
      WorkFlow
    },
    data() {
      return {
        addForm:{},
        id:0,
        detailed:[],
         currencyList: [],
        surplusData:[],
        receiptAccountList:[],
        selectedUsers:[],
        list:[],
        params: {
          page: 1,
          rows: 20,
        },
        bankId:0,
        form:{}
      }
    },
    async created() {
        if (this.$route.query.id) {
          this.id = this.$route.query.id;
        }
        if (this.$route.query.bankId) {
          this.bankId = this.$route.query.bankId;
        }
        await getInvoicingItem({ id: this.id }).then(res => {
          this.list = [...res.data]
        })
        await getReceiptAccountList({ id: this.id }).then(res => {
            this.receiptAccountList = [...res.data]
          })
        await getCurrencyPage(this.params).then(res => this.currencyList = res.data.list)
        await this.getList()
        await getReceiptInfoByIds({ id: this.id }).then(res => {
          this.form = res.data
          })
    },
    methods:{
      getList() {
        getReceivableItem({ id: this.id }).then(res => {
          this.detailed = res.data.map(v => ({
            ...v,
            amountDate: this.parseTime(v.amountDate, '{y}-{m}-{d}'),
            rate:parseFloat(v.rate).toFixed(2),
            attr: v.attr ? v.attr.split(',').map(t => ({ name: t.slice(t.lastIndexOf('/') + 1), url: t })) : []
          }))
          console.log(this.detailed)
          this.addForm = this.detailed.find((itt) => itt.id == this.bankId);
          console.log(this.addForm)
          this.handleAddReceiptItem()
        })
      },
      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 ''
      },
      submitForm(){
        this.$modal
          .confirm(this.$t('您确认要提交审核吗'+'?'))
          .then(() => {
            financeReceiptItemWriteOff({receiptId:this.id,receiptNo:this.form.receiptNo,receiptItemId:this.bankId}).then(res=>{
              this.$message.success(this.$t("提交成功"));
              this.$store.dispatch('tagsView/delCurrentView')
            });
          })
          .catch(() => {});
      },
      handleAddReceiptItem() {
        this.surplusData = []

        // 已收
        let recepted = []
        this.detailed.forEach(item => {

            if(!recepted[item.currencyId]){
              recepted[item.currencyId] = item.amount
            }else recepted[item.currencyId] = NP.plus(recepted[item.currencyId], item.amount)
        })
        console.log('rece',recepted)

        // 应收
        let collom = []
        // 从期望收费金额中提取应收币种和金额

       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)
          }
          var dollarList = this.receiptAccountList.filter(v => v.collectionCurrencyId == item.id)
          if(dollarList.length>0){
            var dollar = dollarList.reduce((total, currentValue) => NP.plus(total, currentValue.collectionAmount), 0).toFixed(2)
            if(dollar){
              collom[item.id] = dollar
            }else{
              collom.push(0)
            }
          }
        })
        console.log('collom',collom)
          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
              }
            }

          })
          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
              }

              }
            }
          })
      },
    },
    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
      },
    }
  }
</script>

<style>
  .card {
    margin-top: 20px;
  }
  .dialog-footer {
    text-align: left;
  }
  .card-title {
    font-size: 18px;
    font-weight: bold;
  }
  .bpm-title{
    font-size: 20px;
    font-weight: bold;
    color:#666;
    margin:20px 0;
  }
</style>