<template>
    <el-tabs type="border-card">
        <!-- 资产信息-->
        <el-tab-pane label="资产信息">
            <!-- <div class="app-container"> -->
            <el-form ref="forms" :model="forms" :inline="true" style="margin-top: 20px" label-width="auto" >
                <el-row class="zap-form" style="padding-bottom: 0;">
                    <el-col :span="12">
                        <el-form-item label="选择融信:" prop="zfrFinanceId" size="large">
                            <el-select v-model="forms.zfrFinanceId" clearable @clear="clearBoth">
                                <el-option v-for="(item,index) in financeInfList" :key="index" :label="item.zfiNumber" :value="item.zfiId" @click.native="amount(item)"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="融资收款账户:" prop="zfrCollectionAccount" size="large" label-width="101px">
                            <el-input v-model="forms.zfrCollectionAccount" clearable placeholder="请输入融资账户" maxlength="25" :readonly="readonly" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row class="zap-form" style="padding-bottom: 0;">
                    <el-col :span="12">
                        <el-form-item label="融信金额:" prop="zfiAmount" size="large">
                            <el-input v-model="forms.zfiAmount" clearable placeholder="请输入融信金额" maxlength="25" readonly />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="申请融资方:" prop="companyName" size="large">
                            <el-input v-model="forms.companyName" clearable placeholder="请输入申请融资方" maxlength="25" readonly />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row class="zap-form" style="padding-bottom: 0;">
                    <el-col :span="12">
                        <el-form-item label="融资金额:" prop="zfrAmount" size="large">
                            <el-input v-model="forms.zfrAmount" clearable placeholder="请输入融资金额" maxlength="25" readonly />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="融资利率:" prop="zfrRate" size="large">
                            <el-input v-model="forms.zfrRate" clearable placeholder="请输入融资利率" maxlength="25" readonly />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row class="zap-form" style="padding-bottom: 0;">
                    <el-col :span="12">
                        <el-form-item label="承诺还款日期:" prop="zfrRepaymentDate" size="large"  label-width="101px">
                            <el-input v-model="forms.zfrRepaymentDate" clearable placeholder="请输入承诺还款日期" maxlength="25" readonly />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="服务费率:" prop="zfpcrChargeRate" size="large">
                            <el-input v-model="forms.zfpcrChargeRate" clearable placeholder="请输入服务费率" maxlength="25" readonly />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row class="zap-form" style="padding-bottom: 0;">
                    <el-col :span="12">
                        <el-form-item label="融资期限:" prop="termIng" size="large" label-width="101px">
                            <el-input v-model="forms.termIng" clearable placeholder="请输入融资期限" maxlength="25" readonly />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <el-form ref="form" :model="form" :rules="rules" :inline="true" style="margin-top: 20px" label-width="auto" >
                <el-divider content-position="left">签收</el-divider>
                 <el-form-item label="融信利率:"> 
                            <span>{{this.zfiRate}}</span>%
                 </el-form-item>
                <table class="gridtable" style="width:80%;text-align:center" align="center">
                    <tr>
                        <td rowspan="4">开立方</td>
                        <td>全称</td>
                        <td>{{openName}}</td>
                        <td rowspan="4">接收方</td>
                        <td>全称</td>
                        <td>{{receiveName}}</td>
                    </tr>
                    <tr>
                        <td>社会统一码</td>
                        <td>{{openCode}}</td>
                        <td>社会统一码</td>
                        <td>{{receiverCode}}</td>
                    </tr>    
                    <tr>
                        <td>开户银行</td>
                        <td>{{openBank}}</td>
                        <td>开户银行</td>
                        <td>{{receiverBank}}</td>
                    </tr>    
                    <tr>
                        <td>账号</td>
                        <td>{{openAccount}}</td>
                        <td>账号</td>
                        <td>{{receiverAccount}}</td>
                    </tr> 
                    <tr>
                        <td colspan="2">粮信金额</td>
                        <td colspan="4">人民币(大写):{{issuedAmount}}<br>人民币(小写)￥{{form.zfiAmount}}</td>
                    </tr>
                    <tr>
                        <td colspan="2">起止日期</td>
                        <td colspan="4">{{stopDate}}</td>
                    </tr>           
                </table>    
                <el-form-item  style="margin-left: 100px">
                    <el-button size="mini" type="success" :disabled="isClick" @click="openTicket">选择</el-button>
                    <el-button size="mini" type="primary" :disabled="isClick" @click="addPay">新增应收账款</el-button>
                    <el-button size="mini" @click="deleteTicekt" :disabled="isClick" >清空全部</el-button>
                    <el-form-item label="合计金额:"> 
                            <span>{{checkTotalAmt}}</span>
                    </el-form-item>
                    <el-form-item label="金额大写:"> 
                            <span>{{checkTotalBigAmt}}</span>
                    </el-form-item>
                    
                    <el-table :data="ticketList" style="width: 1100px">
                        <el-table-column label="账款名称"  align="center"  prop="zbiName" show-overflow-tooltip />
                        <el-table-column label="应收企业"  align="center"  prop="receiveName"/>
                        <el-table-column label="应收企业"  align="center"  prop="payName"    />
                        <el-table-column label="预计还款期"  align="center"  prop="zbiPayDate" show-overflow-tooltip />
                        <el-table-column label="金额"  align="center"  prop="zbiAmount" />
                        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250">
                            <template slot-scope="scope">
                            <el-button
                                size="mini"
                                type="text"
                                icon="el-icon-delete"
                                :disabled="isClick"
                                @click="handleDelete(scope.$index, ticketList)"
                            >删除</el-button>
                            <el-button
                                size="mini"
                                type="text"
                                icon="el-icon-view"
                                @click="handleDetail(scope.$index, ticketList)"
                            >详情</el-button>
                            <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.$index, ticketList)">修改</el-button> -->
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="签发金额" prop="zfiAmount"> 
                            <el-input v-model="form.zfiAmount" style="width: 200px"  disabled @input="getBigSmall"/>
                        </el-form-item>
                    </el-col> 
                
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="金额大写" prop="issuedAmount"> 
                            {{issuedAmount}}
                        </el-form-item>
                    </el-col>  
                </el-row>      
                <p>请知悉，资产信息仅能接受指定的销售方与购买方的往来账款(含账款基本信息、贸易合同与贸易发票等)；如须使用系统尚未维护的往来账款，请点击新增应付账款
                </p>
            </el-form>
            <!-- 发票附件 -->
            <!-- <el-divider content-position="left">发票附件</el-divider>
            <el-table :data="invoiceFileList"  style="width: 100%">
                    <el-table-column label="文件名称" align="center" prop="pfiFileName" show-overflow-tooltip />
                    <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width='300' fixed="right" >
                        <template slot-scope="scope">
                            <el-button
                                size="mini"
                                type="text"
                                icon="el-icon-view"
                                @click="handleDownload(scope.row)"
                            >下载</el-button>
                            <el-button
                                size="mini"
                                type="text"
                                icon="el-icon-view"
                                @click="handlePreview(scope.row)"
                            >预览</el-button>
                        </template>
                    </el-table-column>
            </el-table> -->
            <!-- 合同附件 -->
            <!-- <el-divider content-position="left">合同附件</el-divider>
            <el-table :data="contractFileList"  style="width: 100%">
                <el-table-column label="文件名称" align="center" prop="pfiFileName" show-overflow-tooltip />
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width='300' fixed="right" >
                        <template slot-scope="scope">
                            <el-button
                                size="mini"
                                type="text"
                                icon="el-icon-view"
                                @click="handleDownload(scope.row)"
                            >下载</el-button>
                            <el-button
                                size="mini"
                                type="text"
                                icon="el-icon-view"
                                @click="handlePreview(scope.row)"
                            >预览</el-button>
                        </template>
                    </el-table-column>
            </el-table> -->
            <!-- 其他附件 -->
            <!-- <el-divider content-position="left">其他附件</el-divider>
            <el-table :data="otherFileList"  style="width: 100%">
                    <el-table-column label="文件名称" align="center" prop="pfiFileName" show-overflow-tooltip />
                    <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width='300' fixed="right" >
                        <template slot-scope="scope">
                            <el-button
                                size="mini"
                                type="text"
                                icon="el-icon-view"
                                @click="handleDownload(scope.row)"
                            >下载</el-button>
                            <el-button
                                size="mini"
                                type="text"
                                icon="el-icon-view"
                                @click="handlePreview(scope.row)"
                            >预览</el-button>
                        </template>
                    </el-table-column>
            </el-table> -->
            <div class="footer" style="float: right;
                margin-bottom:2px;">
                <el-button type="info" @click="submitForm('01')">拒绝</el-button>
                <el-button type="primary" @click="sign()" v-if="!isHas">签收</el-button>
                <el-button type="primary" @click="submitForm('00')" v-if="isHas">内部审批</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
            <!-- 应收账款信息 -->
            <el-dialog :title="payTitle" :visible.sync="open" width="1120px" append-to-body>
            <el-form :model="queryParamsPay"  ref="formQuery"  :inline="true"  label-width="68px"  style="margin-bottom: -21px">
                <el-form-item label="账款名称" prop="zbiName">
                    <el-input
                        v-model="queryParamsPay.zbiName"
                        placeholder="请输入账款名称"
                        clearable
                        size="small"
                        maxlength="11"
                        @keyup.enter.native="handleQuerys"/>
                </el-form-item>
                <el-form-item>
                    <el-button
                        type="cyan"
                        icon="el-icon-search"
                        size="mini"
                        @click="handleQuerys"
                        >搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetQuerys"
                        >重置</el-button>
                </el-form-item>
            </el-form>
            <el-table :data="payList"
                ref="tablePay"
                class="single-select-table"
                @selection-change="handleSelectionChange" 
                :row-key="rowkey">
                <el-table-column
                type="selection"
                :reserve-selection="true"
                width="50"
                align="center"/>
                <el-table-column label="序号" type="index" width="50" align="center">
                <template slot-scope="scope">
                    <span>{{ (queryParamsPay.pageNum - 1) * queryParamsPay.pageSize + scope.$index + 1}}</span>
                </template>
                </el-table-column>
                <el-table-column label="账款名称"  align="center"  prop="zbiName" show-overflow-tooltip />
                <el-table-column label="应收企业"  align="center"  prop="receiveName"/>
                <el-table-column label="应收企业"  align="center"  prop="payName"    />
                <el-table-column label="预计还款期"  align="center"  prop="zbiPayDate" show-overflow-tooltip />
                <el-table-column label="金额"  align="center"  prop="zbiAmount" />
            </el-table>
            <pagination
                v-show="total > 0"
                :total="total"
                :page.sync="queryParamsPay.pageNum"
                :limit.sync="queryParamsPay.pageSize"
                @pagination="getAccountsCollection" />
            <span slot="footer" class="dialog-footer">
                <el-button size="mini" @click="cancelTicket">取消</el-button>
                <el-button size="mini" type="primary" @click="closeTicket">确认</el-button>
            </span>
            </el-dialog>
            
            <!-- 新增往来账款 -->
            <el-dialog title="新增往来账款" :visible.sync="openAddBill" width="1120px" append-to-body>
                <add-bill :companyId="form.zfiCoreId" companyType="01" :payDate="payDate" @addClick="emitAddClick" v-if="openAddBill"></add-bill>
            </el-dialog>
            <el-dialog title="详情" :visible.sync="openDetailBill" width="1120px" append-to-body>
                <detail-bill :zbiId="this.zbiId"   v-if="openDetailBill"></detail-bill>
            </el-dialog>
            <!-- 修改往来账款 -->
            <el-dialog title="修改往来账款" :visible.sync="openEditBill" width="1120px" append-to-body>
                <edit-bill :zbiId="this.zbiId" @editClick="emitEditClick" v-if="openEditBill"></edit-bill>
            </el-dialog>
            <!--预览-->
            <el-dialog  :visible.sync="openFile" width="1000px" append-to-body>
                <img :src="wordUrl" v-if="show" width='450px' height='500px'/>
                <iframe :src="wordUrl" width='800px' height='600px' frameborder='1' v-if="heid"/>
            </el-dialog>
            <el-dialog
            :visible.sync="pdfShowDialog"
            width="70%"
            height = "60%"
            append-to-body>
                <pdf-show :pdfFileList="pdfFileList" :zfiId="this.form.zfiId" :parent="parent">
                </pdf-show>
            </el-dialog>
            <!--去融资-->
            <el-dialog  :visible.sync="goShow" width="300px"  append-to-body :before-close = "cancelGo" center>
                    <!-- <p>恭喜您成功签收一笔融信</p> -->
                    <el-form ref="financeSignForm" :model="financeSignForm" label-width="auto" :inline="true">
                        <el-row>
                            <el-form-item label="融信编号：">{{financeSignForm.zfiNumber}}</el-form-item>
                            <el-form-item label="融信金额：">{{handleInput(financeSignForm.zfiAmount)}}</el-form-item>
                            <el-form-item label="大写：">{{smallToBig(financeSignForm.zfiAmount)}}</el-form-item>
                        </el-row>
                        <el-row>
                            <el-form-item label="融信利率：">{{financeSignForm.zfiRate}}</el-form-item>
                            <el-form-item label="最长融信期限：">{{financeSignForm.intervalTime + "天"}}</el-form-item>
                            <el-form-item label="融信有效期：">{{financeSignForm.validity}}</el-form-item>
                        </el-row>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button type="primary" @click="goFinance">去融资</el-button>
                        <el-button @click="cancelGo">取 消</el-button>
                    </div>    
            </el-dialog>
        </el-tab-pane>
        <el-tab-pane label="签署合同">
            <el-table :data="creditSealList"  style="width: 100%">
                <el-table-column label="文件名称" align="center" prop="pfiFileName" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <img    style="width:30px;height:30px;"
                            src="../../../assets/images/pdf.png"  
                        />
                        <span>{{scope.row.pfiFileName}}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width='300' fixed="right" >
                    <template slot-scope="scope">
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-view"
                            @click="handleDownload(scope.row)"
                        >下载</el-button>
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-view"
                            @click="handlePreview(scope.row)"
                        >预览</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-tab-pane>
    </el-tabs>
  <!-- </div> -->
</template>
<script>
import {getCreditDetail,getAvailableBalance,getAccountsCollection,getFile,getFinanceSign} from "@/api/service/credit/credit";
import {signFor,getCreditSealFile,getContractFile} from "@/api/service/credit/creditHandle";
import {accAdd} from "@/utils/calculation";
import {getToken} from "@/utils/auth";
import AddBill from "@/views/service/bill/addBill";
import EditBill from "@/views/service/bill/editBill";
import {isOpenApproval} from "@/api/service/credit/approvalRelatedCredit";
import pdfShow from "./pdfShow";
import DetailBill from "@/views/service/credit/billDetail";
import {contractSigning} from "@/api/service/credit/message";
import { listFinanceInf } from "@/api/common/financeInf";
import { amtformat } from "@/utils/amtCommon";
import Cookies from 'js-cookie';
export default {
    name: "addCredit",
    components: {AddBill,DetailBill,pdfShow,EditBill},
    data() {
        return {
            //往来账款id
            zbiId: '',
            // 总条数
            total: 0,
            // 表单参数read
            form: {

            },
            forms:{},
            // 表单校验
            rules: {
               
            },
            financeSignForm:{},
            // 是否显示弹出层
            open: false,
            openAddBill: false,
            openDetailBill: false,
            openEditBill: false,
           //选择的应收账款
           payList:[],
           //现有的应收账款
           ticketList:[],
           //签发金额大写
           issuedAmount:"零元整",
           //合计选中的应收账款的金额
           checkTotalAmt:"0.00",
           //合计选中的应收账款的大写金额
           checkTotalBigAmt:"零元整",
           //接收方
          supplierList:[],
          supplierForm:{},
          queryParamsPay: {
                pageNum: 1,
                pageSize: 10,
                zbiName:null
            },
          //授信额度
          creditLineList:[],
          //可用额度
          availableAmt:"0.00",
          //有效期
          validityDate:"",
          //有效期类型
          zfpcrDateType:"" ,
          //产品是否可拆分
          zfpSplit:"",
          //融资放款方式
          zfpcrLoanType:"",
          //产品编号
          zfpId:"",
          //标题
          payTitle:"",
          //利率
          zfiRate:"",
          //授信额度
          creditParams: {
                zfpcrId:null,
                type:'1'
            },
          //合同附件
          contractFileList:[],
          //发票附件
          invoiceFileList:[],
          //其他文件
          otherFileList:[] ,
          //盖章文件
          creditSealList:[],
          //开立方编号
          zfiCoreId:"",
          //接收方
          zfiSupplierId:"" ,
          //融信类型
          zfiCreateType:"",
          //控制按钮是否可点击
          isClick:true,
          openFile:false,
          wordUrl: "",
          show:false,
          heid:false,
          chooseTicket:[],
          payDate:null,
          //开立方
          openName:"",
          //开立社会码
          openCode:"",
          //开立银行
          openBank:"",
          //开立账户
          openAccount:"",
          //接收方
          receiveName:"",
          //接收方社会统一码
          receiverCode:"",
          //接收方银行
          receiverBank:"",
          //接收方账户
          receiverAccount:"",
          //起止日期
          stopDate:"",
          //控制签收，内部审批按钮展示
          isHas:true,
          //融资企业审批状态
          zfiSupplierStatus:"",
          //融信编号
          zfiId:"",
          pdfFileList : [],
          pdfShowDialog : false,
          parent : this,
          //显示去融资框
          goShow:false
          
        };
    },
    watch:{
        'form.zfiCoreQuotaId':'change'
    },
    created() {
         const zfiId = this.$route.params && this.$route.params.zfiId;
         this.zfiId = zfiId;
         getCreditDetail(zfiId).then((response) => {
             if(response.data){
                 //签发金额
                this.form= response.data.financeInf;
                //签发金额大写
                this.issuedAmount = this.smallToBig(this.form.zfiAmount);
                //开立方编号
                this.zfiCoreId = response.data.financeInf.zfiCoreId;
                //接收方
                this.zfiSupplierId = response.data.financeInf.zfiSupplierId;
                //类型
                this.zfiCreateType = response.data.financeInf.zfiCreateType;
                //融资方审批状态
                this.zfiSupplierStatus = response.data.financeInf.zfiSupplierStatus;
                //核心
                if( this.zfiCreateType == "1"){
                    this.isClick = false;
                }else{
                    this.isClick = true;
                }
                //给表格赋值
               this.openName = response.data.openName;
               this.openCode = response.data.openCode;
               this.openBank = response.data.openBank;
               this.openAccount = response.data.openAccount;
               this.receiveName = response.data.receiveName;
               this.receiverCode = response.data.receiverCode;
               this.receiverBank = response.data.receiverBank;
               this.receiverAccount = response.data.receiverAccount;
               this.stopDate = response.data.stopDate;
               this.zfiRate = response.data.financeInf.zfiRate;
               
             }
             if(response.data.payList){
                 this.ticketList = response.data.payList.records;
                 this.getReTotal(this.ticketList);
                 //附件
                 this.getFile(this.ticketList);
             }
             //查询有无签收内部审批
             this.isOpenApproval();
             //盖章合同
             this.getCreditSealFile();
        });
        this.getFinanceInf(zfiId);
        this.getUserProfile();
      
    },
    methods: {
        /** 查询融信编号 */
        getFinanceInf(zfrFinanceId) {
            this.loading = true;
            listFinanceInf(zfrFinanceId).then(response => {
                debugger;
                if (response.data) {
                this.financeInfList = response.data;
                for (let item of this.financeInfList) {
                    if (item.zfiId == zfrFinanceId) {
                    this.amount(item);
                    }
                }
                this.loading = false;
                }
            });
        },
        getUserProfile(){
            getUserProfile().then(response => {
                debugger
                if(response.company){
                    this.$set(this.forms, "companyName", response.company.scyName);
                }
            });
        },
        /* 融信编号赋值融资金额 */
    amount(item) {
      debugger;
      this.$set(this.forms, "zfiAmount", item.zfiAmount);
      this.$set(this.forms, "zfrAmount", item.zfiAmount);
      this.$set(this.forms, "zfrRepaymentDate", item.zfiExpireDate);
      this.$set(this.forms, "zfrRate", item.zfpcrRate);
      this.$set(this.forms, "zfpcrLoanType", item.zfpcrLoanType);
      this.$set(this.forms, "zfiProductId", item.zfiProductId);
      this.$set(this.forms, "zfpcrChargeRate", item.zfpcrChargeRate);
      this.$set(this.forms, "termIng", item.termIng);
    },
        // 取消按钮
        cancel() {
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.go(-1);
        },
         /* 多选框跨页 */
        rowkeyCustomer(row) {
            return row.cciId;
        },
        //获取附件信息
        getFile(datas){
            var queryParamsFile = {};
            queryParamsFile.ticketList = datas;
            getFile(queryParamsFile).then((response) => {
                if(response.data){
                    //获取发票文件
                     this.invoiceFileList = response.data.invoiceFileList;
                    //获取合同文件
                     this.contractFileList = response.data.contractFileList;
                    //获取其他文件
                    this.otherFileList = response.data.otherFileList;
                }
            });
        },
        //获取盖章文件
        getCreditSealFile(){
            getCreditSealFile(this.form).then((response) => {
                if(response.data.list){
                    this.creditSealList = response.data.list;
                }
            });
        },
        //文件下载
        handleDownload(row){
            const pfiUrl = row.pfiUrl;
            if(pfiUrl != null && pfiUrl != ''){
            window.open(pfiUrl +"/"+ getToken());
            }else{
                this.$message({
                message: '该附件不存在！',
                type: 'warning'
                });
                return;
            }
        },
        resetQuerys() {
            this.resetForm("formQuery");
            this.handleQuerys();
        },
        handleQuerys() {
            this.queryParamsPay.pageNum = 1;
            this.getAccountsCollection();
        },
        //打开应收账款选择列表
        openTicket() {
            //清空搜索条件
            this.queryParamsPay.zbiName = "";
            this.queryParamsPay.pageNum = 1;
            this.getAccountsCollection();
            this.open = true;
            this.payTitle = "应收账款";
        },
        //应收账款查询列表
        getAccountsCollection() {
            //开立方为应收企业的
            this.queryParamsPay.payId = this.zfiCoreId;
            //接收方
            this.queryParamsPay.zfiSupplierId = this.zfiSupplierId;
           return getAccountsCollection(this.queryParamsPay).then((response) => {
                this.payList = response.data.records;
                this.selectChecked();
                this.total = response.data.total;
                return Promise.resolve(response)
            });
        },
        selectChecked() {
             //清空选择
            this.$refs.tablePay && this.$refs.tablePay.clearSelection();
            this.ticketList.forEach((item) => {
                this.payList.forEach(row => {
                if (row.zbiId == item.zbiId) {
                    this.$nextTick(() => {
                    this.$refs.tablePay && this.$refs.tablePay.toggleRowSelection(row, true);
                    })
                }
                });
            });
             //合计
            this.getReTotal(this.ticketList);
            //附件
             this.getFile(this.ticketList);
        },
        /* 删除按钮 */
        handleDelete(index, rows) {
            rows.splice(index, 1);
            if(this.$refs.tablePay){
                this.$refs.tablePay.clearSelection();
            }
            this.selectChecked();
        },
        //详情按钮
        handleDetail(index, rows){
            this.zbiId = rows[index].zbiId
            this.openDetailBill = true
        },
        /* 修改按钮 */
        handleUpdate(index, rows) {
            this.zbiId = rows[index].zbiId;
            this.openEditBill = true
        },
        /* 多选框跨页 */
        rowkey(row) {
            return row.zbiId;
        },
        // 多选框选中数据
        handleSelectionChange(val) {
            this.chooseTicket = val
        },
         //回到父页
        cancelGo(){
            this.goShow = false;
            this.$store.dispatch(
                "tagsView/delView",
                this.$route
            );
            this.$router.go(-1);
        },
        // 确认选择
      closeTicket() {
        if(this.chooseTicket.length > 0){
                var flag = true;
                //获取选中第一个的预计还款日期
                var zbiPayDate = this.chooseTicket[0].zbiPayDate;
                for(var i = 0 ;i < this.chooseTicket.length;i++){
                    if(zbiPayDate != this.chooseTicket[i].zbiPayDate){
                        flag = false;
                        this.$message({
                            message: '请选择预计还款日期相同的应收账款',
                            type: 'warning'
                        });
                        break;
                    }
                }
                if(flag){
                    //合计
                    this.getReTotal(this.chooseTicket);
                    this.ticketList = this.chooseTicket;
                    //更新附件信息
                    this.getFile(this.ticketList);
                    this.open = false;
                }
               
        }else{
            this.$message({
            message: '请选择应收账款',
            type: 'warning'
            });
        }
    },
      //重新合计
    getReTotal(chooseTicket){
                      //合计
                      this.checkTotalAmt = "0.00";
                      for(var i = 0; i < chooseTicket.length;i++){
                              this.checkTotalAmt  = accAdd(this.checkTotalAmt,chooseTicket[i].zbiAmount,2);
                      }
                      this.checkTotalBigAmt = this.smallToBig(this.checkTotalAmt);
                      this.checkTotalAmt = this.amtFormat(this.checkTotalAmt);
      },
    //取消选择按钮
    cancelTicket(){
        /* this.ticketList = [];
        if(this.$refs.tablePay){
            this.$refs.tablePay.clearSelection();
        } */
        this.open = false;
    },
    /** 清空选择信息 */
    deleteTicekt() {
        this.ticketList = [];
        this.checkTotalAmt = "0.00";
        this.checkTotalBigAmt = this.smallToBig(this.checkTotalAmt);
        if(this.$refs.tablePay){
            this.$refs.tablePay.clearSelection();
        }
        //更新附件
        this.getFile(this.ticketList);
    },
    /* 删除按钮 */
    handleDelete(index, rows) {
        rows.splice(index, 1);
        if(this.$refs.tablePay){
            this.$refs.tablePay.clearSelection();
        }
        this.selectChecked();
    },
    onSelectAll() {
        if(this.$refs.tablePay){
            this.$refs.tablePay.clearSelection();
        }
    },
    //格式化金额 
    amtFormat(cellValue) {
      if(cellValue == null || cellValue== undefined || cellValue == ''){
      cellValue = '0.00'
      }
      cellValue += '';
            if (!cellValue.includes('.')) {
      cellValue += '.00';
      }
      return cellValue.replace(/(\d)(?=(\d{3})+\.)/g, function ($0, $1) {
        return $1 + ',';
      }).replace(/\.$/, '');
    },
    //获取签发金额大写
    getBigSmall(){
        this.issuedAmount = this.smallToBig(this.form.zfiAmount);
    },
    /* //  将数字金额转换为大写金额 */
    smallToBig(money) {
      //  将数字金额转换为大写金额
      var cnNums = new Array(
        "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" ); //汉字的数字
      var cnIntRadice = new Array("", "拾", "佰", "仟"); //基本单位
      var cnIntUnits = new Array("", "万", "亿", "兆"); //对应整数部分扩展单位
      var cnDecUnits = new Array("角", "分", "毫", "厘"); //对应小数部分单位
      var cnInteger = "整"; //整数金额时后面跟的字符
      var cnIntLast = "元"; //整数完以后的单位
      //最大处理的数字
      var maxNum = 999999999999999.9999;
      var integerNum; //金额整数部分
      var decimalNum; //金额小数部分
      //输出的中文金额字符串
      var chineseStr = "";
      var parts; //分离金额后用的数组，预定义
      if (money == "" || money == null || money == undefined) {
        return "零元零角零分";
      }
      money = parseFloat(money);
      if (money >= maxNum) {
        //超出最大处理数字
        return "超出最大处理数字";
      }
      if (money == 0) {
        chineseStr = cnNums[0] + cnIntLast + cnInteger;
        return chineseStr;
      }
      //四舍五入保留两位小数,转换为字符串
      money = Math.round(money * 100).toString();
      integerNum = money.substr(0, money.length - 2);
      decimalNum = money.substr(money.length - 2);
      //获取整型部分转换
      if (parseInt(integerNum, 10) > 0) {
        var zeroCount = 0;
        var IntLen = integerNum.length;
        for (var i = 0; i < IntLen; i++) {
          var n = integerNum.substr(i, 1);
          var p = IntLen - i - 1;
          var q = p / 4;
          var m = p % 4;
          if (n == "0") {
            zeroCount++;
          } else {
            if (zeroCount > 0) {
              chineseStr += cnNums[0];
            }
            //归零
            zeroCount = 0;
            chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
          }
          if (m == 0 && zeroCount < 4) {
            chineseStr += cnIntUnits[q];
          }
        }
        chineseStr += cnIntLast;
      }
      //小数部分
      if (decimalNum != "") {
        var decLen = decimalNum.length;
        for (var i = 0; i < decLen; i++) {
          var n = decimalNum.substr(i, 1);
          if (n != "0") {
            chineseStr += cnNums[Number(n)] + cnDecUnits[i];
          }
        }
      }
      if (chineseStr == "") {
        chineseStr += cnNums[0] + cnIntLast + cnInteger;
      } else if (decimalNum == "" || /^0*$/.test(decimalNum)) {
        chineseStr += cnInteger;
      }
      return chineseStr;
    },
    //选择授信触发
    change(val) {
      if (!val) {
            //可用额度
            this.availableAmt = "0.00";
            //有效期
            this.validityDate ="";
            //产品是否可拆分
            this.zfpSplit= "",
            //融资放款方式
            this.zfpcrLoanType = "";
            //产品
            this.zfpId = "";
            //利率
            this.zfiRate = "";
            return;
        }
        let obj = {};
        obj = this.creditLineList.find(item => {
            return item.value === val;
        });
        //获取有效期的类型
        this.zfpcrDateType = obj.zfpcrDateType;
        //产品是否可拆分
        this.zfpSplit= obj.zfpSplit;
        //放款方式
        this.zfpcrLoanType = obj.zfpcrLoanType;
        //产品
        this.zfpId = obj.zfpId;
        //利率
        this.zfiRate = obj.zfpcrRate;
        //长期
        if("0"== this.zfpcrDateType){
            this.validityDate = "长期";
        }else{
            this.validityDate = obj.zfpcrEndDate;
        }
        var lineQueryParam = {};
        lineQueryParam.zfpcrId = val;
        //获取可用额度
        getAvailableBalance(lineQueryParam).then((response) => {
            this.availableAmt = response.data.remaining;
        });
    },
    //内部审批
    submitForm(param){
        this.$refs["form"].validate(valid => {
            //通过
           if(param == "00"){
                if(this.ticketList.length < 1){
                        this.$message({
                            message: '请选择应收账款',
                            type: 'warning'
                        });
                        return;
                }
                if(parseFloat(this.form.zfiAmount) > parseFloat(this.moneyDelete(this.checkTotalAmt))){
                    this.$message({
                            message: '签发金额不可大于合计金额',
                            type: 'warning'
                        });
                        return;
                }
           }
            
            if (valid) {
                const loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    background: 'rgba(0, 0, 0,0)'
                }); 
            //如果签发金额小于合计金额
            if((parseFloat(this.form.zfiAmount)) < (parseFloat(this.moneyDelete(this.checkTotalAmt)))){
                        var _this = this;
                        this.$confirm('签发金额小于应收金额合计,是否确认提交', "警告", {
                            confirmButtonText: "确定",
                            cancelButtonText: "取消",
                            type: "warning"
                        }).then(function() {
                           //应收账款
                            _this.form.ticketList = _this.ticketList;
                             _this.form.flag = param;
                            signFor(_this.form).then(response => {
                                 loading.close();
                                //通过
                                if("00" == param){
                                    _this.msgSuccess("融信资料已提交内部审核");
                                    _this.$store.dispatch("tagsView/delView", _this.$route);
                                    _this.$router.go(-1);
                                }else if ("01" == param){//拒绝
                                    _this.msgSuccess("该笔融信将作废");
                                    _this.$store.dispatch("tagsView/delView", _this.$route);
                                    _this.$router.go(-1);
                                }
                            }).catch((response)=>{
                                loading.close();
                            });
                        }).catch((e) => {
                                loading.close();
                            });

            }else{
                    //应收账款
                    this.form.ticketList = this.ticketList;
                    this.form.flag = param;
                    signFor(this.form).then(response => {
                         loading.close();
                        //通过
                        if("00" == param){
                            this.msgSuccess("融信资料已提交内部审核");
                            this.$store.dispatch("tagsView/delView", this.$route);
                            this.$router.go(-1);
                        }else if ("01" == param){//拒绝
                            this.msgSuccess("该笔融信将作废");
                            this.$store.dispatch("tagsView/delView", this.$route);
                            this.$router.go(-1);
                        }
                    }).catch((response)=>{
                        loading.close();
                    });
            }
            }
        });
    }, 
     //金额去掉千分位
    moneyDelete(num){
            if(num &&num != undefined && num != null){
                let _num = num;
                _num = _num.toString();
                _num = _num.replace(/,/gi,'');
                return _num;
            }else{
                return num;
            }
    },
    //预览
    handlePreview(row) {
        const pfiUrl = row.pfiUrl;
        const pfiFileName = row.pfiFileName;
        if (row.pfiUrl) {
            console.log(pfiFileName.substr(-3));
            if (pfiFileName.substr(-3) == "pdf") {
                this.wordUrl = pfiUrl + "/" + getToken();
                this.show=false;
                this.heid=true;
            } else if (
                pfiFileName.substr(-3) == "jpg" ||
                pfiFileName.substr(-3) == "png" ||
                pfiFileName.substr(-3) == "JPG" ||
                pfiFileName.substr(-3) == "PNG" ||
                pfiFileName.substr(-4) == "jpeg" ||
                pfiFileName.substr(-3) == "JPEG" 
            ) {
                this.wordUrl =
                    pfiUrl +
                    "/" +
                    getToken();
                    this.show=true;
                    this.heid=false;
                        console.log("====>",this.wordUrl);
            } else if (
                pfiFileName.substr(-3) == "doc" ||
                pfiFileName.substr(-3) == "DOC"||
                pfiFileName.substr(-4) == "docx" ||
                pfiFileName.substr(-3) == "DOCX"
            ) {
                this.wordUrl =
                    "https://view.officeapps.live.com/op/view.aspx?src=" +
                    pfiUrl +
                    "/" +
                    getToken() +
                    "/" +
                    pfiFileName;
                    this.show=false;
                    this.heid=true;
                    console.log("====>",this.wordUrl);
            } else {
                this.$message({
                    message: "暂不支持该类型文件预览",
                    type: "warning",
                });
                return;
            }
        }
        this.openFile = true;
    },
    //新增应付
    addPay(){
         //获取选中第一个的预计还款日期
        if(this.chooseTicket[0]){
            var zbiPayDate = this.chooseTicket[0].zbiPayDate;
            this.payDate = zbiPayDate;
        }
        if(this.form.zfiCoreId){
            this.openAddBill = true
        }else{
            this.$message({
                message: "开立方不能为空",
                type: "warning",
            });
        }
    },
    //新增账款回调
    emitAddClick(val){
        var self = this
        this.getAccountsCollection().then((response) => {
            //新增付款返回id直接选中
            if (val) {
                self.payList.forEach(element => {
                    if(element.zbiId == val){
                        // 将当前点击项选中
                        self.chooseTicket.push(element)
                        self.closeTicket()
                    }
                });
            }
        })
        self.openAddBill = false
    },
    //修改账款回调
    emitEditClick(val) {
        var self = this
        this.getAccountsCollection().then((response) => {
            //修改付款返回id直接选中
            if (val) {
                // self.payList.forEach(element => {
                //     if (element.zbiId == val) {
                //         // 将当前点击项选中
                //         // self.chooseTicket.push(element)
                //         //self.closeTicket()
                //     }
                // });
                console.log(self.chooseTicket)
                self.ticketList = self.chooseTicket
                self.closeTicket()
            }
        })
        self.openEditBill = false
    }, 
    //查询有无签收内部审批
    isOpenApproval(){
         var confirmParam = {};
         confirmParam.menuId = "1000000005";
         isOpenApproval(confirmParam).then((response) => {
             var result = response.data.isOpen;
            //有签收内部审批
            if(true == result){
                 //获取融资方审批状态(拒绝或者状态为空时显示通过按钮)
                if(this.zfiSupplierStatus == "02" || this.zfiSupplierStatus == "" || this.zfiSupplierStatus == "null" || this.zfiSupplierStatus == null ){
                    this.isHas = true;
                }else{
                     this.isHas = false;
                     //获取文件
                     //融资方通过
                    if(this.zfiSupplierStatus == '01'){
                        //预览文件
                        this.getContractFile(true);
                    }
                }
            }else{//无签收内部审批,显示签收按钮
                this.isHas = false;
                 //融资方通过
                if(this.zfiSupplierStatus == '01'){
                    //预览文件
                    this.getContractFile(true);
                }
            }
        });
    },
    //签收
    sign(){
        //融资方通过
        if(this.zfiSupplierStatus == '01'){
            //预览文件
            this.getContractFile();
        }else{
                this.$refs["form"].validate(valid => {
                //通过
                if(this.ticketList.length < 1){
                        this.$message({
                            message: '请选择应收账款',
                            type: 'warning'
                        });
                        return;
                }
                if(parseFloat(this.form.zfiAmount) > parseFloat(this.moneyDelete(this.checkTotalAmt))){
                    this.$message({
                            message: '签发金额不可大于合计金额',
                            type: 'warning'
                        });
                        return;
                }
                
                if (valid) {
                    const loading = this.$loading({
                        lock: true,
                        text: 'Loading',
                        background: 'rgba(0, 0, 0,0)'
                    }); 
                //如果签发金额小于合计金额
                if((parseFloat(this.form.zfiAmount)) < (parseFloat(this.moneyDelete(this.checkTotalAmt)))){
                            var _this = this;
                            this.$confirm('签发金额小于应收金额合计,是否确认提交', "警告", {
                                confirmButtonText: "确定",
                                cancelButtonText: "取消",
                                type: "warning"
                            }).then(function() {
                            //应收账款
                                _this.form.ticketList = _this.ticketList;
                                _this.form.flag = "00";
                                signFor(_this.form).then(response => {
                                    loading.close();
                                    //预览文件
                                    _this.getContractFile();
                                }).catch((response)=>{
                                    loading.close();
                                });
                            }).catch((e) => {
                                    loading.close();
                                });

                }else{
                        //应收账款
                        this.form.ticketList = this.ticketList;
                        this.form.flag = "00";
                        signFor(this.form).then(response => {
                            loading.close();
                            //预览文件
                            this.getContractFile();
                        }).catch((response)=>{
                            loading.close();
                        });
                }
                }
            });
        }

    },
    //获取合同文件
    getContractFile(nosign){
        const loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    background: 'rgba(0, 0, 0,0)'
                });
         getContractFile(this.form).then((response) => {
                loading.close();
                if(response.data.list){
                    this.pdfFileList = response.data.list;
                }
                 //文件存在
                if(this.pdfFileList.length > 0 ){
                    this.pdfShowDialog = true;

                }else{
                     /*  this.$message({
                        message: '文件不存在！',
                        type: 'warning'
                      }); */
                      //文件不存在，并且不是一进页面调的文件预览才盖章
                      if(!nosign){
                          this.contractSigning();
                      }
                }
            }).catch((response)=>{
                        loading.close();
            });
    },
    closePdfShow(){
        this.pdfShowDialog = false;
    },
    //盖章
    contractSigning(){
            const loading = this.$loading({
                        lock: true,
                        text: 'Loading',
                        background: 'rgba(0, 0, 0,0)'
                    });
            contractSigning(this.form).then((response) => {
                loading.close();
                const zfiId = this.$route.params && this.$route.params.zfiId;
                getFinanceSign(zfiId).then((response) => {
                    //融信编号
                    this.financeSignForm.zfiNumber = response.data.zfiNumber;
                    //融信金额
                    this.financeSignForm.zfiAmount = response.data.zfiAmount;
                    //利率
                    this.financeSignForm.zfiRate = response.data.zfiRate;
                    //最长融信期限
                    this.financeSignForm.intervalTime = response.data.intervalTime;
                    //融信有效期
                    this.financeSignForm.validity = response.data.validity;
                    this.goShow = true;
                });
            }).catch((response) => {
                loading.close();
            });
    },
     //去融资
    goFinance(){
        //关闭当前页
         this.$store.dispatch(
            "tagsView/delView",
            this.$route
        );
        //关闭弹框
        this.goShow = false;
        Cookies.set("/credit/goFinance/"+this.zfiId + "/", this.$route.fullPath)
        this.$router.push({ path: "/credit/goFinance/"+this.zfiId + "/" });
    },
    //返回到列表页
    goParent(){
         var self = this
        this.pdfShowDialog = false;
        self.$store.dispatch(
            "tagsView/delView",
            self.$route
            );
         //self.$router.push("/Bill/credit")
         self.$router.push("/Bill/finance/credit")
    },
    /* 金额展示 */
    handleInput(str) {
        return amtformat(str, 2, ".", ",");
    },
  }
};
</script>

<style lang="scss">

.uoloadfj .el-upload--picture-card{
  width:110px;
  height:110px;
  line-height:110px;
}
.fjUoloadSty .el-upload--picture-card{
  display:none;   
}

table th.star div::before {
    content: '*';
    color: red;
}

</style>

<style type="text/css">
 table.gridtable {
    font-size:11px;
    color:#333333;
     border-width: 1px;
    border-collapse: collapse;
}
 table.gridtable th {
     border-width: 1px;
     padding: 8px;
     border-style: solid;
     background-color: #dedede;
 }
 table.gridtable td {
        border-width: 1px;
        padding: 8px;
        border-style: solid;
    }
 </style>