<template>
    <div class="app-container" id="costApplyList">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="80px">
            <el-form-item prop="unitIds">
                <treeselect v-model="queryParams.unitId" :options="unitList" :normalizer="normalizer" :show-count="true"
                    style="width: 240px" :disable-branch-nodes="true" noChildrenText="没有数据了" noOptionsText="没有数据"
                    noResultsText="没有搜索结果" placeholder="请选择结算单位" @select="unitChange" />
                <!-- <el-cascader v-model="unitIds"
                    :show-all-levels="false"
                    :options="unitList"
                    :props="selectTreeProps"
                    filterable
                    clearable
                    collapse-tags
                    @change="unitChange"
                    placeholder="请选择单位"
                ></el-cascader>  -->
            </el-form-item>
            <el-form-item prop="projectIds">
                <treeselect v-model="queryParams.projectId" :options="proList" :normalizer="normalizer"
                    :show-count="true" style="width: 240px" :disable-branch-nodes="true" noChildrenText="没有数据了"
                    noOptionsText="没有数据" noResultsText="没有搜索结果" placeholder="请选择结算工程" @select="proChange" />
                <!-- <el-cascader v-model="projectIds"
                        :show-all-levels="false"
                        :options="proList"
                        :props="selectTreeProps"
                        filterable clearable
                        collapse-tags
                        @change="proChange"
                        placeholder="请选择工程"
                    ></el-cascader>  -->
            </el-form-item>
            <el-form-item prop="agreementCode">
                <el-input v-model="queryParams.agreementCode" placeholder="请输入协议号" clearable />
            </el-form-item>
            <el-form-item prop="sltStatus">
                <el-select v-model="queryParams.sltStatus" placeholder="请选择结算状态" clearable filterable>
                    <el-option v-for="dict in statusList" :key="dict.id" :label="dict.name"
                        :value="dict.id"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item prop="auditTime" label="审批时间:">
                <el-date-picker v-model="auditTimeRange" type="daterange" range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期" style="width: 280px">
                </el-date-picker>
            </el-form-item>
            <el-form-item prop="settlementType">
                <el-select v-model="queryParams.settlementType" placeholder="结算费用筛选" clearable filterable>
                    <el-option label="工器具" :value="1"></el-option>
                    <el-option label="安全工器具" :value="2"></el-option>
                    <el-option label="总费用" :value="3"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="tableList" :max-height="650">
            <el-table-column label="序号" align="center" type="index">
                <template slot-scope="scope">
                    <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column label="协议号" align="center" prop="agreementCode" :show-overflow-tooltip="true" />
            <el-table-column label="分公司" align="center" prop="impUnitName" width="150px":show-overflow-tooltip="true"/>
            <el-table-column label="结算单位" align="center" prop="unitName" />
            <el-table-column label="结算工程" align="center" prop="projectName" />
            <el-table-column label="合计费用（元）" align="center" prop="costs" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    {{ parseFloat(scope.row.costs || 0).toFixed(2) }}
                </template>
            </el-table-column>

            <el-table-column label="结算类型" align="center" prop="sltStatus" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.settlementType === 1" effect="plain">工器具</el-tag>
                    <el-tag type="warning" v-if="scope.row.settlementType === 2" effect="plain">安全工器具</el-tag>
                    <el-tag v-if="scope.row.settlementType == null || scope.row.settlementType === 0" effect="plain">
                        总费用
                    </el-tag>
                    <el-tag type="danger" v-if="scope.row.settlementType === 3" effect="plain">全部</el-tag>
                </template>
            </el-table-column>

            <el-table-column label="审批人" align="center" prop="auditor" :show-overflow-tooltip="true" />
            <el-table-column label="审批时间" align="center" prop="auditTime" width="100" />
            <el-table-column label="结算状态" align="center" prop="sltStatus" :show-overflow-tooltip="true" width="165">
                <!--                <template slot-scope="scope">-->
                <!--                    <dict-tag :options="dict.type.cost_status" :value="scope.row.sltStatus"/>-->
                <!--                </template>-->
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.sltStatus == '1'">{{ scope.row.sltAuditor || '待审核' }}</el-tag>
                    <el-tag type="success" v-else-if="scope.row.sltStatus == '2'">审核通过</el-tag>
                    <el-tag type="danger" v-else-if="scope.row.sltStatus == '3'">审核驳回</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="normal" icon="el-icon-search" @click="handleView(scope.row)">
                        查看
                    </el-button>
                    <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleExame(scope.row)"
                        v-if="scope.row.sltStatus == '1'">
                        审批
                    </el-button>
                    <!-- <el-button size="mini" type="danger" icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                    >撤销申请</el-button> -->
                    <el-button type="primary" plain size="mini" @click="openPrintDialog(scope.row)">协议书</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />

        <!-- 审批弹窗 -->
        <el-dialog title="结算审批" :visible.sync="applyVisible" width="650px" append-to-body>
            <el-form ref="aform" :model="aform" label-width="120px">
                <el-form-item label="结算审批" prop="status">
                    <el-radio v-model="aform.status" label="2">通过</el-radio>
                    <el-radio v-model="aform.status" label="3">不通过</el-radio>
                </el-form-item>
                <el-form-item label="原因" prop="remark">
                    <el-input v-model="aform.remark" maxlength="100" placeholder="请输入" show-word-limit size="small"
                        style="width: 350px" type="textarea" rows="4"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer" style="text-align: center">
                <el-button type="primary" @click="submitListForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 协议单弹窗 -->
        <el-dialog :visible.sync="openPrint" width="1100px" append-to-body>
            <div style="height: 600px; overflow-y: scroll">
                <vue-easy-print tableShow ref="remarksPrintRef" class="print">
                    <div style="text-align: center; font-weight: 600; font-size: 16px">
                        {{ dialogTitle }}有偿使用费结算协议书
                    </div>
                    <div class="info" style="margin-top: 10px; display: flex; justify-content: space-between; align-items: center; padding-right: 20px">
                        <div class="item" style="flex-shrink: 0; margin-bottom: 5px; font-size: 14px">
                            <span v-if="agreementContent.bookCode">协议书编号：{{ agreementContent.bookCode }}</span>
                        </div>
                        <div class="item" style="flex-shrink: 0; margin-bottom: 5px; font-size: 14px">
                            <span>协议号：{{ agreementContent.agreementCode }}</span>
                        </div>
                    </div>
                    <div class="tabelColumn" :class="{ 'pdf-export-mode': isPdfExporting }">
                        <div class="columnLabel" style="width: 20%">工程名称：</div>
                        <div class="columnContent" style="width: 80%; line-height: 1.2;">
                            <span v-if="isPdfExporting && agreementContent.projectName && agreementContent.projectName.length > 30">
                                {{ agreementContent.projectName.substring(0, 30) }}<br/>{{ agreementContent.projectName.substring(30) }}
                            </span>
                            <span v-else>{{ agreementContent.projectName }}</span>
                        </div>
                    </div>
                    <div class="tabelColumn">
                        <div class="columnLabel" style="width: 20%">承租单位：</div>
                        <div class="columnContent" style="width: 40%">{{ agreementContent.unitName }}</div>
                        <div class="columnLabel" style="width: 10%; border-left: 1px solid #9c9c9c">日期：</div>
                        <div class="columnContent" style="width: 30%">{{ agreementContent.applyTime }}</div>
                    </div>
                    <div class="tabelColumn">
                        <div class="columnLabel" style="width: 100%">结算项目及金额(元)</div>
                    </div>
                    <div class="tabelColumn">
                        <div class="columnLabel" style="width: 60%">项目</div>
                        <div class="columnLabel" style="width: 20%; border-left: 1px solid #9c9c9c">施工机具</div>
                        <div class="columnLabel" style="width: 20%; border-left: 1px solid #9c9c9c">安全工器具</div>
                    </div>
                    <div class="tabelColumn">
                        <div class="columnLabel" style="width: 60%">一、施工机具有偿使用费：</div>
                        <div class="columnContent" style="width: 20%">
                            ￥ {{ Number(agreementContent.leaseCost).toFixed(2) }}
                        </div>
                        <div class="columnContent" style="width: 20%">
                            ￥ {{ Number(agreementContent.aqLeaseCost).toFixed(2) }}
                        </div>
                    </div>
                    <div class="tabelColumn">
                        <div class="columnLabel" style="width: 60%">二、施工机具维修费：</div>
                        <div class="columnContent" style="width: 20%">
                            ￥ {{ Number(agreementContent.repairCost).toFixed(2) }}
                        </div>
                        <div class="columnContent" style="width: 20%">
                            ￥ {{ Number(agreementContent.aqRepairCost).toFixed(2) }}
                        </div>
                    </div>
                    <div class="tabelColumn">
                        <div class="columnLabel" style="width: 60%">三、施工机具丢失费：</div>
                        <div class="columnContent" style="width: 20%">
                            ￥ {{ Number(agreementContent.loseCost).toFixed(2) }}
                        </div>
                        <div class="columnContent" style="width: 20%">
                            ￥ {{ Number(agreementContent.aqLoseCost).toFixed(2) }}
                        </div>
                    </div>
                    <div class="tabelColumn">
                        <div class="columnLabel" style="width: 60%">四、施工机具损坏赔偿费：</div>
                        <div class="columnContent" style="width: 20%">
                            ￥ {{ Number(agreementContent.scrapCost).toFixed(2) }}
                        </div>
                        <div class="columnContent" style="width: 20%">
                            ￥ {{ Number(agreementContent.aqScrapCost).toFixed(2) }}
                        </div>
                    </div>
                    <div class="tabelColumn">
                        <div class="columnLabel" style="width: 60%">五、施工机具租赁减免费：</div>
                        <div class="columnContent" style="width: 20%">
                            ￥ {{ Number(agreementContent.reductionCost).toFixed(2) }}
                        </div>
                        <div class="columnContent" style="width: 20%">
                            ￥ {{ Number(agreementContent.aqReductionCost).toFixed(2) }}
                        </div>
                    </div>
                    <div class="tabelColumn">
                        <div class="columnLabel" style="width: 60%">小计：</div>
                        <div class="columnContent" style="width: 20%">
                            ￥ {{ Number(agreementContent.addMoneySafety).toFixed(2) }}
                        </div>
                        <div class="columnContent" style="width: 20%">
                            ￥ {{ Number(agreementContent.addMoneyProject).toFixed(2) }}
                        </div>
                    </div>
                    <div class="tabelColumn">
                        <div class="columnLabel" style="width: 20%">费用合计金额（大写）：</div>
                        <div class="columnContent" style="width: 40%">{{ agreementContent.costAllUpper }}</div>
                        <div class="columnContent" style="width: 40%">
                            ￥ {{ Number(agreementContent.costAll).toFixed(2) }}
                        </div>
                    </div>
                    <div class="tabelColumn">
                        <div class="columnLabel" style="width: 20%">说明：</div>
                        <div class="columnContent" style="width: 80%">
                            本协议一式两份，甲方一份，乙方一份，经双方签字后生效。
                        </div>
                    </div>
                    <div class="tabelColumn" style="border: 1px solid #9c9c9c">
                        <div class="columnLabel" style="width: 20%">备注：</div>
                        <div class="columnContent" style="width: 80%">
                            此费用仅为在机具（物流）分公司发生费用，未计从项目部领用机具费用。
                        </div>
                    </div>

                    <div class="fillIn" style="margin-top: 20px; display: flex; justify-content: space-between">
                        <div class="item-new" style="width: 33%">

                            <span>部门负责人：</span>

                            <div style="display: flex;flex-direction: column">
                                <div v-for="(item, index) in agreementContent.signUrlList" :key="index" style="margin-top: -20px;">
                                    <img v-if="item.auditorSignUrl"  :src="initImgPath(item.auditorSignUrl)"
                                        style="width: 40px; max-height: 90px;margin-left: 20px; max-width: 100%;"
                                        :style="{ transform: item.signType == 0 ? 'rotate(-90deg)' : '' }" alt="" />
                                </div>
                            </div>

                        </div>

                        <div class="item-new" style="width: 33%">

                            <span>承租负责人：</span>
                            <img :src="agreementContent.signUrlList[0].managerSignUrl"
                                style="width: 40px; height: 90px; max-width: 100%;margin-left: 20px;"
                                :style="{ transform: agreementContent.signUrlList && agreementContent.signUrlList[0].signType == 0 ? 'rotate(-90deg)' : '' }" alt=""
                                onerror="this.style.display='none'" v-if="agreementContent.signUrlList && agreementContent.signUrlList[0].managerSignUrl" />

                        </div>

                        <div class="item-new" style="width: 33%">

                            <span>核算员：</span>


                            <img :src="initImgPath(agreementContent.signUrlList && agreementContent.signUrlList[0].sltSignUrl)"
                                style="width: 40px; height: 90px; max-width: 100%; margin-left: 20px;"
                                :style="{ transform: agreementContent.signUrlList && agreementContent.signUrlList[0].signType == 0 ? 'rotate(-90deg)' : '' }" alt=""
                                onerror="this.style.display='none'" v-if="agreementContent.signUrlList && agreementContent.signUrlList[0].sltSignUrl" />

                        </div>
                    </div>
                </vue-easy-print>
            </div>

            <div slot="footer" class="dialog-footer" style="text-align: center">
                <!-- <el-button @click="exportExcel">导出Excel</el-button> -->
                <el-button type="primary" @click="openBookCodeDialog" v-if="!agreementContent.bookCode">协议书编号录入</el-button>
                <el-button type="primary" @click="print">打 印</el-button>
                <el-button type="success" @click="exportPDF">导出PDF</el-button>
                <el-button @click="openPrint = false">关 闭</el-button>
            </div>
        </el-dialog>

        <!-- 协议书编号录入对话框 -->
        <el-dialog title="协议书编号录入" :visible.sync="bookCodeDialogVisible" width="400px" @close="resetBookCodeForm">
            <el-form :model="bookCodeForm" label-width="100px">
                <el-form-item label="编号：">
                    <el-input v-model="bookCodeForm.bookCode" placeholder="请输入协议书编号"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="bookCodeDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveBookCode">保 存</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { getProjectList, getUnitList, getAgreementInfoById, getUnitListFilterTeam } from '@/api/back/index.js'
import { getSltList, costExamine, getSltAgreementBookApi, updateSltBookCodeById } from '@/api/cost/cost'
import { toChineseAmount } from '@/utils/bonus.js'
import vueEasyPrint from 'vue-easy-print'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { formatTime } from '@/utils/bonus'
import { saveAs } from 'file-saver'
import ExcelJS from 'exceljs'
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
import {
    Document,
    Packer,
    Paragraph,
    TextRun,
    Table,
    TableRow,
    TableCell,
    AlignmentType,
    WidthType,
    BorderStyle,
    PageOrientation
} from 'docx'

export default {
    name: 'ExamHome',
    dicts: ['cost_status'],
    components: { Treeselect, vueEasyPrint },
    data() {
        return {
            // 遮罩层
            loading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 单位数据
            unitList: [],
            // 工程数据
            proList: [],
            unitIds: null,
            projectIds: null,
            selectTreeProps: {
                children: 'children',
                label: 'name',
                value: 'id'
                // multiple: true,//false
            },
            statusList: [
                { id: '1', name: '待审核' },
                { id: '2', name: '审核通过' },
                { id: '3', name: '审核驳回' }
            ], //集合
            // 表格数据
            tableList: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                keyWord: undefined,
                sltStatus: '',
                settlementType: '',
                isCommit: '',
                unitId: null,
                projectId: null,
                agreementId: null,
                agreementCode: null,
                enableQuerySltData: true,
                startTime: null,
                endTime: null
            },
            openPrint: false,
            // 审批弹窗
            aform: { status: '2', remark: '' },
            //审批弹窗是否开启
            applyVisible: false,
            id: '',
            agreementIdTemp: '',
            // 协议书内容
            agreementContent: {
                agreementCode: '',
                projectName: '',
                unitName: '',
                leaseCost: '', // 租赁费用
                repairCost: '', // 维修费用
                loseCost: '', // 丢失费用
                scrapCost: '', // 报废费用
                reductionCost: '', // 减免费用
                aqLeaseCost: '', // 租赁费用
                aqRepairCost: '', // 维修费用
                aqLoseCost: '', // 丢失费用
                aqScrapCost: '', // 报废费用
                aqReductionCost: '', // 减免费用
                addMoneySafety: '',//安全费用小计
                addMoneyProject: '',//施工费用小计
                costAll: '', // 合计费用
                costAllUpper: '' // 合计费用大写
            },
            dialogTitle: '',
            currentRow: {},
            isPdfExporting: false,
            bookCodeDialogVisible: false,
            bookCodeForm: {
                bookCode: ''
            },
            auditTimeRange: null
        }
    },
    created() {
        this.GetUnitData()
        this.GetProData()
        this.getList()
    },
    methods: {
        /** 转换菜单数据结构 */
        normalizer(node) {
            if (node.children && !node.children.length) {
                delete node.children
            }
            return {
                id: node.id,
                label: node.name,
                children: node.children
            }
        },
        // 获取 来往单位 列表数据
        async GetUnitData() {
            const params = {
                // projectId: this.queryParams.projectId /*  */,
            }
            const res = await getUnitListFilterTeam(params)
            this.unitList = res.data

            this.getAgreementInfo()
        },
        unitChange(val) {
            // if(val&&val.length>0){
            //     this.queryParams.unitId=this.unitIds[this.unitIds.length - 1]
            // }else if(val&&val.length==0){
            //     this.queryParams.unitId=""
            // }
            // this.GetProData()
            setTimeout(() => {
                this.queryParams.projectId = null
                this.queryParams.agreementId = null
                this.queryParams.agreementCode = null
                this.GetProData()
            }, 500)
        },
        // 获取 工程名称 列表数据
        async GetProData() {
            const params = {
                unitId: this.queryParams.unitId
            }
            const res = await getProjectList(params)
            this.proList = res.data

            this.getAgreementInfo()
        },
        proChange(val) {
            // if(val&&val.length>0){
            //     this.queryParams.projectId=this.projectIds[this.projectIds.length - 1]
            // }else if(val&&val.length==0){
            //     this.queryParams.projectId=""
            // }
            // this.GetUnitData()
            setTimeout(() => {
                this.GetUnitData()
            }, 500)
        },
        // 获取 协议id
        async getAgreementInfo() {
            if (this.queryParams.unitId && this.queryParams.projectId) {
                const params = {
                    unitId: this.queryParams.unitId,
                    projectId: this.queryParams.projectId
                }
                const res = await getAgreementInfoById(params)
                console.log(res)
                if (!(res.data && res.data.agreementId)) {
                    this.$message.error('当前单位和工程无协议！')
                    this.queryParams.unitId = null
                    this.queryParams.projectId = null
                    this.GetUnitData()
                    this.GetProData()
                } else {
                    this.queryParams.agreementId = res.data.agreementId
                    this.queryParams.agreementCode = res.data.agreementCode
                }
            }
        },

        /** 查询列表 */
        getList() {
            this.loading = true
            getSltList(this.queryParams).then(response => {
                this.tableList = response.rows
                this.total = response.total
                this.loading = false
            })
        },

        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            // 处理日期范围
            if (this.auditTimeRange && this.auditTimeRange.length === 2) {
                this.queryParams.startTime = this.formatDate(this.auditTimeRange[0])
                this.queryParams.endTime = this.formatDate(this.auditTimeRange[1])
            } else {
                this.queryParams.startTime = null
                this.queryParams.endTime = null
            }
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.queryParams = {
                pageNum: 1,
                pageSize: 10,
                sltStatus: '',
                settlementType: '',
                isCommit: '',
                unitId: null,
                projectId: null,
                agreementId: '',
                agreementCode: '',
                startTime: null,
                endTime: null,
                enableQuerySltData: true
            }
            this.auditTimeRange = null
            this.resetForm('queryForm')
            this.handleQuery()
        },
        //结算审批查看
        handleView(row) {
            let arr = []
            row.enableQuerySltData = true
            arr.push(row)
            this.$emit('goDetail', JSON.stringify(arr))
        },
        //结算审批
        handleExame(row) {
            this.currentRow = row
            this.id = row.id
            this.agreementIdTemp = row.agreementId
            this.aform.remark = ''
            this.applyVisible = true
        },
        //提交按钮
        submitListForm() {
            let param = {
                id: this.id,
                status: this.aform.status,
                remark: this.aform.remark,
                agreementId: this.agreementIdTemp,
                settlementType: this.currentRow.settlementType,
                sltTask: this.currentRow.sltTask
            }
            costExamine(param)
                .then(res => {
                    if (res.code == 200) {
                        this.$modal.msgSuccess('审批成功')
                        this.getList()
                        this.applyVisible = false
                    } else {
                        this.$modal.msgError(res.msg)
                    }
                })
                .catch(() => { })
        },

        //取消按钮
        cancel() {
            this.applyVisible = false
            this.aform = { status: '2' }
        },

        async openPrintDialog(row) {
            // this.dialogTitle = row.settlementType == 2 ? '安全工器具' : '机具设备'
            if (row.settlementType == 1) {
                this.dialogTitle = '机具设备'
            } else if (row.settlementType == 2) {
                this.dialogTitle = '安全工器具'
            } else {
                this.dialogTitle = ''
            }
            // 保存当前行的 id，用于协议书编号录入
            this.agreementIdTemp = row.id
            row.enableQuerySltData = true
            this.openPrint = true
            try {
                const res = await getSltAgreementBookApi(row)
                console.log('🚀 ~ openPrintDialog ~ res:', res)
                if (!res.data) return
                this.agreementContent = res.data
                this.agreementContent.agreementCode = row.agreementCode
                this.agreementContent.addMoneySafety =
                    Number(res.data.leaseCost) +
                    Number(res.data.repairCost) +
                    Number(res.data.scrapCost) +
                    Number(res.data.loseCost) -
                    Number(res.data.reductionCost)

                this.agreementContent.addMoneyProject =
                    Number(res.data.aqLeaseCost) +
                    Number(res.data.aqRepairCost) +
                    Number(res.data.aqScrapCost) +
                    Number(res.data.aqLoseCost) -
                    Number(res.data.aqReductionCost)

                this.agreementContent.costAll =
                    Number(res.data.leaseCost) +
                    Number(res.data.repairCost) +
                    Number(res.data.scrapCost) +
                    Number(res.data.loseCost) -
                    Number(res.data.reductionCost) +
                    Number(res.data.aqLeaseCost) +
                    Number(res.data.aqRepairCost) +
                    Number(res.data.aqScrapCost) +
                    Number(res.data.aqLoseCost) -
                    Number(res.data.aqReductionCost)
                // costAllUpper 中文大写
                this.agreementContent.costAllUpper = toChineseAmount(this.agreementContent.costAll.toFixed(2))
            } catch (error) {
                console.log('🚀 ~ openPrintDialog ~ error:', error)
            }
        },
        //维修任务单打印
        print() {
            this.$refs.remarksPrintRef.print()
        },
        async exportExcel() {
            const data = this.agreementContent
            const workbook = new ExcelJS.Workbook()
            const sheet = workbook.addWorksheet('结算协议')

            // ======= 公共边框样式 =======
            const borderStyle = {
                top: { style: 'thin' },
                left: { style: 'thin' },
                bottom: { style: 'thin' },
                right: { style: 'thin' }
            }

            // ======= 列宽设置 =======
            sheet.columns = [{ width: 25 }, { width: 50 }, { width: 25 }, { width: 35 }]

            // ======= 标题 =======
            sheet.mergeCells('A1:D1')
            const title = sheet.getCell('A1')
            title.value = '机具设备有偿使用费结算协议书'
            title.font = { bold: true, size: 16 }
            title.alignment = { horizontal: 'center', vertical: 'middle' }

            // ======= 协议号 =======
            sheet.mergeCells('A2:D2')
            const codeCell = sheet.getCell('A2')
            codeCell.value = `协议号：${data.agreementCode}`
            codeCell.alignment = { horizontal: 'right', vertical: 'middle' }

            // ======= 工程名称 =======
            const r3 = sheet.addRow(['工程名称：', data.projectName, '', ''])
            sheet.mergeCells(`B${r3.number}:D${r3.number}`)
            r3.eachCell(c => {
                c.border = borderStyle
                c.alignment = { horizontal: 'center', vertical: 'middle' }
            })

            // ======= 承租单位 + 日期 =======
            const r4 = sheet.addRow(['承租单位：', data.unitName, '日期：', data.applyTime])
            r4.eachCell(c => {
                c.border = borderStyle
                c.alignment = { horizontal: 'center', vertical: 'middle' }
            })

            // ======= 表头 =======
            const r6 = sheet.addRow(['结算项目及金额(元)', '', '', ''])
            sheet.mergeCells(`A${r6.number}:D${r6.number}`)
            r6.eachCell(c => {
                c.border = borderStyle
                c.font = { bold: true }
                c.alignment = { horizontal: 'center', vertical: 'middle' }
            })

            // ======= 金额明细 =======
            const items = [
                ['一、施工机具有偿使用费：', `￥ ${Number(data.leaseCost).toFixed(2)}`],
                ['二、施工机具维修费：', `￥ ${Number(data.repairCost).toFixed(2)}`],
                ['三、施工机具丢失费：', `￥ ${Number(data.loseCost).toFixed(2)}`],
                ['四、施工机具损坏赔偿费：', `￥ ${Number(data.scrapCost).toFixed(2)}`],
                ['五、施工机具租赁减免费：', `￥ ${Number(data.reductionCost).toFixed(2)}`]
            ]
            items.forEach(row => {
                const r = sheet.addRow([row[0], '', '', row[1]])
                sheet.mergeCells(`A${r.number}:C${r.number}`)
                r.eachCell(c => {
                    c.border = borderStyle
                    c.alignment = { horizontal: 'center', vertical: 'middle' }
                })
            })

            // ======= 合计 =======
            const totalRow = sheet.addRow([
                '费用合计金额（大写）：',
                data.costAllUpper,
                '',
                `￥ ${Number(data.costAll).toFixed(2)}`
            ])
            sheet.mergeCells(`B${totalRow.number}:C${totalRow.number}`)
            totalRow.eachCell(c => {
                c.border = borderStyle
                c.alignment = { horizontal: 'center', vertical: 'middle' }
            })

            // ======= 说明 =======
            const explainRow = sheet.addRow([
                '说明：',
                '本协议一式两份，甲方一份，乙方一份，经双方签字后生效。',
                '',
                ''
            ])
            sheet.mergeCells(`B${explainRow.number}:D${explainRow.number}`)
            explainRow.eachCell(c => {
                c.border = borderStyle
                c.alignment = { horizontal: 'center', vertical: 'middle' }
            })

            // ======= 备注 =======
            const remarkRow = sheet.addRow([
                '备注：',
                '此费用仅为在机具（物流）分公司发生费用，未计从项目部领用机具费用。',
                '',
                ''
            ])
            sheet.mergeCells(`B${remarkRow.number}:D${remarkRow.number}`)
            remarkRow.eachCell(c => {
                c.border = borderStyle
                c.alignment = { horizontal: 'center', vertical: 'middle' }
            })

            // ======= 空行 =======
            sheet.addRow(['', '', '', ''])

            // ======= 签名行（无边框 + 左对齐 + 三等分） =======
            const signRow = sheet.addRow(['部门负责人：', '承租负责人：', '核算员：'])
            signRow.eachCell(cell => {
                cell.border = undefined
                cell.alignment = { horizontal: 'left', vertical: 'middle' }
            })

            // ======= 导出文件 =======
            const buf = await workbook.xlsx.writeBuffer()
            saveAs(new Blob([buf]), `机具设备有偿使用费结算协议书-${data.agreementCode}_${formatTime(new Date())}.xlsx`)
        },
        async exportWord() {
            const data = this.agreementContent

            // ====== 通用单元格样式 ======
            const cellOpts = {
                margins: { top: 300, bottom: 300, left: 40, right: 40 }, // 缩小上下间距
                verticalAlign: 'center',
                borders: {
                    top: { style: BorderStyle.SINGLE, size: 1 },
                    bottom: { style: BorderStyle.SINGLE, size: 1 },
                    left: { style: BorderStyle.SINGLE, size: 1 },
                    right: { style: BorderStyle.SINGLE, size: 1 }
                }
            }

            const noBorder = {
                top: { style: BorderStyle.NONE },
                bottom: { style: BorderStyle.NONE },
                left: { style: BorderStyle.NONE },
                right: { style: BorderStyle.NONE }
            }

            // ====== 创建文档 ======
            const doc = new Document({
                sections: [
                    {
                        properties: {
                            page: {
                                size: { width: 11900, height: 16840, orientation: PageOrientation.PORTRAIT },
                                margin: { top: 720, right: 720, bottom: 720, left: 720 }
                            }
                        },
                        children: [
                            // ===== 标题 =====
                            new Paragraph({
                                alignment: AlignmentType.CENTER,
                                spacing: { before: 100, after: 200 },
                                children: [new TextRun({ text: '机具设备有偿使用费结算协议书', bold: true, size: 32 })]
                            }),

                            // ===== 协议号和编号 =====

                            new Table({
                                width: { size: 100, type: WidthType.PERCENTAGE },
                                rows: [
                                    new TableRow({
                                        children: [
                                            new TableCell({
                                                width: { size: 70, type: WidthType.PERCENTAGE },
                                                borders: noBorder,
                                                children: [new Paragraph({ text: '' })]
                                            }),
                                            new TableCell({
                                                width: { size: 30, type: WidthType.PERCENTAGE },
                                                borders: noBorder,
                                                children: [
                                                    new Paragraph({
                                                        alignment: AlignmentType.LEFT,
                                                        text: `协议号：${data.agreementCode || ''}`,
                                                        spacing: { before: 0, after: 0 }
                                                    })
                                                ],
                                                margins: { top: 100, bottom: 100 } // 缩小上下空间
                                            })
                                        ]
                                    }),
                                    new TableRow({
                                        children: [
                                            new TableCell({
                                                width: { size: 70, type: WidthType.PERCENTAGE },
                                                borders: noBorder,
                                                children: [new Paragraph({ text: '' })]
                                            }),
                                            new TableCell({
                                                width: { size: 30, type: WidthType.PERCENTAGE },
                                                borders: noBorder,
                                                children: [
                                                    new Paragraph({
                                                        alignment: AlignmentType.LEFT,
                                                        text: `编号：`,
                                                        spacing: { before: 0, after: 0 }
                                                    })
                                                ],
                                                margins: { top: 100, bottom: 100 } // 缩小上下空间
                                            })
                                        ]
                                    })
                                ]
                            }),

                            // === 添加一个空白 Paragraph ===
                            new Paragraph({
                                text: '',
                                spacing: { before: 100, after: 100 } // 给点上下间距，让后面内容不受影响
                            }),

                            // ===== 主体表格 =====
                            new Table({
                                width: { size: 100, type: WidthType.PERCENTAGE },
                                rows: [
                                    // 工程名称
                                    new TableRow({
                                        children: [
                                            new TableCell({
                                                ...cellOpts,
                                                columnSpan: 1,
                                                width: { size: 40, type: WidthType.PERCENTAGE },
                                                children: [
                                                    new Paragraph({
                                                        alignment: AlignmentType.CENTER,
                                                        text: '工程名称：'
                                                    })
                                                ]
                                            }),
                                            new TableCell({
                                                ...cellOpts,
                                                width: { size: 60, type: WidthType.PERCENTAGE },
                                                columnSpan: 3,
                                                children: [
                                                    new Paragraph({
                                                        alignment: AlignmentType.CENTER,
                                                        text: data.projectName
                                                    })
                                                ]
                                            })
                                        ]
                                    }),

                                    // 承租单位 + 日期
                                    new TableRow({
                                        children: [
                                            new TableCell({
                                                ...cellOpts,
                                                // columnSpan: 1,
                                                width: { size: 20, type: WidthType.PERCENTAGE },
                                                children: [
                                                    new Paragraph({
                                                        alignment: AlignmentType.CENTER,
                                                        text: '承租单位：'
                                                    })
                                                ]
                                            }),
                                            new TableCell({
                                                ...cellOpts,
                                                width: { size: 20, type: WidthType.PERCENTAGE },
                                                children: [
                                                    new Paragraph({
                                                        alignment: AlignmentType.CENTER,
                                                        text: data.unitName
                                                    })
                                                ]
                                            }),
                                            new TableCell({
                                                ...cellOpts,
                                                width: { size: 60, type: WidthType.PERCENTAGE },
                                                children: [
                                                    new Paragraph({
                                                        alignment: AlignmentType.CENTER,
                                                        text: `日期：` + data.applyTime
                                                    })
                                                ]
                                            })

                                        ]
                                    }),

                                    // 表头
                                    new TableRow({
                                        children: [
                                            new TableCell({
                                                ...cellOpts,
                                                columnSpan: 4,
                                                children: [
                                                    new Paragraph({
                                                        alignment: AlignmentType.CENTER,
                                                        text: '结算项目及金额（元）',
                                                        bold: true
                                                    })
                                                ]
                                            })
                                        ]
                                    }),

                                    // 项目 工机具 安全工器具
                                    new TableRow({
                                        children: [
                                            new TableCell({
                                                ...cellOpts,
                                                width: { size: 40, type: WidthType.PERCENTAGE },
                                                children: [
                                                    new Paragraph({
                                                        alignment: AlignmentType.CENTER,
                                                        text: '项目'
                                                    })
                                                ]
                                            }),
                                            new TableCell({
                                                ...cellOpts,
                                                width: { size: 30, type: WidthType.PERCENTAGE },
                                                children: [
                                                    new Paragraph({
                                                        alignment: AlignmentType.CENTER,
                                                        text: '工机具'
                                                    })
                                                ]
                                            }),
                                            new TableCell({
                                                ...cellOpts,
                                                width: { size: 30, type: WidthType.PERCENTAGE },
                                                children: [
                                                    new Paragraph({
                                                        alignment: AlignmentType.CENTER,
                                                        text: '安全工器具'
                                                    })
                                                ]
                                            }),
                                        ]
                                    }),

                                    // 金额明细
                                    ...[
                                        ['一、施工机具有偿使用费：', `￥ ${Number(data.leaseCost).toFixed(2)}`, `￥ ${Number(data.leaseCost).toFixed(2)}`],
                                        ['二、施工机具维修费：', `￥ ${Number(data.repairCost).toFixed(2)}`, `￥ ${Number(data.leaseCost).toFixed(2)}`],
                                        ['三、施工机具丢失费：', `￥ ${Number(data.loseCost).toFixed(2)}`, `￥ ${Number(data.leaseCost).toFixed(2)}`],
                                        ['四、施工机具损坏赔偿费：', `￥ ${Number(data.scrapCost).toFixed(2)}`, `￥ ${Number(data.leaseCost).toFixed(2)}`],
                                        ['五、施工机具租赁减免费：', `￥ ${Number(data.reductionCost).toFixed(2)}`, `￥ ${Number(data.leaseCost).toFixed(2)}`],
                                        ['小计：', `￥ ${Number(data.addMoneySafety).toFixed(2)}`, `￥ ${Number(data.addMoneyProject).toFixed(2)}`]
                                    ].map(
                                        ([label, toolValue, safeValue]) =>
                                            new TableRow({
                                                children: [
                                                    // 项目
                                                    new TableCell({
                                                        ...cellOpts,
                                                        width: { size: 40, type: WidthType.PERCENTAGE },
                                                        children: [
                                                            new Paragraph({
                                                                alignment: AlignmentType.CENTER,
                                                                text: label
                                                            })
                                                        ]
                                                    }),

                                                    // 工机具
                                                    new TableCell({
                                                        ...cellOpts,
                                                        width: { size: 30, type: WidthType.PERCENTAGE },
                                                        children: [
                                                            new Paragraph({
                                                                alignment: AlignmentType.CENTER,
                                                                text: toolValue
                                                            })
                                                        ]
                                                    }),

                                                    // 安全工器具
                                                    new TableCell({
                                                        ...cellOpts,
                                                        width: { size: 30, type: WidthType.PERCENTAGE },
                                                        children: [
                                                            new Paragraph({
                                                                alignment: AlignmentType.CENTER,
                                                                text: safeValue
                                                            })
                                                        ]
                                                    })
                                                ]
                                            })
                                    ),

                                    // 合计
                                    new TableRow({
                                        children: [
                                            new TableCell({
                                                ...cellOpts,
                                                children: [
                                                    new Paragraph({
                                                        alignment: AlignmentType.CENTER,
                                                        text: '费用合计金额（大写）：'
                                                    })
                                                ]
                                            }),
                                            new TableCell({
                                                ...cellOpts,
                                                children: [
                                                    new Paragraph({
                                                        alignment: AlignmentType.CENTER,
                                                        text: data.costAllUpper
                                                    })
                                                ]
                                            }),
                                            new TableCell({
                                                ...cellOpts,
                                                columnSpan: 2,
                                                children: [
                                                    new Paragraph({
                                                        alignment: AlignmentType.CENTER,
                                                        text: `￥ ${Number(data.costAll).toFixed(2)}`
                                                    })
                                                ]
                                            })
                                        ]
                                    }),

                                    // 说明
                                    new TableRow({
                                        children: [
                                            new TableCell({
                                                ...cellOpts,
                                                children: [
                                                    new Paragraph({ alignment: AlignmentType.CENTER, text: '说明：' })
                                                ]
                                            }),
                                            new TableCell({
                                                ...cellOpts,
                                                columnSpan: 3,
                                                children: [
                                                    new Paragraph({
                                                        alignment: AlignmentType.CENTER,
                                                        text: '本协议一式两份，甲方一份，乙方一份，经双方签字后生效。'
                                                    })
                                                ]
                                            })
                                        ]
                                    }),

                                    // 备注
                                    new TableRow({
                                        children: [
                                            new TableCell({
                                                ...cellOpts,
                                                children: [
                                                    new Paragraph({ alignment: AlignmentType.CENTER, text: '备注：' })
                                                ]
                                            }),
                                            new TableCell({
                                                ...cellOpts,
                                                columnSpan: 3,
                                                children: [
                                                    new Paragraph({
                                                        alignment: AlignmentType.CENTER,
                                                        text: '此费用仅为在机具（物流）分公司发生费用，未计从项目部领用机具费用。'
                                                    })
                                                ]
                                            })
                                        ]
                                    })
                                ]
                            }),

                            // 空白间距
                            new Paragraph({ text: '', spacing: { before: 200 } }),

                            // ===== 底部签名行（无边框） =====
                            new Table({
                                width: { size: 100, type: WidthType.PERCENTAGE },
                                rows: [
                                    new TableRow({
                                        children: ['部门负责人：', '承租负责人：', '核算员：'].map(
                                            text =>
                                                new TableCell({
                                                    borders: noBorder,
                                                    children: [new Paragraph({ alignment: AlignmentType.LEFT, text })],
                                                    margins: { top: 200, bottom: 200 } // 缩小上下空间
                                                })
                                        )
                                    })
                                ]
                            })
                        ]
                    }
                ]
            })

            const blob = await Packer.toBlob(doc)
            saveAs(blob, `机具设备有偿使用费结算协议书-${data.agreementCode}.docx`)
        },

        // ===== PDF 导出 =====
        async exportPDF() {
            try {
                // 设置 PDF 导出标志，启用工程名称换行
                this.isPdfExporting = true

                // 等待 Vue 更新 DOM
                await this.$nextTick()

                // 显示加载提示
                const loadingInstance = this.$loading({
                    lock: true,
                    text: '正在生成PDF...',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                })

                // 获取要导出的 DOM 元素
                const element = this.$refs.remarksPrintRef.$el

                // 保存原始样式
                const originalStyle = element.getAttribute('style')

                // 保存所有 tabelColumn 和相关元素的原始样式
                const tabelColumns = element.querySelectorAll('.tabelColumn')
                const columnLabels = element.querySelectorAll('.columnLabel')
                const columnContents = element.querySelectorAll('.columnContent')
                const titleElement = element.querySelector('div[style*="text-align: center"]')
                const infoElement = element.querySelector('.info')
                const allTextElements = element.querySelectorAll('*')

                const originalTabelStyles = Array.from(tabelColumns).map(el => el.getAttribute('style'))
                const originalLabelStyles = Array.from(columnLabels).map(el => el.getAttribute('style'))
                const originalContentStyles = Array.from(columnContents).map(el => el.getAttribute('style'))
                const originalTitleStyle = titleElement ? titleElement.getAttribute('style') : null
                const originalInfoStyle = infoElement ? infoElement.getAttribute('style') : null
                const originalTextStyles = Array.from(allTextElements).map(el => el.getAttribute('style'))

                // 临时添加边距样式和顶部间距
                element.style.padding = '40px 20px 20px 20px'
                element.style.backgroundColor = '#ffffff'
                element.style.boxSizing = 'border-box'

                // 调整标题：加粗并增大2个字号（16px -> 20px）
                if (titleElement) {
                    titleElement.style.fontSize = '20px'
                    titleElement.style.fontWeight = '700'
                }

                // 调整其他文字：增大1个字号（14px -> 16px）
                if (infoElement) {
                    const infoItems = infoElement.querySelectorAll('.item')
                    infoItems.forEach(item => {
                        item.style.fontSize = '16px'
                    })
                }

                // 调整所有行的高度为双倍（70px）
                tabelColumns.forEach((el, index) => {
                    el.style.height = '70px'
                    el.style.minHeight = '70px'

                    // 前两个 tabelColumn（工程名称和承租单位）增加10px高度
                    if (index < 2) {
                        el.style.height = '80px'
                        el.style.minHeight = '80px'
                    }
                })

                columnLabels.forEach(el => {
                    el.style.height = '70px'
                    el.style.lineHeight = '70px'
                    el.style.fontSize = '16px'
                })

                columnContents.forEach((el, index) => {
                    el.style.height = '70px'
                    el.style.lineHeight = '70px'
                    el.style.fontSize = '16px'

                    // 第一个 columnContent（工程名称内容）调整为紧凑的换行
                    if (index === 0) {
                        el.style.height = '80px'
                        el.style.lineHeight = '1.2'
                        el.style.display = 'flex'
                        el.style.alignItems = 'center'
                        el.style.justifyContent = 'center'
                        el.style.whiteSpace = 'normal'
                        el.style.overflow = 'hidden'
                    }
                })

                // 调整签名区域的顶部间距
                const fillInElement = element.querySelector('.fillIn')
                if (fillInElement) {
                    fillInElement.style.marginTop = '30px'
                }

                // 调整签名项的顶部间距
                const itemNewElements = element.querySelectorAll('.item-new')
                itemNewElements.forEach(el => {
                    el.style.paddingTop = '10px'
                })

                // 使用 html2canvas 将 DOM 转换为 canvas
                const canvas = await html2canvas(element, {
                    scale: 2, // 提高清晰度
                    useCORS: true, // 允许跨域图片
                    logging: false,
                    backgroundColor: '#ffffff',
                    allowTaint: true,
                    windowHeight: element.scrollHeight
                })

                // 恢复原始样式
                if (originalStyle) {
                    element.setAttribute('style', originalStyle)
                } else {
                    element.removeAttribute('style')
                }

                // 恢复标题样式
                if (titleElement) {
                    if (originalTitleStyle) {
                        titleElement.setAttribute('style', originalTitleStyle)
                    } else {
                        titleElement.removeAttribute('style')
                    }
                }

                // 恢复信息区域样式
                if (infoElement) {
                    if (originalInfoStyle) {
                        infoElement.setAttribute('style', originalInfoStyle)
                    } else {
                        infoElement.removeAttribute('style')
                    }
                    const infoItems = infoElement.querySelectorAll('.item')
                    infoItems.forEach(item => {
                        item.style.fontSize = ''
                    })
                }

                // 恢复所有元素的原始样式
                tabelColumns.forEach((el, index) => {
                    if (originalTabelStyles[index]) {
                        el.setAttribute('style', originalTabelStyles[index])
                    } else {
                        el.removeAttribute('style')
                    }
                })

                columnLabels.forEach((el, index) => {
                    if (originalLabelStyles[index]) {
                        el.setAttribute('style', originalLabelStyles[index])
                    } else {
                        el.removeAttribute('style')
                    }
                })

                columnContents.forEach((el, index) => {
                    if (originalContentStyles[index]) {
                        el.setAttribute('style', originalContentStyles[index])
                    } else {
                        el.removeAttribute('style')
                    }
                })

                // 恢复签名区域样式
                if (fillInElement) {
                    fillInElement.style.marginTop = ''
                }

                itemNewElements.forEach(el => {
                    el.style.paddingTop = ''
                })

                // A4 纸张尺寸（毫米）
                const pageWidth = 210
                const pageHeight = 297
                const margin = 10 // 边距（毫米）
                const contentWidth = pageWidth - 2 * margin

                // 计算图片高度，保持宽高比
                const imgHeight = (canvas.height * contentWidth) / canvas.width

                // 创建 PDF 文档
                const pdf = new jsPDF({
                    orientation: 'portrait',
                    unit: 'mm',
                    format: 'a4'
                })

                let heightLeft = imgHeight
                let position = margin

                // 如果内容超过一页，分页处理
                const pageContentHeight = pageHeight - 2 * margin

                while (heightLeft > 0) {
                    // 计算当前页面可用高度
                    const currentPageHeight = Math.min(heightLeft, pageContentHeight)

                    // 计算需要从原图中截取的部分
                    const sourceHeight = (currentPageHeight * canvas.height) / imgHeight
                    const sourceY = (imgHeight - heightLeft) * (canvas.height / imgHeight)

                    // 创建临时 canvas 用于截取
                    const tempCanvas = document.createElement('canvas')
                    tempCanvas.width = canvas.width
                    tempCanvas.height = sourceHeight
                    const ctx = tempCanvas.getContext('2d')
                    ctx.drawImage(canvas, 0, sourceY, canvas.width, sourceHeight, 0, 0, canvas.width, sourceHeight)

                    const pageImgData = tempCanvas.toDataURL('image/png')
                    pdf.addImage(pageImgData, 'PNG', margin, position, contentWidth, currentPageHeight)

                    heightLeft -= currentPageHeight
                    position = margin

                    if (heightLeft > 0) {
                        pdf.addPage()
                    }
                }

                // 保存 PDF 文件
                const fileName = `机具设备有偿使用费结算协议书-${this.agreementContent.agreementCode}_${formatTime(new Date())}.pdf`
                pdf.save(fileName)

                // 关闭加载提示
                loadingInstance.close()
                this.$message.success('PDF导出成功')
            } catch (error) {
                console.error('PDF导出失败:', error)
                this.$message.error('PDF导出失败，请重试')
            } finally {
                // 恢复 PDF 导出标志
                this.isPdfExporting = false
                await this.$nextTick()
            }
        },

        // ======================
        // 打开协议书编号录入对话框
        openBookCodeDialog() {
            this.bookCodeForm.bookCode = ''
            this.bookCodeDialogVisible = true
        },

        // 重置协议书编号表单
        resetBookCodeForm() {
            this.bookCodeForm.bookCode = ''
        },

        // 保存协议书编号
        saveBookCode() {
            if (!this.bookCodeForm.bookCode || this.bookCodeForm.bookCode.trim() === '') {
                this.$message.warning('请输入协议书编号')
                return
            }

            const params = {
                id: this.agreementIdTemp,
                bookCode: this.bookCodeForm.bookCode.trim()
            }

            updateSltBookCodeById(params).then(response => {
                this.$message.success('协议书编号保存成功')
                this.bookCodeDialogVisible = false
                this.resetBookCodeForm()
                // 刷新协议书信息
                this.getAgreementInfo()
            }).catch(error => {
                // 由统一网络请求封装异常处理提醒，不进行重复提醒了
                //this.$message.error(error)
            })
        },

        // ======================
        // 格式化日期为 YYYY-MM-DD 格式
        formatDate(date) {
            if (!date) return null
            const year = date.getFullYear()
            const month = String(date.getMonth() + 1).padStart(2, '0')
            const day = String(date.getDate()).padStart(2, '0')
            return `${year}-${month}-${day}`
        },

        // 初始化签名图片路径
        initImgPath(path) {
            if (!path) return
            // 判断path前四位是否为http 如果是则直接返回 如果不是则是base64
            if (path.startsWith('http')) {
                return path; // 是http开头，直接返回
            } else if (!path.startsWith('data:image')) {
                return `data:image/png;base64,${path}`; // 不是则拼接base64前缀（假设为png格式，可根据实际调整）
            }
        }
    }
}
</script>
<style lang="scss" scoped>
::v-deep.el-table .fixed-width .el-button--mini {
    width: 80px !important;
    margin-bottom: 10px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    align-items: center;
}

.tabelColumn {
    width: 1000px;
    height: 35px;
    display: flex;
    align-items: center;
    border: 1px solid #9c9c9c;
    // margin-bottom: 1px;
    border-bottom: none;
}

.columnLabel {
    height: 35px;
    line-height: 35px;
    text-align: center;
    border-left: none;
}

.columnContent {
    height: 35px;
    line-height: 35px;
    text-align: center;
    border-left: 1px solid #9c9c9c;
}

.item-new {
    display: flex;
    align-items: center;
}
</style>
