<template>
    <div>
        <el-card :body-style="cardBodyStyle">
            <el-form :inline="true" :model="query">
                <el-row style="margin-bottom: 5px;">
                    <el-col :span="5">
                        <el-form-item label="结算单号" style="margin-bottom: 0;">
                            <el-input v-model="query.accountNo" placeholder="" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="合同号" style="margin-bottom: 0;">
                            <el-input v-model="query.contrNo" placeholder="" clearable>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="对方合同号" style="margin-bottom: 0;">
                            <el-input v-model="query.khContrNo" placeholder="" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="供应商名称" style="margin-bottom: 0;">
                            <el-input v-model="query.tradePartnerName" placeholder="" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <ButtonBar @search="handleSearch" @add="handleAdd"></ButtonBar>

        <el-card :body-style="cardBodyStyle">
            <el-tabs v-model="activeNameTop" type="border-card">
                <el-tab-pane label="结算头" name="master">
                    <el-table :data="tableData" border highlight-current-row @row-click="DoubleClick">
                        <el-table-column type="selection" fixed></el-table-column>
                        <el-table-column type="index" label="序号" align="center" width="60" fixed>
                            <template #default="scope">
                                <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column v-if="true" prop="accountNo" label="结算单号" width="200" header-align="center"
                            align="center" show-overflow-tooltip fixed>
                        </el-table-column>
                        <el-table-column v-if="true" prop="contrNo" label="合同号" width="150" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="khContrNo" label="对方合同号" width="150" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="tradePartnerCode" label="供应商编号" width="150"
                            header-align="center" align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="tradePartnerName" label="供应商名称" width="250"
                            header-align="center" align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="invoiceNo" label="发票编号" width="200" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="invoiceNum" label="发票号码" width="150" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="invoiceCnt" label="发票张数" width="100" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="invoiceDate" label="发票日期" width="120" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="invoiceAmount" label="发票金额" width="120" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="transportMth" label="运输方式" width="100" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="payMth" label="付款方式" width="100" header-align="center"
                            align="center" show-overflow-tooltip :formatter="formatter">
                        </el-table-column>
                        <el-table-column v-if="true" prop="actBasis" label="结算依据" width="100" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="actMth" label="结算方式" width="120" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="actQty" label="结算数量" width="120" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="totalAmountExcludeTax" label="不含税金额合计" width="150"
                            header-align="center" align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="taxRate" label="税率" width="80" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="taxRateCal" label="计算税率" width="100" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="glDateBegin" label="结算起止日期" width="220" header-align="center"
                            align="center" show-overflow-tooltip :formatter="formatter">
                        </el-table-column>
                        <el-table-column v-if="true" prop="transactionDate" label="入账日期" width="150" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="payAmount" label="已付金额" width="100" header-align="center"
                            align="center" show-overflow-tooltip :formatter="formatter">
                        </el-table-column>
                        <el-table-column v-if="true" prop="payFlag" label="是否生成付款单" width="150" header-align="center"
                            align="center" show-overflow-tooltip :formatter="formatter">
                        </el-table-column>
                        <el-table-column v-if="true" prop="workModel.flowStatusName" label="流程状态" width="120"
                            header-align="center" align="center" show-overflow-tooltip>
                            <template #default="{ row }">
                                <div>
                                    <el-tag v-if="row.workId !== undefined && row.workModel.flowStatus === '110'">{{
                                        row.workModel.flowStatusName }}</el-tag>
                                    <el-tag type="success"
                                        v-else-if="row.workId !== undefined && row.workModel.flowStatus === '170'">{{
                                            row.workModel.flowStatusName }}</el-tag>
                                    <el-tag type="danger"
                                        v-else-if="row.workId !== undefined && (row.workModel.flowStatus === '130' || row.workModel.flowStatus === '180' || row.workModel.flowStatus === '190')">{{
                                            row.workModel.flowStatusName }}</el-tag>
                                    <el-tag type="warning" v-else>'---'</el-tag>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" header-align="center" align="center" width="300px" fixed="right">
                            <template #default="{ row }">
                                <el-button plain type="warning" @click="handleEdit(row)"
                                    v-if="row.workId === '' || row.workModel.opType === '1'">编辑
                                </el-button>
                                <el-button plain type="danger" @click="handleDelete(row)"
                                    v-if="row.workId === '' || row.workModel.opType === '1'">删除
                                </el-button>
                                <el-button plain type="danger" @click="handleCancelAct(row)"
                                    v-if="row.workId !== '' && row.workModel.flowStatus === '170' && row.payFlag != '1'">取消结算
                                </el-button>
                                <el-button plain type="success" @click="handleSubmit(row)"
                                    v-if="row.workId === '' || row.workModel.opType === '1'">发起
                                </el-button>
                                <el-button plain type="primary" @click="handleDetail(row)"
                                    v-if="row.workId !== ''">详情</el-button>
                                <el-button plain type="info" @click="handleCancel(row)"
                                    v-if="row.workId !== '' && row.workModel.opType !== '1' && row.workModel.flowStatus !== '170'">撤回</el-button>
                                <el-button plain type="info" @click="handlePrintPreview(row)"
                                    v-if="row.workId !== '' && row.workModel.flowStatus === '170'">打印
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>

        <el-card :body-style="cardBodyStyle">
            <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="pageSizes" :total="totalRows"
                background="background" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                @current-change="handleCurrentChange">
            </el-pagination>
        </el-card>

        <el-card :body-style="cardBodyStyle">
            <el-tabs v-model="activeNameBottom" type="border-card">
                <el-tab-pane label="结算行" name="first">
                    <el-table :data="tableDataLine" border highlight-current-row>
                        <!-- <el-table-column type="selection" fixed></el-table-column> -->
                        <el-table-column type="index" label="序号" align="center" width="60" fixed>
                            <template #default="scope">
                                <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column v-if="true" prop="accountNo" label="结算单号" width="200" header-align="center"
                            align="center" show-overflow-tooltip fixed>
                        </el-table-column>
                        <el-table-column v-if="true" prop="accountLine" label="结算单行号" width="100" header-align="center"
                            align="center" show-overflow-tooltip fixed>
                        </el-table-column>
                        <el-table-column v-if="true" prop="itemCd" label="物料编码" width="150" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="itemNm" label="物料名称" width="100" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="quantityInvoiced" label="发票匹配接收数量(对应入库量)" width="250"
                            header-align="center" align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="quantityAccount" label="结算量" width="100"
                            header-align="center" align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="unit" label="计量单位" width="100" header-align="center"
                            align="center" show-overflow-tooltip :formatter="formatter">
                        </el-table-column>
                        <el-table-column v-if="true" prop="unitPrice" label="单价" width="150" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="amount" label="行金额" width="150" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="unitTaxPrice" label="含税单价" width="150" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="taxAmount" label="行含税金额" width="150" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="purOrdNo" label="订单号" width="200" header-align="center"
                            align="center" show-true-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="purOrdLn" label="订单行号" width="100" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="billNo" label="对账单号" width="100" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="billLine" label="对账单行号" width="150" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="true" prop="contractNo" label="合同号" width="200" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column v-if="false" prop="taxRate" label="税率" width="100" header-align="center"
                            align="center" show-overflow-tooltip :formatter="formatter">
                        </el-table-column>
                        <el-table-column v-if="true" prop="description" label="备注" width="120" header-align="center"
                            align="center" show-overflow-tooltip>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>

        <el-card :body-style="cardBodyStyle">
            <el-pagination :current-page="currentPageLine" :page-size="pageSizeLine" :page-sizes="pageSizesLine"
                :total="totalRowsLine" background="background" layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChangeLine" @current-change="handleCurrentChangeLine">
            </el-pagination>
        </el-card>

        <el-dialog fullscreen class="diaClass" :close-on-click-modal="false" draggable :title="title"
            v-model="dialogVisible" @open="openDialog">
            <el-card class="box-card">
                <template #header>
                    <el-button type="primary" plain @click="handleBill" :disabled="form.id">查询</el-button>
                    <!-- <el-button type="success" plain @click="handleSave(ruleFormRef)">保存</el-button> -->
                </template>

                <el-form :model="form" label-width="110px" label-position="right" inline ref="ruleFormRef"
                    :rules="rules">
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="结算单号">
                                <el-input v-model="form.accountNo" clearable style="width: 220px" disabled></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="合同号" prop="contrNo">
                                <el-input v-model="form.contrNo" clearable style="width: 220px" disabled></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="对方合同号">
                                <el-input v-model="form.khContrNo" clearable style="width: 220px" disabled></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="供应商名称" prop="tradePartnerName">
                                <el-input v-model="form.tradePartnerName" clearable style="width: 220px"
                                    disabled></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="供应商编号">
                                <el-input v-model="form.tradePartnerCode" clearable style="width: 220px"
                                    disabled></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="发票编号">
                                <el-input v-model="form.invoiceNo" clearable style="width: 220px" disabled></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="发票号码" prop="invoiceNum">
                                <el-input v-model="form.invoiceNum" clearable style="width: 220px"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="发票张数" prop="invoiceCnt">
                                <el-input v-model="form.invoiceCnt" clearable style="width: 220px"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="发票日期" prop="invoiceDate">
                                <el-date-picker v-model="form.invoiceDate" type="date" style="width: 220px;"
                                    value-format="YYYY-MM-DD" format="YYYY-MM-DD"></el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="发票金额" prop="invoiceAmount">
                                <el-input-number v-model="form.invoiceAmount" :precision="2" :step="0.1"
                                    controls-position="right" clearable style="width: 220px"></el-input-number>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="合同单价">
                                <el-input v-model="form.contrPrice" clearable style="width: 220px"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="合同含税单价">
                                <el-input v-model="form.contrTaxPrice" clearable style="width: 220px"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="运输方式">
                                <el-select v-model="form.transportMth" placeholder="请选择" clearable style="width: 220px">
                                    <el-option key="汽运自提" label="汽运自提" value="汽运自提" />
                                    <el-option key="送货到厂" label="送货到厂" value="送货到厂" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="付款方式">
                                <el-select v-model="form.payMth" placeholder="请选择" clearable style="width: 220px">
                                    <el-option v-for="item in dicList.COM_PAY_MTH" :key="item.dicCode"
                                        :label="item.dicName" :value="item.dicCode" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="结算依据">
                                <el-select v-model="form.actBasis" placeholder="请选择" clearable style="width: 220px">
                                    <el-option key="手动输入" label="手动输入" value="手动输入" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="结算方式">
                                <el-select v-model="form.actMth" placeholder="请选择" clearable style="width: 220px">
                                    <el-option key="分批办理" label="分批办理" value="分批办理" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="结算数量">
                                <el-input-number v-model="form.actQty" :precision="2" :step="0.1"
                                    controls-position="right" clearable style="width: 220px" disabled></el-input-number>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="不含税金额合计">
                                <el-input-number v-model="form.totalAmountExcludeTax" :precision="2" :step="0.1"
                                    controls-position="right" clearable style="width: 220px" disabled></el-input-number>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="税率" prop="taxRate">
                                <el-select v-model="form.taxRate" placeholder="请选择" clearable style="width: 220px">
                                    <el-option v-for="item in dicList.TAX_RATE" :key="item.dicCode"
                                        :label="item.dicName" :value="item.dicCode" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="计算税率">
                                <el-input-number v-model="form.taxRateCal" style="width: 220px" :precision="2"
                                    :step="0.1" controls-position="right" disabled></el-input-number>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="税额">
                                <el-input-number v-model="form.tax" :precision="2" :step="0.1" controls-position="right"
                                    clearable style="width: 220px" disabled></el-input-number>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="起止日期">
                                <el-date-picker v-model="glDate" type="daterange" style="max-width: 200px"
                                    value-format="YYYY-MM-DD" format="YYYY-MM-DD"></el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="入账日期">
                                <el-date-picker v-model="form.transactionDate" type="date" style="max-width: 220px"
                                    value-format="YYYY-MM-DD" format="YYYY-MM-DD"></el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="18">
                            <el-form-item label="备注">
                                <el-input type="textarea" v-model="form.description" clearable
                                    style="width: 940px"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-card>

            <el-card class="box-card" v-if="true" style="margin-top: 10px;">
                <el-table :data="tableDataLine" border highlight-current-row>
                    <!-- <el-table-column type="selection" fixed></el-table-column> -->
                    <el-table-column type="index" label="序号" align="center" width="60" fixed>
                        <template #default="scope">
                            <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column v-if="true" prop="accountNo" label="结算单号" width="200" header-align="center"
                        align="center" show-overflow-tooltip fixed>
                    </el-table-column>
                    <el-table-column v-if="true" prop="accountLine" label="结算单行号" width="100" header-align="center"
                        align="center" show-overflow-tooltip fixed>
                    </el-table-column>
                    <el-table-column v-if="true" prop="itemCd" label="物料编码" width="150" header-align="center"
                        align="center" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column v-if="true" prop="itemNm" label="物料名称" width="100" header-align="center"
                        align="center" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column v-if="true" prop="quantityInvoiced" label="发票匹配接收数量(对应入库量)" width="250"
                        header-align="center" align="center" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column v-if="true" prop="quantityAccount" label="结算量" width="100" header-align="center"
                        align="center" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column v-if="true" prop="unit" label="计量单位" width="100" header-align="center"
                        align="center" show-overflow-tooltip :formatter="formatter">
                    </el-table-column>
                    <el-table-column v-if="true" prop="unitPrice" label="单价" width="150" header-align="center"
                        align="center" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column v-if="true" prop="amount" label="行金额" width="150" header-align="center"
                        align="center" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column v-if="true" prop="unitTaxPrice" label="含税单价" width="150" header-align="center"
                        align="center" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column v-if="true" prop="taxAmount" label="行含税金额" width="150" header-align="center"
                        align="center" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column v-if="true" prop="purOrdNo" label="订单号" width="200" header-align="center"
                        align="center" show-true-tooltip>
                    </el-table-column>
                    <el-table-column v-if="true" prop="purOrdLn" label="订单行号" width="100" header-align="center"
                        align="center" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column v-if="true" prop="billNo" label="对账单号" width="100" header-align="center"
                        align="center" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column v-if="true" prop="billLine" label="对账单行号" width="150" header-align="center"
                        align="center" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column v-if="true" prop="contractNo" label="合同号" width="200" header-align="center"
                        align="center" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column v-if="false" prop="taxRate" label="税率" width="100" header-align="center"
                        align="center" show-overflow-tooltip :formatter="formatter">
                    </el-table-column>
                    <el-table-column v-if="true" prop="description" label="备注" width="120" header-align="center"
                        align="center" show-overflow-tooltip>
                    </el-table-column>
                </el-table>
            </el-card>
            <template #footer>
                <div class="dialog-footer">
                    <el-button plain type="success" @click="handleSave(ruleFormRef)">保存</el-button>
                    <el-button plain type="danger" @click="handleCancelSave">取消</el-button>
                    <!-- <el-button plain type="info" @click="handleCancelSave">关闭</el-button> -->
                </div>
            </template>
        </el-dialog>
    </div>

    <PopupBillConfirm ref="PopupRefBill" @receive-from-child="retuBill"></PopupBillConfirm>
</template>

<script setup>
import ButtonBar from '@/components/ButtonBar.vue'
import PopupBillConfirm from '@/views/pur/components/PopupBillConfirm.vue'

import {
    ref,
    reactive,
    onMounted,
    getCurrentInstance
} from 'vue'

const {
    proxy
} = getCurrentInstance()

import tools from '@/tools'
import { workflowSubmit, workflowCancel } from "@/tools/workflow.js"

const cardBodyStyle = ref(tools.style.card)
const inputStyle = ref(tools.style.input)

onMounted(() => {
    handleSearch()
    getDictList()
})

/**
 * 查询公司代码
 */
const userId = window.localStorage.getItem('userId')
const userCode = window.localStorage.getItem('userCode')
const userName = window.localStorage.getItem('userDesc')
const dept = JSON.parse(window.localStorage.getItem('dept'))
const deptTree = JSON.parse(window.localStorage.getItem('deptTree'))
/**
 * 查询公司代码
 */


/**
 *  查询字典
 */
const dicList = ref({
    COM_PAY_MTH: [],
    TAX_RATE: [],
    MEASURING_UNIT: []
})
const getDictList = () => {
    var url = 'framework/Common/querySelectorList'
    var param = {
        type: JSON.stringify(['COM_PAY_MTH', 'TAX_RATE', 'MEASURING_UNIT'])
    }
    proxy.$axios.get(url, param).then(response => {
        if (response.data.code == '0') {
            dicList.value = response.data.data
        } else {
            ElMessage.error('操作失败！' + response.data.msg)
        }
    })
}
const formatter = (row, column, cellValue, index) => {
    if (!cellValue || cellValue == null || cellValue == '') {
        return cellValue
    }
    switch (column.property) {
        case 'payMth':
            cellValue = dicList.value.COM_PAY_MTH.find(item => item.dicCode == cellValue)?.dicName
            break
        case 'taxRate':
            cellValue = dicList.value.TAX_RATE.find(item => item.dicCode == cellValue)?.dicName
            break
        case 'unit':
            cellValue = dicList.value.MEASURING_UNIT.find(item => item.dicCode == cellValue)?.dicName
            break
        case 'glDateBegin':
            cellValue = row.glDateBegin + ' 至 ' + row.glDateEnd
            break
        case 'payFlag':
            cellValue = cellValue === '1' ? '是' : '否'
            break
    }
    return cellValue
}
/**
 *  查询字典
 */


/**
 *   查询  -- 结算头
 */
const query = ref({
    accountNo: '',
    contrNo: '',
    khContrNo: '',
    tradePartnerName: '',
})
const activeNameTop = ref('master')
const tableData = ref([])
const handleSearch = () => {
    tableDataLine.value = []
    tableDataLine.value = []
    currentPage.value = 1
    getTableData()
}

const getTableData = () => {
    var url = 'pur/ActHead/query'
    var param = {
        page: currentPage.value,
        rows: pageSize.value,
        params: JSON.stringify(query.value)
    }
    proxy.$axios.get(url, param).then(response => {
        if (response.data.code == '0') {
            tableData.value = response.data.data.records
            totalRows.value = response.data.data.total
        } else {
            ElMessage.error('操作失败！' + response.data.msg)
        }
    })
}
/**
 *   查询
 */

/**
 * 分页
 */
const currentPage = ref(1)
const totalRows = ref(0)
const pageSizes = ref([5, 10, 20, 30, 40])
const pageSize = ref(5)
const handleSizeChange = (val) => {
    pageSize.value = val
    getTableData()
}
const handleCurrentChange = (val) => {
    currentPage.value = val
    getTableData()
}
/**
 * 分页
 */


/**
 * 新增
 */
const title = ref('')
const dialogVisible = ref(false)
const form = ref({
    compCd: '',
    compNm: '',
    accountNo: '',
    tradePartnerCode: '',
    tradePartnerName: '',
    tradePartnerId: '',
    invoiceNo: '',
    invoiceCnt: '',
    invoiceType: '',
    invoiceDate: '',
    invoiceAmount: null,
    invoiceCurrency: '',
    exchangeRate: '',
    exchangeDate: '',
    description: '',
    glDateBegin: '',
    glDateEnd: '',
    totalAmountExcludeTax: null,
    contrNo: '',
    khContrNo: '',
    invoiceNum: '',
    taxRateCode: '',
    taxRateCal: null,
    tax: null,
    taxRate: '',
    transportMth: '',
    payMth: '',
    actBasis: '',
    actMth: '',
    actQty: null,
    contrPrice: '',
    contrTaxPrice: '',
    addId: '',
    addCode: '',
    addName: '',
    addDeptId: '',
    addDeptCode: '',
    addDeptName: '',
    addTime: '',
    modifyCode: '',
    modifyName: '',
})
const ruleFormRef = ref()
const rules = reactive({
    contrNo: [{
        required: true,
        message: '请输入合同号',
        trigger: 'change' | 'blur'
    }],
    tradePartnerName: [{
        required: true,
        message: '请输入供应商名称',
        trigger: 'change' | 'blur'
    }],
    invoiceNum: [{
        required: true,
        message: '请输入发票号码',
        trigger: 'change' | 'blur'
    }],
    invoiceCnt: [{
        required: true,
        message: '请输入发票张数',
        trigger: 'change' | 'blur'
    }],
    invoiceDate: [{
        required: true,
        message: '请输入发票日期',
        trigger: 'change' | 'blur'
    }],
    invoiceAmount: [{
        required: true,
        message: '请输入发票金额',
        trigger: 'change' | 'blur'
    }],
    taxRate: [{
        required: true,
        message: '请输入税率',
        trigger: 'change' | 'blur'
    }],
})

const handleAdd = () => {
    if (window.localStorage.getItem('deptTree') == JSON.stringify(new Array())) {
        ElMessage({
            type: 'warning',
            message: '请添加登录人所在公司'
        })
        return
    }

    form.value = {
        compCd: deptTree[0].deptCode,
        compNm: deptTree[0].deptName,
        accountNo: '',
        tradePartnerCode: '',
        tradePartnerName: '',
        tradePartnerId: '',
        invoiceNo: '',
        invoiceCnt: '',
        invoiceType: '',
        invoiceDate: '',
        invoiceAmount: null,
        invoiceCurrency: '',
        exchangeRate: '',
        exchangeDate: '',
        description: '',
        glDateBegin: '',
        glDateEnd: '',
        totalAmountExcludeTax: null,
        contrNo: '',
        khContrNo: '',
        invoiceNum: '',
        taxRateCode: '',
        taxRateCal: null,
        tax: null,
        taxRate: '',
        transportMth: '', // 汽运自提
        payMth: '',
        actBasis: '', // 手动输入
        actMth: '', // 分批办理
        actQty: null,
        contrPrice: '',
        addId: userId,
        addCode: userCode,
        addName: userName,
        addDeptId: dept[0].id,
        addDeptCode: dept[0].deptCode,
        addDeptName: dept[0].deptName,
        addTime: '',
        modifyCode: '',
        modifyName: '',
    }
    glDate.value = []

    if (ruleFormRef.value) {
        ruleFormRef.value.resetFields();
    }
    tableDataLine.value = []
    title.value = '新增'
    dialogVisible.value = true
}
/**
 * 新增
 */


/**
 * 保存、修改、删除
 */

const openDialog = () => {
}

const glDate = ref([])
const handleSave = (ruleFormRef) => {
    form.value.glDateEnd = glDate.value[1]
    form.value.glDateBegin = glDate.value[0]


    ruleFormRef.validate((valid, fields) => {
        if (valid) {
            var url = 'pur/ActHead/save'
            var param = {
                json: JSON.stringify(form.value),
                json1: JSON.stringify(billLines.value),
            }
            proxy.$axios.post(url, param).then(response => {
                if (response.data.code == 0) {
                    ElMessage({
                        message: '保存成功',
                        type: 'success',
                    })
                    form.value = response.data.data
                    queryLine.value.accountNo = form.value.accountNo
                    getTableDataLine()
                    getTableData()
                    // dialogVisible.value = false
                } else {
                    ElMessage({
                        message: '操作失败' + response.data.msg,
                        type: 'error'
                    })
                }
            })

        } else {
            console.log('error submit!', fields)
        }
    })
}
const handleCancelSave = () => {
    dialogVisible.value = false
}
const handleEdit = (row) => {

    if (ruleFormRef.value) {
        ruleFormRef.value.resetFields();
    }
    title.value = '编辑'
    form.value = { ...row }
    form.value.modifyCode = userCode
    form.value.modifyName = userName
    glDate.value.push(form.value.glDateBegin)
    glDate.value.push(form.value.glDateEnd)
    dialogVisible.value = true
}
const handleDelete = (row) => {
    ElMessageBox.confirm(
        '确定删除本条记录?',
        '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
    })
        .then(() => {
            var url = 'pur/ActHead/remove'
            var param = {
                id: row.id
            }
            proxy.$axios.post(url, param).then(response => {
                if (response.data.code == 0) {
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    })
                    tableDataLine.value = []
                    getTableData()
                } else {
                    ElMessage({
                        type: 'error',
                        message: '删除失败' + response.data.msg
                    });
                }
            });
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消',
            })
        })
}
const handleCancelAct = (row) => {
    ElMessageBox.confirm(
        '确定取消本条记录?',
        '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
    })
        .then(() => {
            var url = 'pur/ActHead/cancel'
            var param = {
                id: row.id
            }
            proxy.$axios.post(url, param).then(response => {
                if (response.data.code == 0) {
                    ElMessage({
                        type: 'success',
                        message: '取消成功',
                    })
                    tableDataLine.value = []
                    getTableData()
                } else {
                    ElMessage({
                        type: 'error',
                        message: '取消失败' + response.data.msg
                    });
                }
            });
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消',
            })
        })
}
const handlePrintPreview = (row) => {
    location.href = import.meta.env.VITE_BASE_API +
        '/pur/ActHead/downloadAct?userId=' + localStorage.getItem('userId') + '&id=' + encodeURIComponent(row.id)
}
/**
 * 保存、修改、删除
 */


/**
 *   查询 -- 结算行
 */
const queryLine = ref({
    accountNo: ''
})
const activeNameBottom = ref('first')
const loadingLine = ref(false)
const tableDataLine = ref([])
const DoubleClick = (row) => {
    queryLine.value.accountNo = row.accountNo
    getTableDataLine()
}
const getTableDataLine = () => {
    loadingLine.value = true
    var url = 'pur/ActLine/query'
    var param = {
        page: currentPageLine.value,
        rows: pageSizeLine.value,
        params: JSON.stringify(queryLine.value)
    }
    proxy.$axios.get(url, param).then(response => {
        tableDataLine.value = response.data.data.records
        totalRowsLine.value = response.data.data.total
    })
    loadingLine.value = false
}
/**
 *   查询
 */


/**
 * 分页
 */
const currentPageLine = ref(1)
const totalRowsLine = ref(0)
const pageSizesLine = ref([5, 10, 20, 30, 40])
const pageSizeLine = ref(5)
const handleSizeChangeLine = (val) => {
    pageSizeLine.value = val
    getTableDataLine()
}
const handleCurrentChangeLine = (val) => {
    currentPageLine.value = val
    getTableDataLine()
}
/**
 * 分页
 */


/**
 * 对账单
 */
const PopupRefBill = ref(null)
const handleBill = () => {
    PopupRefBill.value.open()
}
const billLines = ref([])
const retuBill = (val) => {
    if (val.length >= 1) {
        form.value.contrNo = val[0].contrNo
        form.value.khContrNo = val[0].khContrNo
        form.value.tradePartnerId = val[0].tradePartnerId
        form.value.tradePartnerCode = val[0].tradePartnerCode
        form.value.tradePartnerName = val[0].tradePartnerName
        form.value.actQty = val.reduce((sum, current) => sum + current.accountQty, 0)
        form.value.contrPrice = val.map(item => item.price).join('、')
        form.value.contrTaxPrice = val.map(item => item.taxPrice).join('、')
        form.value.totalAmountExcludeTax = numberToFixed(val.reduce((sum, current) => sum + current.accountAmount, 0))
        form.value.invoiceAmount = numberToFixed(val.reduce((sum, current) => sum + current.accountTaxAmount, 0))
        form.value.taxRateCal = String(Math.round(parseFloat(form.value.invoiceAmount / form.value.totalAmountExcludeTax - 1) * 10000) / 100)
        form.value.tax = numberToFixed(form.value.invoiceAmount - form.value.totalAmountExcludeTax)
        let minStoInDt = null;
        let maxStoInDt = null;

        // 遍历数组，找到最小和最大的 stoInDt
        val.forEach(item => {
            if (minStoInDt === null || item.stoInDt < minStoInDt) {
                minStoInDt = item.stoInDt
            }
            if (maxStoInDt === null || item.stoInDt > maxStoInDt) {
                maxStoInDt = item.stoInDt
            }
        })
        glDate.value.push(minStoInDt)
        glDate.value.push(maxStoInDt)
        billLines.value = val
    }
}

const numberToFixed = (data) => {
    var value = Math.round(parseFloat(data) * 100) / 100;
    var d = value.toString().split(".");
    if (d.length == 1) {
        value = value.toString() + ".00";
        return value;
    }
    if (d.length > 1) {
        if (d[1].length < 2) {
            console.log(d[1])
            value = value.toString() + "0";
        }
        return value;
    }
}

/**
 * 工作流相关
 */
const flowId = ref('purActFinance')
const handleSubmit = (row) => {
    ElMessageBox.confirm(
        '确定提交审批?',
        '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
    }
    ).then(() => {
        let variables = {
            id: row.id,
        }

        return workflowSubmit(
            flowId.value,
            '采购结算单流程',
            '初始化提交',
            JSON.stringify(variables),
            row.workId,
            row.trackId)
    }).then((result) => {
        if (result.status === 'success') {
            var url = 'pur/ActHead/saveProcessInfo'
            var process = {
                'id': row.id,
                'workId': result.workId,
                'trackId': result.trackId,
            }
            var param = {
                json: JSON.stringify(process),
            }
            proxy.$axios.post(url, param).then(response => {
                if (response.data.code === 0) {
                    form.value = response.data.data
                    ElMessage({
                        type: 'success',
                        message: '提交审批成功',
                    })
                    getTableData()
                }
            })
        }
        else {
            ElMessage({
                type: 'error',
                message: '提交审批失败' + result.msg
            });
        }
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消提交',
        })
    })
}

const handleCancel = (row) => {
    ElMessageBox.confirm(
        '确定撤回审批?',
        '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
    }).then(() => {
        return workflowCancel(row.workId, row.trackId);
    }).then((result) => {
        if (result.status === 'success') {
            ElMessage({
                type: 'success',
                message: '撤回审批成功',
            })
            getTableData()
        } else {
            ElMessage({
                type: 'error',
                message: '撤回审批失败' + result.msg
            })
        }
    }).catch((error) => {
        ElMessage({
            type: 'info',
            message: '已取消撤回',
        })
    })
}

const handleDetail = (row) => {
    if (row.workId === null) {
        ElMessage({
            type: 'info',
            message: '无法查看',
        })
    } else {

        sessionStorage.setItem('workflowQuery', JSON.stringify({
            flowId: flowId.value,
            workId: row.workId,
            trackId: row.trackId,
            date: new Date().getTime()
        }))

        proxy.$router.push({
            path: '/workflow/detail',
        })
    }
}
</script>

<style scoped>
::v-deep .diaClass .el-form-item {
    width: 100%
}

::v-deep .el-dialog__body {
    background-color: #F2F6FC;
}

.el-date-editor--date {
    width: 100%;
}

::v-deep .box-card .el-card__header {
    padding: 5px 20px;
}
</style>