<template>
    <div class="app-container" id="costApplyList">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="80px">
            <el-form-item>
                <treeselect
                    ref="treeselectRef"
                    v-model="unitIds"
                    :options="unitList"
                    :normalizer="normalizer"
                    :show-count="true"
                    style="width: 300px"
                    :disable-branch-nodes="true"
                    noChildrenText="没有数据了"
                    noOptionsText="没有数据"
                    noResultsText="没有搜索结果"
                    placeholder="请选择结算单位"
                    @select="unitChange"
                    :multiple="true"
                ></treeselect>
            </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"
                    :disabled="unitIds.length == 0"
                />
            </el-form-item>
            <el-form-item prop="agreementCode">
                <el-input
                    v-model="queryParams.agreementCode"
                    placeholder="请输入协议号"
                    clearable
                    style="width: 240px"
                />
            </el-form-item>
            <el-form-item prop="sltStatus">
                <el-select v-model="queryParams.sltStatus" placeholder="请选择结算状态" clearable filterable>
                    <el-option
                        v-for="dict in dict.type.cost_status"
                        v-if="dict.value !== '2' && dict.value !== '1'"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                    ></el-option>
                </el-select>
            </el-form-item>

            <el-form-item prop="settlementType">
                <el-select v-model="queryParams.settlementType" placeholder="请选择结算类型" clearable filterable>
                    <el-option
                        v-for="(item, index) in settlementTypeList"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                    />
                </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-button type="primary" plain size="mini" @click="handleApplyList">批量结算</el-button>
            </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="tableList" @selection-change="handleSelectionChange" :max-height="650">
            <el-table-column
                type="selection"
                align="center"
                :selectable="row => row.sltStatus == 0 || row.sltStatus == 3"
            />
            <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">
                    <span v-if="scope.row.costs != null && scope.row.costs != ''">
                        {{ scope.row.costs.toFixed(2) }}
                    </span>
                    <span v-else style="color: #909399">无待结费用</span>
                </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 || scope.row.settlementType == 0" effect="plain">
                        总费用
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="结算状态" align="center" prop="sltStatus" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.cost_status" :value="scope.row.sltStatus" />
                </template>
                <!--                <template slot-scope="scope">-->
                <!--                  <dict-tag :value="scope.row.sltStatus">-->
                <!--                    <el-tag size="mini" type="success" v-if="scope.row.auditStatus == 1">已结算</el-tag>-->
                <!--                    <el-tag size="mini" type="danger" v-if="scope.row.auditStatus == 2">部分结算</el-tag>-->
                <!--                    <el-tag size="mini" type="primary" v-if="scope.row.auditStatus == 0">未结算</el-tag>-->
                <!--                  </dict-tag>-->

                <!--                  <span v-if="scope.row.sltStatus == '0'">未结算</span>-->
                <!--                  <span v-if="scope.row.sltStatus == '1'">已结算</span>-->
                <!--                  <span v-if="scope.row.sltStatus == '2'">部分结算</span>-->
                <!--                </template>-->
            </el-table-column>
            <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
            <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="primary"
                        icon="el-icon-edit"
                        @click="handleApply(scope.row)"
                        v-if="scope.row.sltStatus == '0' || scope.row.sltStatus == '3'"
                    >
                        结算申请
                    </el-button>

                    <!-- <el-button type="primary" plain size="mini" @click="openPrintDialog(scope.row)">协议书</el-button> -->
                    <el-button type="primary" plain size="mini" @click="handleDetails(scope.row)">维修单查看</el-button>
                    <el-button type="primary" plain size="mini" @click="handleTransfer(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 :visible.sync="openPrint" width="1100px" append-to-body>
            <div id="checkId">
                <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">
                            机具设备有偿使用费结算协议书
                        </div>
                        <div class="info" style="margin-top: 10px; display: flex; flex-wrap: wrap">
                            <div
                                class="item"
                                style="width: 65%; flex-shrink: 0; margin-bottom: 5px; font-size: 14px"
                            ></div>
                            <div class="item" style="width: 35%; flex-shrink: 0; margin-bottom: 5px; font-size: 14px">
                                <span>协议号：{{ agreementContent.agreementCode }}</span>
                            </div>
                        </div>
                        <div class="tabelColumn">
                            <div class="columnLabel" style="width: 20%">工程名称：</div>
                            <div class="columnContent" style="width: 80%">{{ agreementContent.projectName }}</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 || newData }}
                            </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="columnContent" style="width: 40%">
                                ￥ {{ agreementContent.leaseCost ? agreementContent.leaseCost.toFixed(2) : '0.00' }}
                            </div>
                        </div>
                        <div class="tabelColumn">
                            <div class="columnLabel" style="width: 60%">二、施工机具维修费：</div>
                            <div class="columnContent" style="width: 40%">
                                ￥ {{ agreementContent.repairCost ? agreementContent.repairCost.toFixed(2) : '0.00' }}
                            </div>
                        </div>
                        <div class="tabelColumn">
                            <div class="columnLabel" style="width: 60%">三、施工机具丢失费：</div>
                            <div class="columnContent" style="width: 40%">
                                ￥ {{ agreementContent.loseCost ? agreementContent.loseCost.toFixed(2) : '0.00' }}
                            </div>
                        </div>
                        <div class="tabelColumn">
                            <div class="columnLabel" style="width: 60%">四、施工机具损坏赔偿费：</div>
                            <div class="columnContent" style="width: 40%">
                                ￥ {{ agreementContent.scrapCost ? agreementContent.scrapCost.toFixed(2) : '0.00' }}
                            </div>
                        </div>
                        <div class="tabelColumn">
                            <div class="columnLabel" style="width: 60%">五、施工机具租赁减免费：</div>
                            <div class="columnContent" style="width: 40%">
                                ￥
                                {{
                                    agreementContent.reductionCost ? agreementContent.reductionCost.toFixed(2) : '0.00'
                                }}
                            </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%">
                                ￥ {{ agreementContent.costAll ? agreementContent.costAll.toFixed(2) : '0.00' }}
                            </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" style="width: 33%">
                                <div>
                                    <span>部门负责人：</span>
                                </div>
                            </div>

                            <div class="item" style="width: 33%">
                                <div>
                                    <span>承租负责人：</span>
                                </div>
                            </div>

                            <div class="item" style="width: 33%">
                                <div>
                                    <span>核算员：</span>
                                </div>
                            </div>
                        </div>
                    </vue-easy-print>
                </div>
            </div>

            <div slot="footer" class="dialog-footer" style="text-align: center">
                <el-button type="primary" @click="print">打 印</el-button>
                <!-- <el-button type="success" @click="handleExportAgreement">导 出</el-button> -->
                <el-button type="success" @click="exportWord">导 出</el-button>
                <el-button @click="openPrint = false">关 闭</el-button>
            </div>
        </el-dialog>
        <!-- 维修单查看 -->
        <el-dialog :visible.sync="repairDialogVisible" width="1100px" append-to-body>
            <el-form :model="repairQuery" size="small" inline @submit.native.prevent>
                <el-form-item label="关键字" prop="repairCode">
                    <el-input
                        v-model="repairQuery.repairCode"
                        placeholder="请输入关键字"
                        clearable
                        style="width: 240px"
                    />
                </el-form-item>

                <!-- 表单按钮 -->
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="getRepairList">查询</el-button>
                    <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>

            <el-table
                :data="repairList"
                highlight-current-row
                style="width: 100%"
                v-loading="isLoading"
                :max-height="650"
            >
                <el-table-column
                    type="index"
                    width="55"
                    label="序号"
                    align="center"
                    :index="index => (repairQuery.pageNum - 1) * repairQuery.pageSize + index + 1"
                />
                <el-table-column
                    v-for="(column, index) in tableColumns"
                    show-overflow-tooltip
                    :key="index"
                    :label="column.label"
                    :prop="column.prop"
                    align="center"
                >
                    <!-- 插槽 -->
                    <template v-slot="{ row }" v-if="column.prop == 'repairCode'">
                        <span style="cursor: pointer; color: #409eff">
                            {{ row.repairCode }}
                        </span>
                    </template>
                </el-table-column>
                <!-- 操作 -->
                <el-table-column label="操作" align="center" width="180">
                    <template v-slot="{ row }">
                        <el-button type="primary" size="mini" @click="handleView(row)">
                            查看
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <pagination
                v-show="repairTotal > 0"
                :total="repairTotal"
                :page.sync="repairQuery.pageNum"
                :limit.sync="repairQuery.pageSize"
                @pagination="getRepairList"
            />
            <div slot="footer" class="dialog-footer" style="text-align: right">
                <el-button @click="repairDialogVisible = false">关 闭</el-button>
            </div>
        </el-dialog>

        <el-dialog :visible.sync="repairView" width="80%" append-to-body>
            <el-table
                :data="repairViewList"
                highlight-current-row
                style="width: 100%"
                v-loading="isLoading"
                :max-height="650"
            >
                <el-table-column type="index" width="55" label="序号" align="center" />
                <el-table-column
                    v-for="(column, index) in repairViewColumns"
                    show-overflow-tooltip
                    :key="index"
                    :label="column.label"
                    :prop="column.prop"
                    align="center"
                >
                    <!-- 插槽 -->
                    <template v-slot="{ row }">
                        <span v-if="column.prop == 'manageType'">
                            <span v-if="row.manageType == 0">编码管理</span>
                            <span v-if="row.manageType == 1">数量管理</span>
                        </span>
                        <span v-else>{{ row[column.prop] }}</span>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
        <!-- 直转查看 -->
        <el-dialog :visible.sync="transferView" width="80%" append-to-body>
            <el-form :model="transferQuery" size="small" inline @submit.native.prevent>
                <el-form-item label="关键字" prop="keyWord">
                    <el-input
                        v-model="transferQuery.keyWord"
                        placeholder="请输入关键字"
                        clearable
                        style="width: 240px"
                    />
                </el-form-item>

                <!-- 表单按钮 -->
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="handleQueryTransfer">查询</el-button>
                    <el-button icon="el-icon-refresh" @click="handleTransferReset">重置</el-button>
                </el-form-item>
            </el-form>

            <el-table
                :data="transferList"
                highlight-current-row
                style="width: 100%"
                v-loading="isLoading"
                :max-height="650"
            >
                <el-table-column
                    type="index"
                    width="55"
                    label="序号"
                    align="center"
                    :index="index => (transferQuery.pageNum - 1) * transferQuery.pageSize + index + 1"
                />
                <el-table-column
                    v-for="(column, index) in transferColumns"
                    :show-overflow-tooltip="column.showTooltip"
                    :key="column.prop"
                    :label="column.label"
                    :prop="column.prop"
                    :width="column.width"
                    align="center"
                >
                    <!-- 插槽 -->
                    <template v-slot="{ row }" v-if="column.prop == 'status'">
                        <span>
                            <el-tag v-if="row.status == '0'" type="warning" size="mini" style="margin-right: 5px">待审核</el-tag>
                            <el-tag v-else-if="row.status == '1'" size="mini" style="margin-right: 5px">审核中</el-tag>
                            <el-tag v-else-if="row.status == '2'" type="success" size="mini" style="margin-right: 5px">
                                已完成
                            </el-tag>
                            <el-tag v-else-if="row.status == '3'" type="danger" size="mini" style="margin-right: 5px">
                                已驳回
                            </el-tag>
                        </span>
                    </template>
                </el-table-column>
                <!-- 操作 -->
                <el-table-column label="操作" align="center" width="180">
                    <template v-slot="{ row }">
                        <el-button type="primary" size="mini" @click="handleTransferView(row)">
                            查看
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <pagination
                v-show="transferTotal > 0"
                :total="transferTotal"
                :page.sync="transferQuery.pageNum"
                :limit.sync="transferQuery.pageSize"
                @pagination="getTransferList"
            />
            <div slot="footer" class="dialog-footer" style="text-align: right">
                <el-button @click="transferView = false">关 闭</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    // getProjectList,
    getUnitList,
    getUnitListFilterTeam
    // getAgreementInfoById,
} from '@/api/back/index.js'
import {
    getSltAgreementInfo,
    getProjectListByUnitIds,
    getAgreementInfoById,
    getSltInfo,
    viewRepairCodeApi,
    getRepairDetailsListApi
} 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 printJS from 'print-js'
import ExcelJS from 'exceljs'
import { getReceiveList } from '@/api/business/index'

import {
    Document,
    Packer,
    Paragraph,
    TextRun,
    Table,
    TableRow,
    TableCell,
    AlignmentType,
    WidthType,
    BorderStyle,
    PageOrientation
} from 'docx'

export default {
    name: 'ApplyHome',
    dicts: ['cost_status'],
    components: { Treeselect, vueEasyPrint },
    data() {
        return {
            // 遮罩层
            loading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 总条数
            total: 0,
            // 单位数据
            unitList: [],
            // 工程数据
            proList: [],
            unitIds: [],
            projectIds: null,
            selectTreeProps: {
                children: 'children',
                label: 'name',
                value: 'id',
                multiple: true //false
            },
            // 表格数据
            tableList: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                sltStatus: '',
                settlementType: '1',
                isCommit: '',
                unitId: null,
                projectId: null,
                agreementId: [],
                agreementCode: ''
            },
            settlementTypeList: [
                // { label: '总费用', value: '' },
                { label: '工器具', value: '1' },
                { label: '安全工器具', value: '2' },
            ],
            openPrint: false,
            // 协议书内容
            agreementContent: {
                agreementCode: '',
                projectName: '',
                unitName: '',
                leaseCost: '', // 租赁费用
                repairCost: '', // 维修费用
                loseCost: '', // 丢失费用
                scrapCost: '', // 报废费用
                reductionCost: '', // 减免费用
                costAll: '', // 合计费用
                costAllUpper: '' // 合计费用大写
            },
            newData: new Date().toISOString().split('T')[0],
            // 维修单查看
            isLoading: false,
            repairDialogVisible: false,
            repairQuery: {
                pageNum: 1,
                pageSize: 10,
                repairCode: '',
                agreementId: ''
            },
            repairTotal: 0,
            tableColumns: [
                { label: '维修单号', prop: 'repairCode' },
                { label: '状态', prop: 'repairStatus' },
                { label: '创建人', prop: 'createBy' },
            ],
            repairList: [],
            repairView: false,
            repairViewParams: {
                pageNum: 1,
                pageSize: 10
            },
            repairViewColumns: [
                { label: '退料单位', prop: 'backUnit' },
                { label: '退料工程', prop: 'backPro' },
                { label: '类型名称', prop: 'typeName' },
                { label: '规格型号', prop: 'type' },
                { label: '计量单位', prop: 'unitName' },
                { label: '退料数量', prop: 'typeRepairNum' },
                { label: '已维修数量', prop: 'typeRepairedNum' },
                { label: '报废数量', prop: 'typeScrapNum' },
                { label: '待修数量', prop: 'waitRepairNum' },
                { label: '管理模式', prop: 'manageType' },
            ],
            repairViewList: [],
            transferView: false,
            transferQuery: {
                pageNum: 1,
                pageSize: 10,
                keyWord: '',
                auditProId: '',
                auditUnitId: '',
            },
            transferColumns: [
                { label: '申请时间', prop: 'createTime', width: '100' },
                { label: '申请人', prop: 'createName', width: '90', showTooltip: true },
                { label: '转出单位', prop: 'backUnitName' },
                { label: '转出工程', prop: 'backProName' },
                { label: '转入单位', prop: 'leaseUnitName' },
                { label: '转入工程', prop: 'leaseProName' },
                { label: '物资类型', prop: 'typeName', showTooltip: true },
                { label: '状态', prop: 'status', width: '80' },
                { label: '业务联单', prop: 'businessCode', showTooltip: true },
            ],
            transferList: [],
            transferTotal: 0,
        }
    },
    // updated() {
    //     this.$nextTick(() => {
    //         // 通过 ref 获取 treeselect 组件的 DOM 元素
    //         const treeselectElm = this.$refs.treeselectRef.$el;
    //         if (treeselectElm && typeof treeselectElm.getBoundingClientRect === 'function') {
    //             const rect = treeselectElm.getBoundingClientRect();
    //             // 处理 rect
    //             console.log(rect);
    //         }
    //     });
    // },
    created() {
        this.GetUnitData()
        // this.GetProData()
        this.getList()
        // 设置默认值
        this.queryParams.settlementType = '1' // 或者根据业务逻辑动态设置
    },
    activated() {
        // 组件被 keep-alive 缓存后重新激活时，不重新加载数据
        // 如果需要刷新数据，可以在这里添加逻辑
        console.log('ApplyHome activated - 页面缓存激活')
    },
    deactivated() {
        // 组件被 keep-alive 缓存时
        console.log('ApplyHome deactivated - 页面缓存')
    },
    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

            if (this.queryParams.projectId) {
                this.getAgreementInfo()
            }
        },
        unitChange(val) {
            console.log('Selected values:', val) // 检查选中的值
            console.log('xxxxxxxxx', this.queryParams.unitId)
            console.log('yyyyyyyyy', this.unitIds)
            setTimeout(() => {
                this.queryParams.projectId = null
                this.queryParams.agreementId = null
                this.queryParams.agreementCode = null
                this.GetProData()
            }, 500)
        },
        // 获取 工程名称 列表数据
        // 增加已结算的过滤
        async GetProData() {
            const unitIdsAsNumbers = this.unitIds.map(id => Number(id))
            const params = {
                enableFilterSlt: true,
                unitIds: unitIdsAsNumbers
            }
            const res = await getProjectListByUnitIds(params)
            this.proList = res.data

            this.getAgreementInfo()
        },
        proChange(val) {
            setTimeout(() => {
                this.GetUnitData()
            }, 500)
        },
        // 获取 协议id
        async getAgreementInfo() {
            if (this.unitIds && this.unitIds.length > 0 && this.queryParams.projectId) {
                const params = {
                    unitIds: this.unitIds,
                    projectId: this.queryParams.projectId
                }
                const res = await getAgreementInfoById(params)
                console.log(res)
                if (!res.data && res.data.some(item => !item.agreementId)) {
                    this.$message.error('当前单位和工程无协议！')
                    this.queryParams.unitId = null
                    this.queryParams.projectId = null
                    this.GetUnitData()
                    this.GetProData()
                } else {
                    this.queryParams.agreementId = res.data.map(item => item.agreementId)
                    this.queryParams.agreementCode = res.data.map(item => item.agreementCode).join(',')
                }
            }
        },
        /** 查询列表 */
        getList() {
            this.loading = true
            const params = {
                pageNum: this.queryParams.pageNum,
                pageSize: this.queryParams.pageSize,
                projectId: this.queryParams.projectId,
                sltStatus: this.queryParams.sltStatus,
                settlementType: this.queryParams.settlementType,
                agreementCode: this.queryParams.agreementCode,
                // ...this.queryParams,
                unitIds: this.unitIds
            }
            getSltAgreementInfo(params).then(response => {
                this.tableList = response.data.rows
                this.total = response.data.total
                this.loading = false
            })
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.unitIds = []
            this.projectIds = []
            this.queryParams = {
                pageNum: 1,
                pageSize: 10,
                sltStatus: '',
                settlementType: '',
                isCommit: '',
                unitId: null,
                projectId: null,
                agreementId: [],
                agreementCode: ''
            }
            this.resetForm('queryForm')
            this.handleQuery()
        },
        //结算申请
        handleApply(row) {
            console.log('🚀 handleApply 被调用，传入数据:', row)
            row.settlementType = this.queryParams.settlementType
            let arr = []
            arr.push(row)
            console.log('🚀 准备发送的数据:', arr)
            console.log('🚀 JSON化后的数据:', JSON.stringify(arr))
            // 注意：'/cost/costApplyDetail' 路由不存在，使用组件切换方式
            this.$emit('goDetail', JSON.stringify(arr))
            console.log('🚀 goDetail 事件已发出')
        },
        handleApplyList() {
            if (this.ids.length < 1) {
                this.$message.error('请勾选需要结算的数据！')
                return
            }
            if (this.ids.length > 0) {
                let arr = this.ids
                this.$emit('goDetail', JSON.stringify(arr))
            }
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item)
            this.single = selection.length != 1
            this.multiple = !selection.length
        },
        async openPrintDialog(row) {
            row.settlementType = this.queryParams.settlementType
            this.openPrint = true
            try {
                const res = await getSltInfo([row])
                console.log('🚀 ~ openPrintDialog ~ res:', res)
                if (!res.data) return
                this.agreementContent = res.data
                this.agreementContent.agreementCode = row.agreementCode
                this.agreementContent.costAll =
                    Number(res.data.leaseCost) +
                    Number(res.data.repairCost) +
                    Number(res.data.scrapCost) +
                    Number(res.data.loseCost) -
                    Number(res.data.reductionCost)
                // costAllUpper 中文大写
                this.agreementContent.costAllUpper = toChineseAmount(this.agreementContent.costAll.toFixed(2))
            } catch (error) {
                console.log('🚀 ~ openPrintDialog ~ error:', error)
            }
        },
        handleDetails(row) {
            this.repairQuery.agreementId = row.agreementId
            this.repairDialogVisible = true
            this.getRepairList()
        },
        handleTransfer(row) {
            this.transferQuery.keyWord = ''
            this.transferQuery.pageNum = 1
            this.transferQuery.pageSize = 10
            this.transferQuery.auditProId = row.projectId
            this.transferQuery.auditUnitId = row.unitId
            this.transferView = true
            this.getTransferList()
        },
        handleQueryTransfer() {
            this.transferQuery.pageNum = 1
            this.getTransferList()
        },
        async getTransferList() {
            try {
                this.isLoading = true
                const res = await getReceiveList(this.transferQuery)
                console.log('🚀 ~ 获取列表 ~ res:', res)
                this.transferList = res.rows || []
                this.transferTotal = res.total || 0
            } catch (error) {
                console.log('🚀 ~ 获取列表 ~ error:', error)
                this.transferList = []
                this.transferTotal = 0
            } finally {
                this.isLoading = false
            }
        },
        handleTransferReset() {
            this.transferQuery.keyWord = ''
            this.transferQuery.pageNum = 1
            this.transferQuery.pageSize = 10
            this.getTransferList()
        },
        handleTransferView(row) {
            this.transferView = false
            this.$router.push({
                name: 'direct-rotation-apply',
                query: {
                    id: row.id,
                    flowId: row.flowId,
                    taskId: row.id,
                    type: 'detail',
                    nodeId: row.nodeId
                }
            })
        },
        async getRepairList() {
            try {
                this.isLoading = true
                const res = await viewRepairCodeApi({ ...this.repairQuery,settlementType:this.queryParams.settlementType })
                this.repairList = res.rows || []
                this.repairTotal = res.total || 0
            } catch (error) {
                console.log('🚀 ~ getRepairList ~ error:', error)
            } finally {
                this.isLoading = false
            }
        },
        handleReset() {
            this.repairQuery.repairCode = ''
            this.getRepairList()
        },
        handleView(row) {
            // this.repairDialogVisible = false
            // this.$router.push({
            //     path: '/repair/repairManage',
            //     query: {
            //         code: row.repairCode
            //     }
            // })
            this.repairView = true
            this.getRepairDetailsList(row)
        },
        async getRepairDetailsList(row) {
            try {
                this.isLoading = true
                const res = await getRepairDetailsListApi({ taskId: row.taskId })
                this.repairViewList = res.data
            } catch (error) {
                console.log('🚀 ~ error:', error)
            } finally {
                this.isLoading = false
            }
        },
        //维修任务单打印
        print() {
            this.$refs.remarksPrintRef.print()
        },

        // 导出协议书
        async handleExportAgreement() {
            try {
                const workbook = new ExcelJS.Workbook()
                const worksheet = workbook.addWorksheet('协议书')

                // 设置列宽
                worksheet.columns = [
                    { header: '', key: 'col1', width: 30 },
                    { header: '', key: 'col2', width: 30 },
                    { header: '', key: 'col3', width: 20 },
                    { header: '', key: 'col4', width: 30 }
                ]

                // 定义边框样式
                const borderStyle = {
                    top: { style: 'thin', color: { argb: 'FF000000' } },
                    bottom: { style: 'thin', color: { argb: 'FF000000' } },
                    left: { style: 'thin', color: { argb: 'FF000000' } },
                    right: { style: 'thin', color: { argb: 'FF000000' } }
                }

                // 标题 - 跨行展示
                const titleRow = worksheet.addRow(['机具设备有偿使用费结算协议书', '', '', ''])
                titleRow.height = 30
                // 先合并单元格
                worksheet.mergeCells('A1:D1')
                // 然后设置合并后的单元格样式
                const titleCell = worksheet.getCell('A1')
                titleCell.value = '机具设备有偿使用费结算协议书'
                titleCell.font = { bold: true, size: 16 }
                titleCell.alignment = { horizontal: 'center', vertical: 'center' }
                titleCell.border = borderStyle
                // 为其他单元格也设置边框
                titleRow.getCell(2).border = borderStyle
                titleRow.getCell(3).border = borderStyle
                titleRow.getCell(4).border = borderStyle

                // 协议号行 - 单独一行
                const agreementCode = this.agreementContent.agreementCode || ''
                const agreementRow = worksheet.addRow(['协议号：', agreementCode, '', ''])
                agreementRow.getCell(1).alignment = { horizontal: 'right', vertical: 'center' }
                agreementRow.getCell(2).alignment = { horizontal: 'left', vertical: 'center' }
                agreementRow.getCell(3).alignment = { horizontal: 'center', vertical: 'center' }
                agreementRow.getCell(4).alignment = { horizontal: 'center', vertical: 'center' }
                agreementRow.height = 25
                agreementRow.eachCell((cell) => {
                    cell.border = borderStyle
                })

                // 工程名称
                const projectName = this.agreementContent.projectName || ''
                const projectRow = worksheet.addRow(['工程名称：', projectName, '', ''])
                projectRow.getCell(1).alignment = { horizontal: 'right', vertical: 'center' }
                projectRow.getCell(2).alignment = { horizontal: 'left', vertical: 'center' }
                projectRow.height = 25
                projectRow.eachCell((cell) => {
                    cell.border = borderStyle
                })
                worksheet.mergeCells('B3:D3')
                worksheet.mergeCells('B4:D4')

                // 承租单位和日期
                const unitName = this.agreementContent.unitName || ''
                const applyDate = this.agreementContent.applyTime || this.newData || ''
                const unitRow = worksheet.addRow(['承租单位：', unitName, '日期：', applyDate])
                unitRow.getCell(1).alignment = { horizontal: 'right', vertical: 'center' }
                unitRow.getCell(2).alignment = { horizontal: 'left', vertical: 'center' }
                unitRow.getCell(3).alignment = { horizontal: 'right', vertical: 'center' }
                unitRow.getCell(4).alignment = { horizontal: 'left', vertical: 'center' }
                unitRow.height = 25
                unitRow.eachCell((cell) => {
                    cell.border = borderStyle
                })

                // 结算项目及金额
                const headerRow = worksheet.addRow(['结算项目及金额(元)'])
                headerRow.font = { bold: true }
                headerRow.eachCell((cell) => {
                    cell.border = borderStyle
                })

                // 费用项目
                const leaseCost = this.agreementContent.leaseCost ? Number(this.agreementContent.leaseCost).toFixed(2) : '0.00'
                const leaseRow = worksheet.addRow(['一、施工机具有偿使用费：', leaseCost, '', ''])
                leaseRow.getCell(1).alignment = { horizontal: 'left' }
                leaseRow.getCell(2).alignment = { horizontal: 'right' }
                leaseRow.eachCell((cell) => {
                    cell.border = borderStyle
                })

                const repairCost = this.agreementContent.repairCost ? Number(this.agreementContent.repairCost).toFixed(2) : '0.00'
                const repairRow = worksheet.addRow(['二、施工机具维修费：', repairCost, '', ''])
                repairRow.getCell(1).alignment = { horizontal: 'left' }
                repairRow.getCell(2).alignment = { horizontal: 'right' }
                repairRow.eachCell((cell) => {
                    cell.border = borderStyle
                })

                const loseCost = this.agreementContent.loseCost ? Number(this.agreementContent.loseCost).toFixed(2) : '0.00'
                const loseRow = worksheet.addRow(['三、施工机具丢失费：', loseCost, '', ''])
                loseRow.getCell(1).alignment = { horizontal: 'left' }
                loseRow.getCell(2).alignment = { horizontal: 'right' }
                loseRow.eachCell((cell) => {
                    cell.border = borderStyle
                })

                const scrapCost = this.agreementContent.scrapCost ? Number(this.agreementContent.scrapCost).toFixed(2) : '0.00'
                const scrapRow = worksheet.addRow(['四、施工机具损坏赔偿费：', scrapCost, '', ''])
                scrapRow.getCell(1).alignment = { horizontal: 'left' }
                scrapRow.getCell(2).alignment = { horizontal: 'right' }
                scrapRow.eachCell((cell) => {
                    cell.border = borderStyle
                })

                const reductionCost = this.agreementContent.reductionCost ? Number(this.agreementContent.reductionCost).toFixed(2) : '0.00'
                const reductionRow = worksheet.addRow(['五、施工机具租赁减免费：', reductionCost, '', ''])
                reductionRow.getCell(1).alignment = { horizontal: 'left' }
                reductionRow.getCell(2).alignment = { horizontal: 'right' }
                reductionRow.eachCell((cell) => {
                    cell.border = borderStyle
                })

                // 合计
                const costAllUpper = this.agreementContent.costAllUpper || ''
                const costAll = this.agreementContent.costAll ? Number(this.agreementContent.costAll).toFixed(2) : '0.00'
                const totalRow = worksheet.addRow(['费用合计金额（大写）：', costAllUpper, '￥', costAll])
                totalRow.font = { bold: true }
                totalRow.getCell(1).alignment = { horizontal: 'left' }
                totalRow.getCell(2).alignment = { horizontal: 'left' }
                totalRow.getCell(3).alignment = { horizontal: 'center' }
                totalRow.getCell(4).alignment = { horizontal: 'right' }
                totalRow.eachCell((cell) => {
                    cell.border = borderStyle
                })

                // 说明
                const remarkHeaderRow = worksheet.addRow(['说明： 本协议一式两份，甲方一份，乙方一份，经双方签字后生效。'])
                remarkHeaderRow.font = { bold: true }
                remarkHeaderRow.eachCell((cell) => {
                    cell.border = borderStyle
                })
                worksheet.mergeCells('A13:D13')

                // 备注
                const noteHeaderRow = worksheet.addRow(['备注： 此费用仅为在机具（物流）分公司发生费用，未计从项目部领用机具费用。'])
                noteHeaderRow.font = { bold: true }
                noteHeaderRow.eachCell((cell) => {
                    cell.border = borderStyle
                })

                worksheet.mergeCells('A14:D14')


                // 导出
                const buffer = await workbook.xlsx.writeBuffer()
                const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
                const url = window.URL.createObjectURL(blob)
                const link = document.createElement('a')
                link.href = url
                link.download = `协议书_${this.agreementContent.agreementCode}_${new Date().getTime()}.xlsx`
                link.click()
                window.URL.revokeObjectURL(url)
                this.$message.success('导出成功')
            } catch (error) {
                console.error('导出失败:', error)
                this.$message.error('导出失败')
            }
        },

        /** 删除按钮操作 */
        handleDelete(row) {
            // const agreementId = row.agreementId;
            // let param = {
            //   agreementId:row.agreementId+''
            // }
            // this.$modal.confirm('是否确认删除该数据项？').then(function() {
            //   return removeAgreement(param);
            // }).then(() => {
            //   this.getList();
            //   this.$modal.msgSuccess("删除成功");
            // }).catch(() => {});
        },
        /** 导出按钮操作 */
        handleExport() {
            // this.download('material/agreementInfo/export', {
            //   ...this.queryParams
            // }, `协议_${new Date().getTime()}.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,
                                                width: { size: 25, type: WidthType.PERCENTAGE },
                                                children: [
                                                    new Paragraph({
                                                        alignment: AlignmentType.CENTER,
                                                        text: '工程名称：'
                                                    })
                                                ]
                                            }),
                                            new TableCell({
                                                ...cellOpts,
                                                width: { size: 75, type: WidthType.PERCENTAGE },
                                                columnSpan: 3,
                                                children: [
                                                    new Paragraph({
                                                        alignment: AlignmentType.CENTER,
                                                        text: data.projectName
                                                    })
                                                ]
                                            })
                                        ]
                                    }),

                                    // 承租单位 + 日期
                                    new TableRow({
                                        children: [
                                            new TableCell({
                                                ...cellOpts,
                                                width: { size: 25, type: WidthType.PERCENTAGE },
                                                children: [
                                                    new Paragraph({
                                                        alignment: AlignmentType.CENTER,
                                                        text: '承租单位：'
                                                    })
                                                ]
                                            }),
                                            new TableCell({
                                                ...cellOpts,
                                                width: { size: 40, type: WidthType.PERCENTAGE },
                                                children: [
                                                    new Paragraph({
                                                        alignment: AlignmentType.CENTER,
                                                        text: data.unitName
                                                    })
                                                ]
                                            }),
                                            new TableCell({
                                                ...cellOpts,
                                                width: { size: 10, type: WidthType.PERCENTAGE },
                                                children: [
                                                    new Paragraph({ alignment: AlignmentType.CENTER, text: '日期：' })
                                                ]
                                            }),
                                            new TableCell({
                                                ...cellOpts,
                                                width: { size: 25, 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
                                                    })
                                                ]
                                            })
                                        ]
                                    }),

                                    // 金额明细
                                    ...[
                                        ['一、施工机具有偿使用费：', `￥ ${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)}`]
                                    ].map(
                                        ([label, value]) =>
                                            new TableRow({
                                                children: [
                                                    new TableCell({
                                                        ...cellOpts,
                                                        columnSpan: 2,
                                                        children: [
                                                            new Paragraph({
                                                                alignment: AlignmentType.CENTER,
                                                                text: label
                                                            })
                                                        ]
                                                    }),
                                                    new TableCell({
                                                        ...cellOpts,
                                                        columnSpan: 2,
                                                        children: [
                                                            new Paragraph({
                                                                alignment: AlignmentType.CENTER,
                                                                text: value
                                                            })
                                                        ]
                                                    })
                                                ]
                                            })
                                    ),

                                    // 合计
                                    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`)
        }
    }
}
</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: 50px;
    display: flex;
    align-items: center;
    border: 1px solid #9c9c9c;
    // margin-bottom: 1px;
    border-bottom: none;
}
.columnLabel {
    height: 50px;
    line-height: 50px;
    text-align: center;
    border-left: none;
}
.columnContent {
    height: 50px;
    line-height: 50px;
    text-align: center;
    border-left: 1px solid #9c9c9c;
}
</style>
