<template>
    <div class="borderless" v-loading="pageLoading">
        <div class="customer-head">
            <div class="customer-back">
                <el-button type="danger" style="border: none;background: none;color: red" icon="el-icon-arrow-left"
                           @click="backToList">返回列表
                </el-button>
            </div>
            <div class="add-customer-btn">
                <el-button size="small" style="margin-right: 8px"
                           :loading="saveLoading" :disabled="!form.id" @click="previewreportfun" >预 览
                </el-button>
                <el-button size="small" style="margin-right: 8px" v-if="roleName.indexOf('admin') != -1"
                           :loading="saveLoading" :disabled="!form.id" @click="DesignreportDialog = true" >报表设计
                </el-button>
                <el-button  size="small" type="warning" plain  style="margin-right: 8px" :disabled="!form.id || editPower" v-if="form.status == 3"
                            :loading="saveLoading" @click="revokeFinInvoicesApprovefun">撤销
                </el-button>
                <el-button  size="small" type="success" plain  style="margin-right: 8px" :disabled="!form.id || editPower" v-else
                            :loading="saveLoading" @click="editCustomer('提交')">提交
                </el-button>
                <el-button  size="small" type="primary" :disabled="statusType || editPower" style="margin-right: 8px" v-if="editSave"
                            :loading="saveLoading" @click="editHandle">编 辑
                </el-button>
                <el-button  size="small" type="primary" :disabled="statusType" style="margin-right: 8px" v-else
                            :loading="saveLoading" @click="editCustomer()">保 存
                </el-button>
            </div>
        </div>
        <div style="margin: 55px 5px 0px 5px;'">
            <el-form :model="form" ref="form" :rules="rules" label-width="90px" class="demo-ruleForm">
                <trade-card title="基础信息" styleIocup="color:#4b9fe9">
                    <el-row>
                        <el-col :span="10">
                            <div class="flexBoxLeft">
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="发票号码" prop="invoiceNo">
                                            <el-input style="width: 100%;" v-model="form.invoiceNo"
                                                      size="small" autocomplete="off"
                                                      :disabled="true"
                                                      clearable placeholder="发票号码" >
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="开票日期" prop="invoiceDate">
                                            <el-date-picker v-model="form.invoiceDate" clearable
                                                            style="width: 100%;"
                                                            type="date" size="small"
                                                            :disabled="editSave"
                                                            value-format="yyyy-MM-dd"
                                                            placeholder="请选择开票日期">
                                            </el-date-picker>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="24">
                                        <el-form-item label="开票单位" prop="invCorpCnName">
                                            <search-query :datalist="invCorpData"
                                                          :selectValue="form.invCorpCnName"
                                                          :clearable="true"
                                                          :disabled="editSave || !form.corpId"
                                                          :buttonIf="false"
                                                          :remote="true"
                                                          :filterable="true"
                                                          placeholder="请选择开票单位"
                                                          :forParameter="{ key:'id', label:'invoiceHeader', value:'id'}"
                                                          @corpChange="corpChange($event,'invCorpCnName')"
                                                          @remoteMethod="invcorpsinvoiceheaderListfun"
                                                          @corpFocus="invcorpsinvoiceheaderListfun" >
                                            </search-query>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="税号" prop="invCorpTaxNo">
                                            <el-input style="width: 100%;" v-model="form.invCorpTaxNo"
                                                      size="small" autocomplete="off"
                                                      :disabled="true"
                                                      clearable placeholder="请输入税号" >
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="发票币种" prop="invCurCode">
                                            <search-query :datalist="invCurCodeData"
                                                          :selectValue="form.invCurCode"
                                                          :filterable="true"
                                                          :clearable="true"
                                                          :disabled="editSave"
                                                          :buttonIf="false"
                                                          placeholder="请选择发票币种"
                                                          :forParameter="{key:'id',label:'code',value:'code'}"
                                                          @corpChange="corpChange($event,'invCurCode')"
                                                          @corpFocus="invCurCodeRateListfun">
                                            </search-query>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="美元银行" prop="invCorpAccountBankUsd">
                                            <el-input style="width: 100%;" v-model="form.invCorpAccountBankUsd"
                                                      size="small" autocomplete="off"
                                                      :disabled="true"
                                                      clearable placeholder="请输入美元银行" >
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="美元账户" prop="invCorpAccountNoUsd">
                                            <el-input style="width: 100%;" v-model="form.invCorpAccountNoUsd"
                                                      size="small" autocomplete="off"
                                                      :disabled="true"
                                                      clearable placeholder="请输入美元账户" >
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="人民币银行" prop="invCorpAccountBankCny">
                                            <el-input style="width: 100%;" v-model="form.invCorpAccountBankCny"
                                                      size="small" autocomplete="off"
                                                      :disabled="true"
                                                      clearable placeholder="请输入美元银行" >
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="人民币账户" prop="invCorpAccountNoCny">
                                            <el-input style="width: 100%;" v-model="form.invCorpAccountNoCny"
                                                      size="small" autocomplete="off"
                                                      :disabled="true"
                                                      clearable placeholder="请输入人民币账户" >
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="船名/航次" prop="vesselVoyno">
                                            <el-input style="width: 100%;" v-model="form.vesselVoyno"
                                                      size="small" autocomplete="off"
                                                      :disabled="editSave"
                                                      clearable placeholder="请输入船名/航次" >
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="开航日期" prop="etd">
                                            <el-date-picker v-model="form.etd" clearable
                                                            style="width: 100%;"
                                                            type="date" size="small"
                                                            :disabled="editSave"
                                                            value-format="yyyy-MM-dd HH:mm:ss"
                                                            placeholder="请输入开航日期">
                                            </el-date-picker>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="装货港" prop="pol">
                                            <search-query :datalist="polData"
                                                          :selectValue="form.pol"
                                                          :filterable="true"
                                                          :clearable="true"
                                                          :remote="true"
                                                          :disabled="editSave"
                                                          :buttonIf="false"
                                                          placeholder="请选择装货港"
                                                          :forParameter="{key:'id',label:'enName',value:'enName'}"
                                                          @corpChange="corpChange($event,'pol')"
                                                          @remoteMethod="polBportsListfun"
                                                          @corpFocus="polBportsListfun" >
                                            </search-query>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="卸货港" prop="pod">
                                            <search-query :datalist="podData"
                                                          :selectValue="form.pod"
                                                          :filterable="true"
                                                          :clearable="true"
                                                          :remote="true"
                                                          :disabled="editSave"
                                                          :buttonIf="false"
                                                          placeholder="请选择卸货港"
                                                          :forParameter="{key:'id',label:'enName',value:'enName'}"
                                                          @corpChange="corpChange($event,'pod')"
                                                          @remoteMethod="podBportsListfun"
                                                          @corpFocus="podBportsListfun" >
                                            </search-query>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="目的地" prop="destination">
                                            <search-query :datalist="destinationData"
                                                          :selectValue="form.destination"
                                                          :filterable="true"
                                                          :clearable="true"
                                                          :remote="true"
                                                          :disabled="editSave"
                                                          :buttonIf="false"
                                                          placeholder="请选择目的地"
                                                          :forParameter="{key:'id',label:'enName',value:'enName'}"
                                                          @corpChange="corpChange($event,'destination')"
                                                          @remoteMethod="destinationBportsListfun"
                                                          @corpFocus="destinationBportsListfun" >
                                            </search-query>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="箱型箱量" prop="containers">
                                            <el-input style="width: 100%;" v-model="form.containers"
                                                      size="small" autocomplete="off"
                                                      :disabled="editSave"
                                                      clearable placeholder="请输入箱型箱量" >
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="开票CNY:" prop="amountCny">
                                            <span>¥{{form.amountCny}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="开票USD:" prop="amountUsd">
                                            <span>${{form.amountUsd}}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="开票合计:" prop="amountLoc">
                                            <span>¥{{form.amountLoc}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </div>
                        </el-col>
                        <el-col :span="14">
                            <div class="flexBoxRight">
                                <!--<el-row>-->
                                <!--    <el-col :span="6">-->
                                <!--        <el-checkbox style="margin-left: 10%" size="medium" :true-label="1" :false-label="0"-->
                                <!--                     :disabled="editSave"-->
                                <!--                     v-model="form.isDk">整票(不列费用明细)-->
                                <!--        </el-checkbox>-->
                                <!--    </el-col>-->
                                <!--    <el-col :span="5">-->
                                <!--        <el-checkbox style="margin-left: 10%" size="medium" :true-label="1" :false-label="0"-->
                                <!--                     :disabled="editSave"-->
                                <!--                     v-model="form.isRp">只提取开票费用-->
                                <!--        </el-checkbox>-->
                                <!--    </el-col>-->
                                <!--    <el-col :span="3">-->
                                <!--        <el-checkbox style="margin-left: 10%" size="medium" :true-label="1" :false-label="0"-->
                                <!--                     :disabled="editSave"-->
                                <!--                     v-model="form.isExportMblno">主单号-->
                                <!--        </el-checkbox>-->
                                <!--    </el-col>-->
                                <!--    <el-col :span="3">-->
                                <!--        <el-checkbox style="margin-left: 10%" size="medium" :true-label="1" :false-label="0"-->
                                <!--                     :disabled="editSave"-->
                                <!--                     v-model="form.isExportVslvoy">船名航次-->
                                <!--        </el-checkbox>-->
                                <!--    </el-col>-->
                                <!--    <el-col :span="3">-->
                                <!--        <el-checkbox style="margin-left: 10%" size="medium" :true-label="1" :false-label="0"-->
                                <!--                     :disabled="editSave"-->
                                <!--                     v-model="form.isExportHblno">分单号-->
                                <!--        </el-checkbox>-->
                                <!--    </el-col>-->
                                <!--</el-row>-->
                                <el-row>
                                    <el-col :span="16">
                                        <el-form-item label="结算单位" prop="corpCnName">
                                            <search-query :datalist="corpData"
                                                          :selectValue="form.corpCnName"
                                                          :clearable="true"
                                                          :disabled="editSave"
                                                          :buttonIf="false"
                                                          :remote="true"
                                                          :filterable="true"
                                                          placeholder="请输入结算单位"
                                                          :forParameter="{ key:'id', label:'cnName', value:'cnName'}"
                                                          @corpChange="corpChange($event,'corpCnName')"
                                                          @remoteMethod="corpBcorpsListfun"
                                                          @corpFocus="corpBcorpsListfun" >
                                            </search-query>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="税控发票号" prop="taxInvoiceNo">
                                            <el-input style="width: 100%;" v-model="form.taxInvoiceNo"
                                                      size="small" autocomplete="off"
                                                      :disabled="editSave"
                                                      clearable placeholder="请输入税控发票号" >
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="9">
                                        <el-form-item label="业务日期" prop="accountDateFrom">
                                            <el-date-picker v-model="form.accountDateFrom" clearable
                                                            style="width: 100%;"
                                                            type="date" size="small"
                                                            :disabled="editSave"
                                                            value-format="yyyy-MM-dd"
                                                            placeholder="选择业务日期">
                                            </el-date-picker>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="7">
                                        <el-form-item label="-" prop="accountDateTo" label-width="30px">
                                            <el-date-picker v-model="form.accountDateTo" clearable
                                                            style="width: 100%;"
                                                            type="date" size="small"
                                                            :disabled="editSave"
                                                            value-format="yyyy-MM-dd"
                                                            placeholder="选择业务日期">
                                            </el-date-picker>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="发票汇率" prop="exrate">
                                            <el-input style="width: 100%;" v-model="form.exrate"
                                                      size="small" autocomplete="off"
                                                      :disabled="editSave"
                                                      clearable placeholder="请输入发票汇率" >
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="16">
                                        <el-form-item label="业务编号" prop="businessNo">
                                            <el-input style="width: 100%;" v-model="form.businessNo"
                                                      size="small" autocomplete="off"
                                                      :disabled="editSave"
                                                      clearable placeholder="请输入业务编号" >
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="发票类型" prop="invType">
                                            <search-query :datalist="invTypeData"
                                                          :selectValue="form.invType"
                                                          :clearable="true"
                                                          :disabled="editSave"
                                                          :buttonIf="false"
                                                          placeholder="请输入发票类型"
                                                          :forParameter="{ key:'dictKey', label:'dictValue', value:'dictKey'}"
                                                          @corpChange="corpChange($event,'isInvoice')"
                                                          @corpFocus="invTypeWorkDictsfun" >
                                            </search-query>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="16">
                                        <el-form-item label="主单编号" prop="mblno">
                                            <el-input style="width: 100%;" v-model="form.mblno"
                                                      size="small" autocomplete="off"
                                                      :disabled="editSave"
                                                      clearable placeholder="请输入主单编号" >
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="对账单号" prop="checkNo">
                                            <el-input style="width: 100%;" v-model="form.checkNo"
                                                      size="small" autocomplete="off"
                                                      :disabled="editSave"
                                                      clearable placeholder="请输入对账单号" >
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="16">
                                        <el-form-item label="分单编号" prop="hblno">
                                            <el-input style="width: 100%;" v-model="form.hblno"
                                                      size="small" autocomplete="off"
                                                      :disabled="editSave"
                                                      clearable placeholder="请输入分单编号" >
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="BOOK NO" prop="bookingNo">
                                            <el-input style="width: 100%;" v-model="form.bookingNo"
                                                      size="small" autocomplete="off"
                                                      :disabled="editSave"
                                                      clearable placeholder="请输入BOOK NO" >
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="业务类型" prop="businessTypes">
                                            <search-query :datalist="businessTypesData"
                                                          :selectValue="form.businessTypes"
                                                          :clearable="true"
                                                          :disabled="editSave"
                                                          :buttonIf="false"
                                                          :multiple="true"
                                                          :collapseTags="true"
                                                          placeholder="请输入业务类型"
                                                          @corpChange="corpChange($event,'businessTypes')">
                                            </search-query>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="税率(%)" prop="taxRate">
                                            <el-input style="width: 100%;" v-model="form.taxRate"
                                                      size="small" autocomplete="off"
                                                      :disabled="editSave"
                                                      clearable placeholder="请输入税率" >
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="选择币种" prop="curCode">
                                            <search-query :datalist="curData"
                                                          :selectValue="form.curCode"
                                                          :filterable="true"
                                                          :clearable="true"
                                                          :disabled="editSave"
                                                          :remote="true"
                                                          :buttonIf="false"
                                                          placeholder="请输入选择币种"
                                                          :forParameter="{key:'id',label:'code',value:'code'}"
                                                          @remoteMethod="getRateListfun"
                                                          @corpChange="corpChange($event,'curCode')"
                                                          @corpFocus="getRateListfun">
                                            </search-query>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="邮箱" prop="yx">
                                            <el-input style="width: 100%;" v-model="form.yx"
                                                      size="small" autocomplete="off"
                                                      :disabled="editSave"
                                                      clearable placeholder="请输入邮箱" >
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-checkbox style="margin-left: 10%" size="medium" :true-label="1" :false-label="0"
                                                     :disabled="editSave"
                                                     v-model="form.isExchangeToCny">转换成人民币
                                        </el-checkbox>
                                        <el-checkbox v-model="appendType" :disabled="statusType" false-label="检索" true-label="追加">追加</el-checkbox>
                                        <el-button type="primary"
                                                   size="small" :disabled="statusType"
                                                   plain @click="finstlbillslistAccBillV1fun(appendType)">提取费用
                                        </el-button>
                                    </el-col>
                                    <el-col :span="24">
                                        <el-form-item label="全电发票:" prop="elecRemarks">
                                            <el-input style="width: 100%;" v-model="form.elecRemarks"
                                                      size="small" autocomplete="off" type="textarea"
                                                      clearable placeholder="请输入全电发票备注" >
                                            </el-input>
                                        </el-form-item>
                                    </el-col>


                                </el-row>
                            </div>
                        </el-col>
                    </el-row>
                </trade-card>
                <el-card style="margin-top: 10px">
                    <el-tabs v-model="detailTabs" type="card">
                        <el-tab-pane label="费用明细" name="first">
                            <div style="margin-bottom: 10px;display: flex;">
                                <search-query :datalist="serverData"
                                              :selectValue="form.serverName"
                                              :clearable="true"
                                              :buttonIf="false"
                                              :filterable="true"
                                              :forParameter="{key:'dictKey',label:'dictValue',value:'dictValue'}"
                                              placeholder="请选择开票项目"
                                              @corpChange="corpChange($event,'serverName')"
                                              @corpFocus="serverWorkDictsfun" >
                                </search-query>
                                <el-button style="margin-left: 10px" :disabled="!form.id || statusType" size="small" type="primary" @click="invoicingfun" >生成开票明细</el-button>
                                <el-button style="margin-left: 10px" :disabled="!form.id || statusType" size="small" type="warning" @click="invoicingRevokefun" >撤销开票明细</el-button>
                                <el-button size="small" :disabled="!form.id || statusType" type="danger" @click="batchDeletefun" >一键删除</el-button>

                                <el-input style="width: 10%;margin-left: 10px;" v-model="invoiceAmountCNY"
                                          size="small" autocomplete="off" type="numbers"
                                          clearable placeholder="开票金额" >
                                    <span style="line-height: 32px;" slot="suffix" >CNY</span>
                                </el-input>
                                <el-input style="width: 10%;margin-left: 5px;" v-model="invoiceAmountUSD"
                                          size="small" autocomplete="off" type="numbers"
                                          clearable placeholder="开票金额" >
                                    <span style="line-height: 32px;" slot="suffix" >USD</span>
                                </el-input>
                                <el-button style="margin-left: 10px" :disabled="statusType" size="small" type="primary" @click="invoiceMatchingfun()" >匹配金额</el-button>
                            </div>
                            <fininvoicesitems ref="fininvoicesitems"
                                              :tableData="tableData"
                                              :handleSelectionData="handleSelectionData"
                                              :editSave="editSave"
                                              @handleSelectionChange="handleSelectionChange"
                                              @deletefun="detailsdeletionfun">
                            </fininvoicesitems>
                        </el-tab-pane>
                        <el-tab-pane label="开票明细" name="second">
                            <div style="margin-bottom: 10px;display: flex;">
                                <el-button :disabled="statusType" size="small" type="danger" @click="invoicingBatchDelete" >一键删除</el-button>
                            </div>
                            <fininvoiceitemdetail :tableData="InvoicingList"
                                                  :handleSelectionData="invoicingCheckboxData"
                                                  @handleSelectionChange="invoicingCheckboxChange"
                                                  @deletefun="invoiceDeletionfun" @savefun="invoiceSavefun">
                            </fininvoiceitemdetail>
                        </el-tab-pane>
                    </el-tabs>
                </el-card>
                <el-card class="box-card" style="margin-top: 10px">
                    <el-row>
                        <el-col :span="5">
                            <el-form-item label="业务编号" prop="billNo">
                                <el-input style="width: 100%;" v-model="form.billNo"
                                          size="small" autocomplete="off"
                                          :disabled="true"
                                          clearable placeholder="请输入业务编号" >
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="单据日期" prop="billDate">
                                <el-date-picker v-model="form.billDate" clearable
                                                style="width: 100%;"
                                                type="date" size="small"
                                                :disabled="true"
                                                value-format="yyyy-MM-dd HH:mm"
                                                placeholder="选择单据日期">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="制单人" prop="createUserName">
                                <el-input style="width: 100%;" v-model="form.createUserName"
                                          size="small" autocomplete="off"
                                          :disabled="true"
                                          clearable placeholder="请输入制单人" >
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-card>
            </el-form>
        </div>

        <!--设计报表弹窗-->
        <el-dialog append-to-body title="设计报表" class="el-dialogDeep" :visible.sync="DesignreportDialog" width="70%"
                   :close-on-click-modal="false" :destroy-on-close="true" :close-on-press-escape="false" v-dialog-drag>
            <reports :id="form.id" :assemblyForm="form" businessValue="FPSQ"></reports>
        </el-dialog>

        <!--预览-->
        <el-dialog
            title="打印"
            :visible.sync="selectPrintingDialog"
            append-to-body
            width="70%"
            :close-on-click-modal="false"
            :destroy-on-close="true"
            :close-on-press-escape="false"
            v-dialog-drag>
            <div>
                <reportformsList ref="reportformsList" @reportRadio="reportRadio"></reportformsList>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="selectPrintingDialog = false;">取 消</el-button>
            </span>
        </el-dialog>

        <!--报表组件-->
        <reportContainer ref="reportContainer"></reportContainer>
    </div>
</template>

<script>
import fininvoicesitems from "@/views/iosBasicData/fininvoicesApplyfor/assembly/fininvoicesitems.vue";
import fininvoiceitemdetail from "@/views/iosBasicData/fininvoicesApplyfor/assembly/fininvoiceitemdetail.vue";
import {getRateList} from "@/api/iosBasicData/rateManagement";
import {finstlbillsGetByDetail, finstlbillsitemsRemove, finstlbillslistAccBillV1} from "@/api/iosBasicData/finstlbills";
import {bcorpsbankList, corpsinvoiceheaderList, getBcorpsList} from "@/api/iosBasicData/bcorps";
import {bportsList} from "@/api/iosBasicData/bports";
import SearchQuery from "@/components/iosbasic-data/searchquery.vue";
import {
    finInvoicesApprove,
    fininvoicesDetail,
    revokeFinInvoicesApprove,
    fininvoicesSubmit,
    fininvoicesitemsRemove,
    generateFinInvoicesDetail,
    fininvoiceitemdetailRemove, revokeFinInvoicesDetail,fininvoiceitemdetailSubmit
} from "@/api/iosBasicData/fininvoices";
import {getWorkDicts} from "@/api/system/dictbiz";
import {getCurrentDate} from "@/util/date";
import reports from "@/views/iosBasicData/SeafreightExportF/bills/assembly/reports.vue";
import reportformsList from "@/views/iosBasicData/SeafreightExportF/bills/assembly/reportformsList.vue";
import {getList as getreportsList, reportsGetReportData} from "@/api/iosBasicData/reports";
import reportContainer from "@/views/iosBasicData/report-container/report-container.vue";

export default {
        components:{reportContainer, reportformsList, reports, SearchQuery, fininvoicesitems,fininvoiceitemdetail},
        data() {
            return {
                DesignreportDialog:false, // 设计报表弹窗
                selectPrintingDialog:false, // 预览报表
                invoiceAmountCNY:0, // 费用明细开票金额输入框CNY
                invoiceAmountUSD:0, // 费用明细开票金额输入框USD
                statusType:false, // 是否已经提交
                serverData:[], // 开票项目数据
                detailTabs:'first',
                appendType:'检索',
                pageLoading:false, // 全屏加载
                saveLoading:false, // 按钮加载
                form:{
                    invCurCode:'CNY',
                    isRp:1,
                    invType:'全电发票',
                    taxRate:0,
                    invoiceDate:getCurrentDate(),
                    isExchangeToCny:0
                },
                tableData:[], // 费用明细数据
                InvoicingList:[], // 开票明细数据
                handleSelectionData:[], // 费用明细选择的数据
                invoicingCheckboxData:[], // 开票明细选择的数据
                corpData:[], // 结算单位数据
                invCorpData:[], // 开票单位
                bankReceiptData:[], // 结算单位银行账号数据
                // 业务类型
                businessTypesData:[
                    {
                        label:'海运出口',
                        value:'SE'
                    },{
                        label:'海运进口',
                        value:'SI'
                    }
                ],
                curData:[], // 币别
                destinationData:[], // 目的港
                podData:[], // 卸货港
                polData:[], // 装货港
                invCurCodeData:[], // 发票币种
                invTypeData:[], // 发票类型
                rules: {
                    corpCnName: [
                        {required: true, message: '请输入付费对象', trigger: 'blur'},
                    ],
                    invoiceDate: [
                        {required: true, message: '请输入开票日期', trigger: 'blur'},
                    ],
                    exrate: [
                        {required: true, message: '请输入导入汇率', trigger: 'blur'},
                    ],
                    taxRate: [
                        {required: true, message: '请输入所属税率', trigger: 'blur'},
                    ],
                    invCurCode: [
                        {required: true, message: '请输入所属发票币别', trigger: 'blur'},
                    ],
                },
                roleName:[], // 当前的角色权限
                saberUserInfo:{}, // 当前登录人信息
                editPower:false, // 当前是否可以编辑
            }
        },
        props:{
            editSave:{
                type:Boolean,
                default:false
            }
        },
        watch:{
            // 监听 状态
            "form.status":{
                // 执行方法
                handler(oldValue,newValue) {
                    if (oldValue == 3) {
                        this.statusType = true
                    }else {
                        this.statusType = false
                    }
                },
                deep: true, // 深度监听
                immediate: true  // 第一次改变就执行
            },
        },
         created() {
             this.roleName =  localStorage.getItem('roleName').split(',')
             // 获取当前登录人个人信息
             this.saberUserInfo = JSON.parse(localStorage.getItem('saber-userInfo')).content
            if (!this.form.id) {
                getRateList({current:1,size:30}).then(res=>{
                    for (let item of res.data.data.records) {
                        if (item.code == "USD") {
                            this.$set(this.form,'exrate',item.exrate)
                        }
                    }
                })
            }
        },
        methods:{
            // 打印
            reportRadio(val){
                // 获取报表数据
                reportsGetReportData({
                    billId:this.form.id,
                    reportCode:val.classifyCode,
                    groupCode:val.groupCode,
                    type:'FPSQ'
                }).then(res=>{
                    this.handleReportPreview(val.url,res.data.data.data)
                })
            },
            // 报表预览
            previewreportfun(){
                getreportsList(1,10,{
                    businessType:'FPSQ',
                    // classifyCode:'结算中心',
                    // groupCode:'付费结算'
                }).then(res=>{
                    if (res.data.data.records.length == 1){
                        this.reportRadio(res.data.data.records[0])
                    }else {
                        this.saveLoading = true
                        this.selectPrintingDialog = true
                        this.saveLoading = false
                        let page = {
                            pageSize: 10,
                            currentPage: 1,
                            total: 0
                        }
                        this.$nextTick(()=>{
                            this.$refs.reportformsList.onLoad(page,{
                                businessType:'FPSQ',
                                // classifyCode:'结算中心',
                                // groupCode:'付费结算'
                            })
                        })
                    }
                })
            },
            // 开票明细编辑完成保存
            invoiceSavefun(row){
                row.amountRate = this.form.taxRate
                // 销售额/(1+税率)×税率
                row.amountTax = (row.amount / (1 + (Number(row.amountRate) / 100)) * (Number(row.amountRate) / 100)).toFixed(2)
                fininvoiceitemdetailSubmit(row).then(res=>{
                    this.$message.success('操作成功')
                    this.fininvoicesDetailfun(this.form.id)
                })
            },
            // 确认开票信息
            invoicingfun(){
                if (this.handleSelectionData.length == 0) {
                    this.$message.warning('请选择数据')
                    return;
                }
                if (!this.form.serverName) {
                    this.$message.warning('请选择开票项目')
                    return
                }
                let obj = this.form
                obj.finInvoicesItemsList = []
                obj.businessTypes = this.form.businessTypes?this.form.businessTypes.join(','):''
                //开票日期
                if(this.form.invoiceDate) {
                    obj.invoiceDate = this.form.invoiceDate.slice(0,10) + ' 00:00:00'
                }
                // 业务日期
                if (this.form.accountDateFrom) {
                    this.form.accountDateFrom = this.form.accountDateFrom.slice(0,10) + ' 00:00:00'
                }
                if (this.form.accountDateTo) {
                    this.form.accountDateTo = this.form.accountDateTo.slice(0,10) + ' 00:00:00'
                }
                for (let item of this.handleSelectionData) {
                    // 拿未开票的数据
                    if(item.status == 0) {
                        if (item.currentCurCode == 'CNY') {
                            item.currentAmount = item.currentAmountCNY
                        }else {
                            item.currentAmount = item.currentAmountUSD
                        }
                        obj.finInvoicesItemsList.push(item)
                    }
                }
                if (obj.finInvoicesItemsList.length == 0) {
                    this.$message.warning('请选择未生成发票的数据')
                    return
                }
                // 开票项目
                generateFinInvoicesDetail(obj).then(res=>{
                    this.$message.warning('操作成功')
                    this.fininvoicesDetailfun(this.form.id)
                })
                this.detailTabs = 'second'
            },
            // 撤销开票信息
            invoicingRevokefun(){
                if (this.handleSelectionData.length == 0) {
                    this.$message.warning('请选择数据')
                    return;
                }
                let obj = this.form
                obj.finInvoicesItemsList = []
                obj.businessTypes = this.form.businessTypes?this.form.businessTypes.join(','):''
                //开票日期
                if(this.form.invoiceDate) {
                    obj.invoiceDate = this.form.invoiceDate.slice(0,10) + ' 00:00:00'
                }
                // 业务日期
                if (this.form.accountDateFrom) {
                    obj.accountDateFrom = this.form.accountDateFrom.slice(0,10) + ' 00:00:00'
                }
                if (this.form.accountDateTo) {
                    obj.accountDateTo = this.form.accountDateTo.slice(0,10) + ' 00:00:00'
                }
                for (let item of this.handleSelectionData) {
                    // 拿未开票的数据
                    if(item.status == 1) {
                        if (item.currentCurCode == 'CNY') {
                            item.currentAmount = item.currentAmountCNY
                        }else {
                            item.currentAmount = item.currentAmountUSD
                        }
                        obj.finInvoicesItemsList.push(item)
                    }
                }
                if (obj.finInvoicesItemsList.length == 0) {
                    this.$message.warning('请选择已生成发票的数据')
                    return
                }
                // 撤销开票项目
                revokeFinInvoicesDetail(obj).then(res=>{
                    this.$message.warning('操作成功')
                    this.fininvoicesDetailfun(this.form.id)
                })
            },
            // 费用明细一键删除
            batchDeletefun(){
                if (this.handleSelectionData.length == 0) {
                    return this.$message.warning('请选择要删除的数据')
                }
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(()=>{
                    // 获取有id 的数据
                    const itemsWithId = this.handleSelectionData.filter(item => item.hasOwnProperty('id'));
                    let arrIds = itemsWithId.map(item=>item.id) // 获取id 数据
                    // 把选中的删除掉
                    this.handleSelectionData.forEach((item)=>{
                        for (let index in this.tableData) {
                            if (item.accBillNo == this.tableData[index].accBillNo) {
                                this.tableData.splice(Number(index),1)
                            }
                        }
                    })
                    // 有id 的处理
                    if(itemsWithId.length != 0) {
                        fininvoicesitemsRemove(arrIds.join(',')).then(res=>{
                            this.$message.success('操作成功')
                        })
                    }
                })
            },
            // 费用明细开票匹配
            invoiceMatchingfun(){
                if (this.invoiceAmountCNY != 0 || this.invoiceAmountUSD != 0) {
                    let dataCNY = JSON.parse(JSON.stringify(this.invoiceAmountCNY))
                    let dataUSD = JSON.parse(JSON.stringify(this.invoiceAmountUSD))
                    for (let item of this.tableData) {
                        this.$refs.fininvoicesitems.$refs.tableRef.toggleRowSelection(item,false)
                        if (this.invoiceAmountCNY != 0) {
                            if (dataCNY < 0) {
                                dataCNY = 0
                            }
                            if (dataCNY > 1500) {
                                if (item.currentCurCode == 'CNY') {
                                    this.$set(item,'currentAmountCNY',1500)
                                    this.$refs.fininvoicesitems.$refs.tableRef.toggleRowSelection(item,true)
                                    dataCNY -= 1500
                                }
                            }else {
                                if (item.currentCurCode == 'CNY') {
                                    if (dataCNY != 0) {
                                        this.$refs.fininvoicesitems.$refs.tableRef.toggleRowSelection(item,true)
                                    }
                                    this.$set(item,'currentAmountCNY',dataCNY)
                                    dataCNY -= 1500
                                }
                            }
                        }
                        if (this.invoiceAmountUSD != 0) {
                            if (dataUSD < 0) {
                                dataUSD = 0
                            }
                            if (dataUSD > 1500) {
                                if (item.currentCurCode == 'USD') {
                                    this.$set(item,'currentAmountUSD',1500)
                                    this.$refs.fininvoicesitems.$refs.tableRef.toggleRowSelection(item,true)
                                    dataUSD -= 1500
                                }
                            }else {
                                if (item.currentCurCode == 'USD') {
                                    this.$set(item,'currentAmountUSD',dataUSD)
                                    if (dataUSD != 0) {
                                        this.$refs.fininvoicesitems.$refs.tableRef.toggleRowSelection(item,true)
                                    }
                                    dataUSD -= 1500
                                }
                            }
                        }
                    }
                }


            },
            // 费用明细单个删除
            detailsdeletionfun(id,index){
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(()=>{
                    if (id) {
                        fininvoicesitemsRemove(id).then(res=>{
                            this.$message.success('操作成功')
                        })
                    }
                    console.log(index,794)
                    this.tableData.splice(index,1)
                })
            },
            // 开票一键删除
            invoicingBatchDelete(){
                if (this.invoicingCheckboxData.length == 0) {
                    return this.$message.warning('请选择要删除的数据')
                }
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(()=>{
                    // 获取有id 的数据
                    const itemsWithId = this.invoicingCheckboxData.filter(item => item.hasOwnProperty('id'));
                    let arrIds = itemsWithId.map(item=>item.id) // 获取id 数据
                    // 把选中的删除掉
                    this.invoicingCheckboxData.forEach((item)=>{
                        for (let index in this.InvoicingList) {
                            if (item.id == this.InvoicingList[index].id) {
                                this.InvoicingList.splice(Number(index),1)
                            }
                        }
                    })
                    // 有id 的处理
                    if(itemsWithId.length != 0) {
                        fininvoiceitemdetailRemove(arrIds.join(',')).then(res=>{
                            this.$message.success('操作成功')
                        })
                    }
                })
            },
            // 开票明细单个删除
            invoiceDeletionfun(id,index){
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(()=>{
                    if (id) {
                        fininvoiceitemdetailRemove(id).then(res=>{
                            this.$message.success('操作成功')
                        })
                    }
                    this.InvoicingList.splice(index,1)
                })
            },
            // 下拉框的回调
            corpChange(value,name){
                // 结算单位
                if (name == 'corpCnName') {
                    if (!value) {
                        this.$set(this.form,'corpId','')
                        this.$set(this.form,'corpCnName','')
                        this.$set(this.form,'corpEnName','')
                        return
                    }
                    for(let item of this.corpData) {
                        if (item.cnName == value) {
                            this.$set(this.form,'corpId',item.id)
                            this.$set(this.form,'corpCnName',item.cnName)
                            this.$set(this.form,'corpEnName',item.enName)
                            bcorpsbankList(1,10,{pid:this.form.corpId}).then(res=>{
                                if (res.data.data.records.length != 0) {
                                    this.$set(this.form,'bankReceiptAccountNo',res.data.data.records[0].accountNo)
                                    this.$set(this.form,'bankReceiptBankName',res.data.data.records[0].accountBank)
                                }
                            })
                            // 带出开票单位数据
                            corpsinvoiceheaderList(1,20,{pid:this.form.corpId}).then(res=>{
                                if (res.data.data.records.length != 0) {
                                    this.$set(this.form,'invCorpId',res.data.data.records[0].id)
                                    this.$set(this.form,'invCorpCnName',res.data.data.records[0].invoiceHeader)
                                    this.$set(this.form,'invCorpTaxNo',res.data.data.records[0].uscc) // 税号
                                    this.$set(this.form,'invCorpAccountBankUsd',res.data.data.records[0].accountBankUsd) // 美元银行
                                    this.$set(this.form,'invCorpAccountNoUsd',res.data.data.records[0].accountNoUsd) // 美元账户
                                    this.$set(this.form,'invCorpAccountBankCny',res.data.data.records[0].accountBankUsd) // 人民币银行
                                    this.$set(this.form,'invCorpAccountNoCny',res.data.data.records[0].accountNoUsd) // 人民币账户
                                }
                            })
                        }
                    }
                }
                // 开票单位
                else if (name == 'invCorpCnName') {
                    this.$set(this.form,'invCorpAccountBankUsd','')
                    this.$set(this.form,'invCorpAccountNoUsd','')
                    this.$set(this.form,'invCorpAccountBankCny','')
                    this.$set(this.form,'invCorpAccountNoCny','')
                    if (!value) {
                        this.$set(this.form,'invCorpId','')
                        this.$set(this.form,'invCorpCnName','')
                        return
                    }
                    for(let item of this.invCorpData) {
                        if (item.id == value) {
                            this.$set(this.form,'invCorpId',item.id)
                            this.$set(this.form,'invCorpCnName',item.invoiceHeader)
                            this.$set(this.form,'invCorpTaxNo',item.uscc) // 税号
                            this.$set(this.form,'invCorpAccountBankUsd',item.accountBankUsd) // 美元银行
                            this.$set(this.form,'invCorpAccountNoUsd',item.accountNoUsd) // 美元账户
                            this.$set(this.form,'invCorpAccountBankCny',item.accountBankUsd) // 人民币银行
                            this.$set(this.form,'invCorpAccountNoCny',item.accountNoUsd) // 人民币账户
                        }
                    }
                }
                // 结算单位银行账户
                else if(name == 'bankReceiptAccountNo') {
                    for(let item of this.bankReceiptData) {
                        if (item.accountNo == value) {
                            this.$set(this.form,'bankReceiptAccountNo',item.accountNo)
                            this.$set(this.form,'bankReceiptBankName',item.accountBank)
                        }
                    }
                }
                else {
                    this.$set(this.form,name,value)
                }

            },
            // 费用明细表格多选
            handleSelectionChange(arr){
                this.handleSelectionData = arr
            },
            // 开票明细表格多选
            invoicingCheckboxChange(arr){
                this.invoicingCheckboxData = arr
            },
            // 编辑事件
            editHandle(){
                this.editSave = false
            },
            // 保存按钮事件
            editCustomer(type){
                this.$refs.form.validate((valid) => {
                    if (!valid) return
                    if (!this.form.id) {
                        // 是否选择从表数据
                        if (this.handleSelectionData.length == 0) {
                            this.$message.warning('请选择结算数据');
                            return;
                        }
                    }
                    this.form.type = '申请'
                    this.form.billNoFormat = 'FPSQ'
                    this.form.businessTypeCode = 'FPSQ'
                    this.form.businessTypes = this.form.businessTypes?this.form.businessTypes.join(','):''
                    //开票日期
                    if(this.form.invoiceDate) {
                        this.form.invoiceDate = this.form.invoiceDate.slice(0,10) + ' 00:00:00'
                    }
                    // 业务日期
                    if (this.form.accountDateFrom) {
                        this.form.accountDateFrom = this.form.accountDateFrom.slice(0,10) + ' 00:00:00'
                    }
                    if (this.form.accountDateTo) {
                        this.form.accountDateTo = this.form.accountDateTo.slice(0,10) + ' 00:00:00'
                    }
                    if (this.form.id) {
                        this.form.finInvoicesItemsList = this.form.finInvoicesItemsList.map(item=>{
                            if (item.currentCurCode == 'CNY') {
                                item.currentAmount = item.currentAmountCNY
                            }else {
                                item.currentAmount = item.currentAmountUSD
                            }
                            return item
                        })
                    }else {
                        this.form.finInvoicesItemsList = this.handleSelectionData.map(item=>{
                            if (item.currentCurCode == 'CNY') {
                                item.currentAmount = item.currentAmountCNY
                            }else {
                                item.currentAmount = item.currentAmountUSD
                            }
                            return item
                        })
                    }
                    this.form.finInvoiceItemDetailList = this.InvoicingList
                    this.saveLoading = true
                    if (type == '提交') {
                        this.$confirm("确定进行发票申请操作?", {
                            confirmButtonText: "确定",
                            cancelButtonText: "取消",
                            type: "warning"
                        }).then(()=>{
                            fininvoicesSubmit(this.form).then(res=>{
                                this.form = res.data.data
                                this.finInvoicesApprovefun()
                            })
                        }).catch(()=>{
                            this.saveLoading = false
                        })
                    }else {
                        this.fininvoicesSubmitfun(this.form)
                    }
                })
            },
            // 检索
            finstlbillslistAccBillV1fun(type){
                if (!this.form.corpId) {
                    this.$message.warning('请选择结算单位');
                    return
                }
                let obj = {}
                // //开票日期
                // if(this.form.invoiceDate) {
                //     obj.invoiceDate = this.form.invoiceDate.slice(0,10) + ' 00:00:00'
                // }
                // 业务日期
                if (this.form.accountDateFrom) {
                    obj.accountDateFrom = this.form.accountDateFrom.slice(0,10) + ' 00:00:00'
                }
                if (this.form.accountDateTo) {
                    obj.accountDateTo = this.form.accountDateTo.slice(0,10) + ' 00:00:00'
                }
                obj.type = '3'
                obj.billNo = this.form.businessNo // 业务编号
                obj.businessBillNo = this.form.billNo // 业务编号
                obj.mblno = this.form.mblno // 主单编号
                obj.hblno = this.form.hblno // 分单编号
                obj.bookingNo = this.form.bookingNo // 订舱号(BOOK NO)
                obj.curCode = this.form.curCode // 币种
                obj.businessType = this.form.businessTypes?this.form.businessTypes.join(','):'' // 业务类型
                // 判断是否有对账单号
                if (this.form.checkNo) {
                    obj.corpId = this.form.corpId // 结算单位
                    obj.checkNo = this.form.checkNo // CHK NO 对账单号
                    finstlbillsGetByDetail(obj).then(res=>{
                        let arr = res.data.data.finStlBillsItemsList.map((item,index)=>{
                            item.lineNo = Number(index) + 1 // 行号
                            item.currentCurCode = item.curCode
                            item.currentExrate = item.exrate
                            if (item.currentCurCode == 'CNY') {
                                // 本次发票金额
                                this.$set(item,'currentAmountCNY',item.appliedInvoiceCurrentAmount)
                            }else {
                                // 本次发票金额
                                this.$set(item,'currentAmountUSD',item.appliedInvoiceCurrentAmount)
                            }
                            delete item.id
                            return item
                        })
                        if (type == '追加') {
                            let a = [...this.tableData,...arr,]
                            this.tableData = a.filter((obj, index) => {
                                return a.findIndex((elem) => {
                                    return elem.accBillNo === obj.accBillNo
                                }) === index;
                            });
                        }else {
                            // 获取有id 的数据
                            const itemsWithId = this.tableData.filter(item => item.hasOwnProperty('id'));
                            let arrIds = itemsWithId.map(item=>item.id) // 获取id 数据
                            // 有id 的处理
                            if(itemsWithId.length != 0) {
                                fininvoicesitemsRemove(arrIds.join(',')).then(res=>{
                                    this.$message.success('操作成功')
                                })
                            }
                            if (arr.length == 0) {
                                this.$message.warning('当前检索暂无数据！')
                            }
                            this.tableData = arr
                        }
                    })
                }else {
                    obj.corpCnName = this.form.corpId // 结算单位
                    obj.checkBillNo = this.form.checkNo // 对账单号
                    finstlbillslistAccBillV1(obj).then(res=>{
                        let arr = res.data.data.map((item,index)=>{
                            item.lineNo = Number(index) + 1 // 行号
                            item.accBillId = item.id
                            item.accBillNo = item.billNo // JOB NO
                            item.billNo = item.businessBillNo // 账单编号
                            item.accDate = item.createTime
                            item.currentCurCode = item.curCode
                            item.currentExrate = item.exrate
                            item.dc = item.accountDc
                            if (item.currentCurCode == 'CNY') {
                                // 本次发票金额
                                this.$set(item,'currentAmountCNY',item.appliedInvoiceCurrentAmount)
                            }else {
                                // 本次发票金额
                                this.$set(item,'currentAmountUSD',item.appliedInvoiceCurrentAmount)
                            }
                            delete item.id
                            return item
                        })
                        if (type == '追加') {
                            let a = [...this.tableData,...arr,]
                            this.tableData = a.filter((obj, index) => {
                                return a.findIndex((elem) => {
                                    return elem.accBillNo === obj.accBillNo
                                }) === index;
                            });
                        }else {
                            // 获取有id 的数据
                            const itemsWithId = this.tableData.filter(item => item.hasOwnProperty('id'));
                            let arrIds = itemsWithId.map(item=>item.id) // 获取id 数据
                            // 有id 的处理
                            if(itemsWithId.length != 0) {
                                fininvoicesitemsRemove(arrIds.join(',')).then(res=>{
                                    this.$message.success('操作成功')
                                })
                            }
                            if (arr.length == 0) {
                                this.$message.warning('当前检索暂无数据！')
                            }
                            this.tableData = arr
                        }

                    })
                }
            },
            // 保存接口
            fininvoicesSubmitfun(obj){
                fininvoicesSubmit(obj).then(res=>{
                    this.saveLoading = false
                    this.$message.success('操作成功');
                    this.fininvoicesDetailfun(res.data.data.id)
                })
            },
            // 详情接口
            fininvoicesDetailfun(id){
                this.pageLoading = true
                fininvoicesDetail(id).then(res=>{
                    this.form = res.data.data
                    if (this.roleName.indexOf('admin') == -1?this.roleName.indexOf('允许修改他人业务') == -1?this.saberUserInfo.user_id != this.form.createUser:false:false) {
                        this.editPower = true
                    }else {
                        this.editPower = false
                    }
                    this.form.businessTypes = this.form.businessTypes?this.form.businessTypes.split(','):[] // 业务类型转换成数组显示
                    this.tableData = this.form.finInvoicesItemsList.map(item=>{
                        if (item.currentCurCode == 'CNY') {
                            this.$set(item,'currentAmountCNY',item.currentAmount)
                        }else {
                            this.$set(item,'currentAmountUSD',item.currentAmount)
                        }
                        return item
                    })
                    this.InvoicingList = this.form.finInvoiceItemDetailList.map(item=>{
                        item.edit = false
                        return item
                    })
                    this.pageLoading = false
                })
            },
            // 确认申请
            finInvoicesApprovefun(){
                this.pageLoading = true
                this.form.businessTypes = this.form.businessTypes?this.form.businessTypes.join(','):''
                finInvoicesApprove(this.form).then(res=>{
                    this.pageLoading = false
                    this.saveLoading = false
                    this.$message.success('操作成功');
                    this.fininvoicesDetailfun(res.data.data.id)
                    this.editSave = true // 提交之后编辑按钮显示出来
                }).catch(err=>{
                    this.pageLoading = false
                    this.saveLoading = false
                })
            },
            // 撤销申请
            revokeFinInvoicesApprovefun(){
                this.$confirm("确定进行撤销发票申请操作?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(res=>{
                    this.pageLoading = true
                    this.form.businessTypes = this.form.businessTypes?this.form.businessTypes.join(','):''
                    revokeFinInvoicesApprove(this.form).then(res=>{
                        this.pageLoading = false
                        this.$message.success('操作成功');
                        this.fininvoicesDetailfun(res.data.data.id)
                    }).catch(err=>{
                        this.pageLoading = false
                    })
                })
            },
            //返回列表
            backToList() {
                this.$emit('goBack')
            },
            // 获取客户名称数据 往来单位数据
            corpBcorpsListfun(cnName){
                getBcorpsList(1,10,{cnName}).then(res=>{
                    this.corpData = res.data.data.records
                })
            },
            // 根据往来单位选择调用获取银行数据
            bcorpsbankListfun(accountNo){
                bcorpsbankList(1,10,{
                    // curNo:this.cntyCode,
                    pid:this.form.corpId,
                    accountNo:accountNo
                }).then(res=>{
                    this.bankReceiptData = res.data.data.records
                })
            },
            // 根据往来单位选择调用获取发票抬头数据 开票单位数据
            invcorpsinvoiceheaderListfun(cnName){
                corpsinvoiceheaderList(1,20,{pid:this.form.corpId,cnName}).then(res=>{
                    this.invCorpData = res.data.data.records
                })
            },
            // 获取币别数据
            getRateListfun(cnName){
                getRateList({current:1,size:10,cnName}).then(res=>{
                    this.curData = res.data.data.records
                })
            },
            // 获取发票币别数据
            invCurCodeRateListfun(cnName){
                getRateList({current:1,size:20,cnName}).then(res=>{
                    this.invCurCodeData = res.data.data.records
                })
            },
            // 目的地
            destinationBportsListfun(enName){
                bportsList(1,10,{enName}).then(res=>{
                    this.destinationData = res.data.data.records
                })
            },
            // 卸货港
            podBportsListfun(enName){
                bportsList(1,10,{enName}).then(res=>{
                    this.podData = res.data.data.records
                })
            },
            // 装货港
            polBportsListfun(enName){
                bportsList(1,10,{enName}).then(res=>{
                    this.polData = res.data.data.records
                })
            },
            // 发票类型字典数据
            invTypeWorkDictsfun(){
                getWorkDicts('inv_type_los').then(res=>{
                    this.invTypeData = res.data.data;
                })
            },
            serverWorkDictsfun(){
                getWorkDicts('Invoice_information_los').then(res=>{
                    this.serverData = res.data.data;
                })
            },
            // 预览报表
            handleReportPreview(url,data){
                console.log(url,1670)
                console.log(data,1671)
                Stimulsoft.Base.StiLicense.key = '6vJhGtLLLz2GNviWmUTrhSqnOItdDwjBylQzQcAOiHn0s4gy0Fr5YoUZ9V00Y0igCSFQzwEqYBh/N77k4f0fWXTHW5rqeBNLkaurJDenJ9o97TyqHs9HfvINK18Uwzsc/bG01Rq+x3H3Rf+g7AY92gvWmp7VA2Uxa30Q97f61siWz2dE5kdBVcCnSFzC6awE74JzDcJMj8OuxplqB1CYcpoPcOjKy1PiATlC3UsBaLEXsok1xxtRMQ283r282tkh8XQitsxtTczAJBxijuJNfziYhci2jResWXK51ygOOEbVAxmpflujkJ8oEVHkOA/CjX6bGx05pNZ6oSIu9H8deF94MyqIwcdeirCe60GbIQByQtLimfxbIZnO35X3fs/94av0ODfELqrQEpLrpU6FNeHttvlMc5UVrT4K+8lPbqR8Hq0PFWmFrbVIYSi7tAVFMMe2D1C59NWyLu3AkrD3No7YhLVh7LV0Tttr/8FrcZ8xirBPcMZCIGrRIesrHxOsZH2V8t/t0GXCnLLAWX+TNvdNXkB8cF2y9ZXf1enI064yE5dwMs2fQ0yOUG/xornE'
                // Stimulsoft.Base.StiLicense.Key = '6vJhGtLLLz2GNviWmUTrhSqnOItdDwjBylQzQcAOiHkcgIvwL0jnpsDqRpWg5FI5kt2G7A0tYIcUygBh1sPs7plofUOqPB1a4HBIXJB621mau2oiAIj+ysU7gKUXfjn/D5BocmduNB+ZMiDGPxFrAp3PoD0nYNkkWh8r7gBZ1v/JZSXGE3bQDrCQCNSy6mgby+iFAMV8/PuZ1z77U+Xz3fkpbm6MYQXYp3cQooLGLUti7k1TFWrnawT0iEEDJ2iRcU9wLqn2g9UiWesEZtKwI/UmEI2T7nv5NbgV+CHguu6QU4WWzFpIgW+3LUnKCT/vCDY+ymzgycw9A9+HFSzARiPzgOaAuQYrFDpzhXV+ZeX31AxWlnzjDWqpfluygSNPtGul5gyNt2CEoJD1Yom0VN9fvRonYsMsimkFFx2AwyVpPcs+JfVBtpPbTcZscnzUdmiIvxv8Gcin6sNSibM6in/uUKFt3bVgW/XeMYa7MLGF53kvBSwi78poUDigA2n12SmghLR0AHxyEDIgZGOTbNI33GWu7ZsPBeUdGu55R8w='
                Stimulsoft.Base.Localization.StiLocalization.addLocalizationFile( '/reports/stimulsoft/Localization/zh-CHS.xml', true, 'zh-CHS')
                Stimulsoft.Base.Localization.StiLocalization.setLocalizationFile('/reports/stimulsoft/Localization/zh-CHS.xml' )
                // 工具栏
                var options = new Stimulsoft.Viewer.StiViewerOptions()
                options.height = '100%'
                options.appearance.scrollbarsMode = true // 滚动条模式
                options.toolbar.showDesignButton = false // 显示设计按钮
                options.toolbar.showAboutButton = false // 显示关于按钮
                options.toolbar.showResourcesButton = false // 显示资源按钮
                options.toolbar.showFullScreenButton = false // 显示全屏按钮
                options.toolbar.showOpenButton = false // 显示打开按钮
                options.appearance.showTooltips = false // 显示工具提示
                options.appearance.showDialogsHelp = false // 显示对话框帮助
                options.exports.showExportToDocument = false // 显示导出到文档
                options.toolbar.showParametersButton = true // 显示参数按钮
                options.appearance.bookmarksPrint = true // 书签打印
                // options.toolbar.showPrintButton = false // 打印按钮是否显示   下面直接自定义控制打印弹窗是否开启

                // printDestination 参数：用于指定报表打印的目标位置，可以是打印机、PDF 文件或者直接打印到浏览器等。
                // Stimulsoft.Viewer.StiPrintDestination.Direct：表示直接打印到打印机，即将报表内容直接发送至打印机进行打印。
                // 通过设置不同的 printDestination 参数，你可以控制报表打印的行为，例如是直接打印到打印机，还是生成 PDF 文件，或者直接在浏览器中预览打印内容等。
                options.toolbar.printDestination = Stimulsoft.Viewer.StiPrintDestination.Direct
                // htmlRenderMode html渲染模式
                options.appearance.htmlRenderMode = Stimulsoft.Report.Export.StiHtmlExportMode.Table
                // 是创建一个 Stimulsoft 报表查看器的实例的代码
                let viewer = new Stimulsoft.Viewer.StiViewer(options, 'StiViewer', false)

                // 报表
                console.log("创建一个报表实例");
                console.log()
                let report = new window.Stimulsoft.Report.StiReport();

                // 加载文件
                console.log("从url加载报表");
                // report.loadFile("/reports/stimulsoft/demos/SimpleList.mrt");
                report.load(url)

                data.pageOne = 'Page : 1 of 1'
                // 处理超长数据
                if (data.hshipperDetails) {
                    var consignerIndex2 = data.hshipperDetails.indexOf( '\n' )
                    for (let i = 0; i < 4; i++) {
                        consignerIndex2 = data.hshipperDetails.indexOf( '\n', consignerIndex2 + 1 );
                    }
                    if (consignerIndex2 != -1) {
                        var hshipperDetails = data.hshipperDetails.substring(consignerIndex2 + 2, data.hshipperDetails.length)
                        data.hshipperDetails = data.hshipperDetails.substring(0, consignerIndex2) + ' *'
                        data.commodityDescr += '\n*' + hshipperDetails
                    }
                }

                if (data.hconsigneeDetails) {
                    var consigneeIndex2 = data.hconsigneeDetails.indexOf( '\n' )
                    for (let i = 0; i < 3; i++) {
                        consigneeIndex2 = data.hconsigneeDetails.indexOf( '\n', consigneeIndex2 + 1 );
                    }
                    if (consigneeIndex2 != -1) {
                        var hconsigneeDetails = data.hconsigneeDetails.substring(consigneeIndex2 + 2, data.hconsigneeDetails.length)
                        data.hconsigneeDetails = data.hconsigneeDetails.substring(0, consigneeIndex2) + ' **'
                        data.commodityDescr += '\n**' + hconsigneeDetails
                    }
                }

                if (data.hnotifyDetails) {
                    var notifierIndex2 = data.hnotifyDetails.indexOf( '\n' )
                    for (let i = 0; i < 3; i++) {
                        notifierIndex2 = data.hnotifyDetails.indexOf( '\n', notifierIndex2 + 1 );
                    }
                    if (notifierIndex2 != -1) {
                        var hnotifyDetails = data.hnotifyDetails.substring(notifierIndex2 + 2, data.hnotifyDetails.length)
                        data.hnotifyDetails = data.hnotifyDetails.substring(0, notifierIndex2) + ' ***'
                        data.commodityDescr += '\n***' + hnotifyDetails
                    }
                }

                // 处理箱号
                if (this.isPrintTheBoxNumber) {
                    data.commodityDescr += '\n.\n.\n'
                }

                // PLACE & DATE OF ISSUE
                data.placeAndDateOfIssue = ''
                if (data.issueAt) {
                    data.placeAndDateOfIssue += data.issueAt
                }
                if (data.issueDate) {
                    let date = new Date(data.issueDate.replace(/-/g,'/'));
                    let yyyy = date.getFullYear();
                    let mmmm = date.toDateString().split(" ")[1]
                    let dd = date.getDate()
                    data.placeAndDateOfIssue += ', ' + dd + '-' + mmmm + '-' + yyyy
                }

                // Total number of containers or packages received by the Carriers
                if (data.preContainersList) {
                    let boxMap = new Map();
                    for (let boxQuantity of data.preContainersList) {
                        if (boxMap.get(boxQuantity.cntrTypeCode)) {
                            let v = boxMap.get(boxQuantity.cntrTypeCode)
                            boxMap.set(boxQuantity.cntrTypeCode, v + boxQuantity.quantity)
                        } else {
                            boxMap.set(boxQuantity.cntrTypeCode, boxQuantity.quantity)
                        }
                    }
                    let boxs = ''
                    boxMap.forEach(function (value, key, map) {
                        boxs += value + 'x' + key + ', '
                    })
                    boxs = boxs.substring(0, boxs.length - 2)

                    data.boxQuantity = boxs + ' CONTAINER(S) ONLY'
                }

                // Number of original B/Ls
                if (data.numberOfObl) {
                    data.numberOfObl += ' (' + data.numberOfOblDigit + ')'
                }

                if (data.commodityDescr) {
                    var descriptionIndex2 = data.commodityDescr.indexOf( '\n' )
                    for (let i = 0; i < 19; i++) {
                        descriptionIndex2 = data.commodityDescr.indexOf( '\n', descriptionIndex2 + 1 );
                    }
                    if (descriptionIndex2 != -1) {
                        data.pageOne = 'Page : 1 of 2'
                        data.pageTwo = 'Page : 2 of 2'
                        var extraLongText = data.commodityDescr.substring(descriptionIndex2 + 2, data.commodityDescr.length)
                        data.commodityDescr = data.commodityDescr.substring(0, descriptionIndex2)
                        data.extraLongTips = '** TO BE CONTINUED ON ATTACHED LIST **'
                        data.extraLongText = extraLongText
                    }
                }

                // console.log(data.hshipperDetails, 'hshipperDetails2')

                // 创建一个 Stimulsoft 数据集（DataSet）的实例的代码
                var dataSet = new Stimulsoft.System.Data.DataSet(
                    'reportData'
                )

                dataSet.readJson(data) // 用于将 JSON 格式的数据加载到数据集中。data 是包含报表数据的 JSON 对象。
                // 这是一个方法调用，用于在报表中注册数据源。参数 'reportData' 是数据源的名称，
                // 第二个 'reportData' 是数据源的别名，dataSet 则是之前创建的数据集实例
                report.regData('reportData', 'reportData', dataSet)
                // 从模版和数据加载报表
                // loadReport(report, '', {})

                // 这是将报表对象指定给报表查看器的属性。viewer 是报表查看器的实例，而 report 是之前创建的报表对象。
                viewer.report = report;

                this.$refs.reportContainer.showContainer(
                    ()=> {
                        setTimeout(() => {
                            viewer.renderHtml('reportContainer')
                            this.createViewerButtons(viewer)
                        }, 50)
                    },
                    ()=>{
                    },
                )
                console.log("加载成功完成!");
            },
            createViewerButtons (viewer){
                viewer.jsObject.collections.images['myClose.png'] =
                    'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAA0ElEQVQ4ja3TO05CQRQG4A8iOwAbtYWETndAaecK7NwCKmETtJZsSBNLobEz8ZFIJQ0UnOGSm3DnYviTybzO/895DQXGWGCVGQuMEqkRcwcfuMOLalziCaf4TIe9UG9nyMJmFRzNGoRK1BU4xxx9G7cfwostciGk+x8MqgySwDXe4tU53hVV+MNtTmAoX84JGv9NYgrHyR6DV8wUSW7hItZLm36ZVoVQxsFJLOMsPOrH/h7dQwR2cdxOTEn8DtUbPGc4V2H7Vb4Yqfedf/GYSGt8VUmxgyfuBAAAAABJRU5ErkJggg=='
                const closeBtn = viewer.jsObject.SmallButton(
                    'closeBtn',
                    '关闭',
                    'myClose.png'
                )
                // 增加打印弹窗配置
                const printBtn = viewer.jsObject.SmallButton(
                    'printBtn',
                    '打印报表',
                    'myClose.png'
                )
                // console.log(viewer.jsObject.print(),'1013')
                // 获取 关闭按钮的dom元素位置
                const toolbarTable = viewer.jsObject.controls.toolbar.firstChild.firstChild
                const buttonsTable = toolbarTable.rows[0].lastChild.lastChild
                const userButtonCell = buttonsTable.rows[0].insertCell(0)
                // 获取打印按钮的位置
                const buttonsTablePrint = toolbarTable.rows[0].childNodes[0].lastChild // 打印按钮
                const userButtonPrint = buttonsTablePrint.rows[0].childNodes[0] // 打印按钮dom位置


                userButtonPrint.addEventListener("click", (event)=>{
                    console.log("打印点击");
                    // event.preventDefault()
                });
                userButtonPrint.addEventListener("mouseover", (event) => {
                    console.log("移入打印按钮");
                    console.log(event,1035)

                });

                userButtonCell.className = 'stiJsViewerClearAllStyles'
                userButtonCell.appendChild(closeBtn) // 添加关闭节点

                // userButtonPrint.prepend(printBtn) // 在 printBtn 节点里最前面增加一个子级节点


                let that=this
                // 关闭按钮的监听点击
                closeBtn.action = function() {
                    console.log(that.$refs.ReportContainer,'1022')
                    if (that.$refs.reportContainer)
                        that.$refs.reportContainer.hideContainer()
                }

                // // // 打印按钮监听
                // printBtn.action = (e)=>{
                //     console.log('打印')
                //     window.print()
                // }

            },



        },
    }
</script>

<style scoped>
::v-deep.el-form-item {
    margin-bottom: 0;
}
.cardBox {
    background: #fff;
    width: 100%;
    height: 100%;
    padding: 20px;
    box-sizing: border-box;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}
.flexBox {
    display: flex;
}
.flexBoxLeft {
    flex: 2;
    margin-right: 10px;
    //padding-bottom: 40px;
}
.flexBoxRight {
    flex: 3;
    //padding-bottom: 40px;
}
</style>
