<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-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-form-item>
            <el-form-item prop="agreementCode" style="width: 130px;">
                <el-input v-model="queryParams.agreementCode" placeholder="协议号查询" clearable/>
            </el-form-item>
            <el-form-item prop="isFinish">
                <el-select v-model="queryParams.isFinish" placeholder="竣工状态" clearable filterable style="width: 130px;">
                    <el-option
                        v-for="item in proStatus"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    ></el-option>
                </el-select>

            </el-form-item>
            <el-form-item prop="settlementType" style="display: none">
                <el-select v-model="queryParams.settlementType" placeholder="结算类型筛选" clearable filterable style="width: 130px;">
                    <el-option label="全部"></el-option>
                    <el-option label="工器具" :value="1"></el-option>
                    <el-option label="安全工器具" :value="2"></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-button type="success" icon="el-icon-download" size="mini" @click="exportExcel" :disabled="tableList.length === 0">导出Excel</el-button>
                <el-button type="info" icon="el-icon-document-copy" size="mini" @click="showHistoryReportDialog">查看历史报表</el-button>
                <el-button
                type="success"
                icon="el-icon-download"
                size="mini"
                @click="exportZip"
                :disabled="!canDownload"
                :loading="isExporting">
                {{ exportButtonText }}
                </el-button>
            </el-form-item>
        </el-form>

        <!-- 进度条显示区域 -->
        <div v-if="showProgress" class="progress-container">
            <el-progress
                :percentage="progressPercentage"
                :status="progressStatus"
                :stroke-width="18"
                :text-inside="true"
                :show-text="true">
            </el-progress>
            <div class="progress-info">
                <span class="progress-text">{{ progressText }}</span>
                <span class="progress-detail">{{ currentItem }}/{{ totalItems }} {{ currentFileName }}</span>
                <span class="progress-speed" v-if="downloadSpeed > 0">
                速度: {{ formatBytes(downloadSpeed) }}/s
                </span>
            </div>
            <div class="progress-actions" v-if="showProgress">
                <el-button
                size="mini"
                @click="cancelDownload"
                :disabled="!isExporting"
                v-if="!downloadComplete">
                取消导出
                </el-button>
                <el-button
                size="mini"
                type="success"
                @click="clearProgress"
                v-if="downloadComplete">
                完成
                </el-button>
            </div>
        </div>

        <el-table v-loading="loading"  ref="tableRef" :data="tableList" @selection-change="handleSelectionChange" :max-height="650">
            <el-table-column
                type="selection"
                align="center"
            />
            <el-table-column label="序号" align="center" type="index" width="60">
                <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="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>
            </template>
          </el-table-column>

          <el-table-column label="租赁费用" align="center" prop="leaseCost" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="showCostDetail(scope.row, 'lease')"
                :style="{color: scope.row.leaseCost > 0 ? '#409EFF' : '#606266'}"
                :disabled="!(scope.row.leaseCost > 0)">
                {{ scope.row.leaseCost || 0 }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="维修费用" align="center" prop="repairCost" width="80">
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="showCostDetail(scope.row, 'repair')"
                :style="{color: scope.row.repairCost > 0 ? '#409EFF' : '#606266'}"
                :disabled="!(scope.row.repairCost > 0)">
                {{ scope.row.repairCost || 0 }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="丢失费用" align="center" prop="loseCost" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="showCostDetail(scope.row, 'lose')"
                :style="{color: scope.row.loseCost > 0 ? '#409EFF' : '#606266'}"
                :disabled="!(scope.row.loseCost > 0)">
                {{ scope.row.loseCost || 0 }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="报废费用" align="center" prop="scrapCost" width="80">
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="showCostDetail(scope.row, 'scrap')"
                :style="{color: scope.row.scrapCost > 0 ? '#409EFF' : '#606266'}"
                :disabled="!(scope.row.scrapCost > 0)">
                {{ scope.row.scrapCost || 0 }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="减免费用" align="center" prop="reductionCost" width="80">
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="showCostDetail(scope.row, 'reduction')"
                :style="{color: scope.row.reductionCost > 0 ? '#409EFF' : '#606266'}"
                :disabled="!(scope.row.reductionCost > 0)">
                {{ scope.row.reductionCost || 0 }}
              </el-button>
            </template>
          </el-table-column>
            <el-table-column label="合计费用（元）" align="center" prop="totalCostAll" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span v-if="scope.row.totalCostAll != null && scope.row.totalCostAll != ''">
                  <el-button
                    type="text"
                    @click="showCostDetail(scope.row, 'total')"
                    :style="{color: calculateTotalCost(scope.row) > 0 ? '#409EFF' : '#606266'}"
                    :disabled="!(calculateTotalCost(scope.row) > 0)">
                    {{ calculateTotalCost(scope.row).toFixed(2) }}
                  </el-button>
                </span>
                <span v-else style="color: #909399;">
                  无待结算费用
                </span>
              </template>
            </el-table-column>
            <el-table-column label="竣工状态" align="center" prop="isFinish" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.isFinish == 1" effect="plain">已竣工</el-tag>
                    <el-tag type="warning" v-if="scope.row.isFinish == 0" effect="plain">未竣工</el-tag>
                </template>
            </el-table-column>
          <el-table-column label="竣工日期" align="center" prop="actualEndDate"/>
        </el-table>

       <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            :page-sizes="[10, 50, 200, 500, 2000]"
            @pagination="getList"
            />


        <!-- 费用详情弹窗 -->
        <el-dialog
            :title="costDetailTitle"
            :visible.sync="costDetailVisible"
            width="80%"
            top="5vh"
            :close-on-click-modal="false">
            <!-- 租赁费用详情表格 -->
            <el-table
                v-if="costDetailType === 'lease'"
                v-loading="costDetailLoading"
                :data="costDetailList"
                border
                stripe
                height="500">
                <el-table-column label="序号" align="center" type="index" width="60" />
                <el-table-column label="名称" align="center" prop="name" :show-overflow-tooltip="true" />
                <el-table-column label="型号" align="center" prop="model" :show-overflow-tooltip="true" />
                <el-table-column label="单位" align="center" prop="unit" width="80" />
                <el-table-column label="单价（元）" align="center" prop="unitPrice" width="100" />
                <el-table-column label="数量" align="center" prop="quantity" width="80" />
                <el-table-column label="归还数量" align="center" prop="returnQuantity" width="100" />
                <el-table-column label="租赁开始日期" align="center" prop="leaseDate" width="120" />
                <el-table-column label="租赁结束日期" align="center" prop="returnDate" width="120" />
                <el-table-column label="天数" align="center" prop="days" width="80" />
                <el-table-column label="费用（元）" align="center" prop="cost" width="100">
                    <template slot-scope="scope">
                        {{ scope.row.cost ? scope.row.cost.toFixed(2) : '0.00' }}
                    </template>
                </el-table-column>
            </el-table>

            <!-- 维修费用详情表格 -->
            <el-table
                v-if="costDetailType === 'repair'"
                v-loading="costDetailLoading"
                :data="costDetailList"
                border
                stripe
                height="500">
                <el-table-column label="序号" align="center" type="index" width="60" />
                <el-table-column label="机具名称" align="center" prop="name" :show-overflow-tooltip="true" />
                <el-table-column label="规格型号" align="center" prop="model" :show-overflow-tooltip="true" />
                <el-table-column label="单位" align="center" prop="unit" width="80" />
                <el-table-column label="维修数量" align="center" prop="repairQuantity" width="100" />
                <el-table-column label="是否收费" align="center" prop="partType" width="100">
                    <template slot-scope="scope">
                        <span v-if="scope.row.partType === '收费'">收费</span>
                        <span v-else-if="scope.row.partType === '不收费'">不收费</span>
                        <span v-else>{{ scope.row.partType || '-' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="维修费用（元）" align="center" prop="cost" width="120">
                    <template slot-scope="scope">
                        {{ scope.row.cost ? scope.row.cost.toFixed(2) : '0.00' }}
                    </template>
                </el-table-column>
            </el-table>

            <!-- 丢失费用详情表格 -->
            <el-table
                v-if="costDetailType === 'lose'"
                v-loading="costDetailLoading"
                :data="costDetailList"
                border
                stripe
                height="500">
                <el-table-column label="序号" align="center" type="index" width="60" />
                <el-table-column label="机具名称" align="center" prop="name" :show-overflow-tooltip="true" />
                <el-table-column label="规格型号" align="center" prop="model" :show-overflow-tooltip="true" />
                <el-table-column label="单位" align="center" prop="unit" width="80" />
                <el-table-column label="丢失数量" align="center" prop="loseQuantity" width="100" />
                <el-table-column label="丢失费用（元）" align="center" prop="cost" width="120">
                    <template slot-scope="scope">
                        {{ scope.row.cost ? scope.row.cost.toFixed(2) : '0.00' }}
                    </template>
                </el-table-column>
            </el-table>

            <!-- 报废费用详情表格 -->
            <el-table
                v-if="costDetailType === 'scrap'"
                v-loading="costDetailLoading"
                :data="costDetailList"
                border
                stripe
                height="500">
                <el-table-column label="序号" align="center" type="index" width="60" />
                <el-table-column label="机具名称" align="center" prop="name" :show-overflow-tooltip="true" />
                <el-table-column label="机具规格" align="center" prop="model" :show-overflow-tooltip="true" />
                <el-table-column label="单位" align="center" prop="unit" width="80" />
                <el-table-column label="报废数量" align="center" prop="scrapQuantity" width="100" />
                <el-table-column label="报废费用（元）" align="center" prop="cost" width="120">
                    <template slot-scope="scope">
                        {{ scope.row.cost ? scope.row.cost.toFixed(2) : '0.00' }}
                    </template>
                </el-table-column>
            </el-table>

            <!-- 减免费用详情表格 -->
            <el-table
                v-if="costDetailType === 'reduction'"
                v-loading="costDetailLoading"
                :data="costDetailList"
                border
                stripe
                height="500">
                <el-table-column label="序号" align="center" type="index" width="60" />
                <el-table-column label="机具名称" align="center" prop="name" :show-overflow-tooltip="true" />
                <el-table-column label="机具规格" align="center" prop="model" :show-overflow-tooltip="true" />
                <el-table-column label="单位" align="center" prop="unit" width="80" />
                <el-table-column label="减免数量" align="center" prop="reductionQuantity" width="100" />
                <el-table-column label="减免费用（元）" align="center" prop="cost" width="120">
                    <template slot-scope="scope">
                        {{ scope.row.cost ? scope.row.cost.toFixed(2) : '0.00' }}
                    </template>
                </el-table-column>
            </el-table>

            <!-- 合计费用详情表格 -->
            <el-table
                v-if="costDetailType === 'total'"
                v-loading="costDetailLoading"
                :data="costDetailList"
                border
                stripe
                height="500">
                <el-table-column label="序号" align="center" type="index" width="60" />
                <el-table-column label="名称" align="center" prop="name" :show-overflow-tooltip="true" />
                <el-table-column label="型号" align="center" prop="model" :show-overflow-tooltip="true" />
                <el-table-column label="单位" align="center" prop="unit" width="80" />
                <el-table-column label="单价（元）" align="center" prop="unitPrice" width="100">
                    <template slot-scope="scope">
                        <span v-if="scope.row.costType === 'lease'">{{ scope.row.unitPrice || 0 }}</span>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <el-table-column label="数量" align="center" width="80">
                    <template slot-scope="scope">
                        <span v-if="scope.row.costType === 'lease'">{{ scope.row.quantity || 0 }}</span>
                        <span v-else-if="scope.row.costType === 'repair'">{{ scope.row.repairQuantity || 0 }}</span>
                        <span v-else-if="scope.row.costType === 'lose'">{{ scope.row.loseQuantity || 0 }}</span>
                        <span v-else-if="scope.row.costType === 'scrap'">{{ scope.row.scrapQuantity || 0 }}</span>
                        <span v-else-if="scope.row.costType === 'reduction'">{{ scope.row.reductionQuantity || 0 }}</span>
                        <span v-else>{{ scope.row.quantity || 0 }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="归还数量" align="center" width="100">
                    <template slot-scope="scope">
                        <span v-if="scope.row.costType === 'lease'">{{ scope.row.returnQuantity || 0 }}</span>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <el-table-column label="租赁开始日期" align="center" width="120">
                    <template slot-scope="scope">
                        <span v-if="scope.row.costType === 'lease'">{{ scope.row.leaseDate || '-' }}</span>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <el-table-column label="租赁结束日期" align="center" width="120">
                    <template slot-scope="scope">
                        <span v-if="scope.row.costType === 'lease'">{{ scope.row.returnDate || '-' }}</span>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <el-table-column label="天数" align="center" width="80">
                    <template slot-scope="scope">
                        <span v-if="scope.row.costType === 'lease'">{{ scope.row.days || 0 }}</span>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <el-table-column label="费用（元）" align="center" prop="cost" width="100">
                    <template slot-scope="scope">
                        {{ scope.row.cost ? scope.row.cost.toFixed(2) : '0.00' }}
                    </template>
                </el-table-column>
                <el-table-column label="费用类型" align="center" prop="costType" width="100">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.costType === 'lease'" type="primary">租赁费用</el-tag>
                        <el-tag v-else-if="scope.row.costType === 'repair'" type="warning">维修费用</el-tag>
                        <el-tag v-else-if="scope.row.costType === 'lose'" type="danger">丢失费用</el-tag>
                        <el-tag v-else-if="scope.row.costType === 'scrap'" type="info">报废费用</el-tag>
                        <el-tag v-else-if="scope.row.costType === 'reduction'" type="success">减免费用</el-tag>
                        <el-tag v-else>未知</el-tag>
                    </template>
                </el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" icon="el-icon-download" @click="exportCostDetail">导出Excel</el-button>
                <el-button @click="costDetailVisible = false">关闭</el-button>
            </div>
        </el-dialog>

        <!-- 历史报表选择弹窗 -->
        <el-dialog
            title="查看历史报表"
            :visible.sync="historyReportDialogVisible"
            width="50%"
            top="5vh"
            :close-on-click-modal="false">
            <el-form :model="historyReportParams" size="small" label-width="100px">
                <el-form-item label="选择年月">
                    <el-date-picker
                        v-model="historyReportParams.yearMonth"
                        type="month"
                        placeholder="选择年月"
                        format="yyyy年MM月"
                        value-format="yyyy-MM"
                        style="width: 100%">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="queryHistoryReport">查询</el-button>
                <el-button @click="historyReportDialogVisible = false">关闭</el-button>
            </div>
        </el-dialog>

        <!-- 历史报表列表弹窗 -->
        <el-dialog
            :title="historyReportTitle"
            :visible.sync="historyReportListVisible"
            width="90%"
            top="5vh"
            :close-on-click-modal="false">
            <el-table v-loading="historyReportLoading" :data="historyReportList" border stripe :max-height="600">
                <el-table-column label="序号" align="center" type="index" width="60" />
                <el-table-column label="协议号" align="center" prop="agreementCode" :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="settlementType" width="100">
                    <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>
                    </template>
                </el-table-column>
                <el-table-column label="租赁费用" align="center" prop="leaseCost" width="100">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            @click="showHistoryCostDetail(scope.row, 'lease')"
                            :style="{color: scope.row.leaseCost > 0 ? '#409EFF' : '#606266'}"
                            :disabled="!(scope.row.leaseCost > 0)">
                            {{ scope.row.leaseCost || 0 }}
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column label="维修费用" align="center" prop="repairCost" width="100">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            @click="showHistoryCostDetail(scope.row, 'repair')"
                            :style="{color: scope.row.repairCost > 0 ? '#409EFF' : '#606266'}"
                            :disabled="!(scope.row.repairCost > 0)">
                            {{ scope.row.repairCost || 0 }}
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column label="丢失费用" align="center" prop="loseCost" width="100">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            @click="showHistoryCostDetail(scope.row, 'lose')"
                            :style="{color: scope.row.loseCost > 0 ? '#409EFF' : '#606266'}"
                            :disabled="!(scope.row.loseCost > 0)">
                            {{ scope.row.loseCost || 0 }}
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column label="报废费用" align="center" prop="scrapCost" width="100">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            @click="showHistoryCostDetail(scope.row, 'scrap')"
                            :style="{color: scope.row.scrapCost > 0 ? '#409EFF' : '#606266'}"
                            :disabled="!(scope.row.scrapCost > 0)">
                            {{ scope.row.scrapCost || 0 }}
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column label="合计费用（元）" align="center" prop="costs" width="120">
                    <template slot-scope="scope">
                        <span>{{ calculateTotalCost(scope.row).toFixed(2) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="竣工状态" align="center" prop="isFinish" width="120">
                  <template slot-scope="scope">
                    <el-tag v-if="scope.row.isFinish == 1" effect="plain">已竣工</el-tag>
                    <el-tag type="warning" v-if="scope.row.isFinish == 0" effect="plain">未竣工</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="竣工日期" align="center" prop="actualEndDate" width="120"/>
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button type="success" icon="el-icon-download" @click="exportHistoryReportList" :disabled="historyReportList.length === 0">导出Excel</el-button>
                <el-button @click="historyReportListVisible = false">关闭</el-button>
            </div>
        </el-dialog>

        <!-- 历史费用详情弹窗 -->
        <el-dialog
            :title="historyCostDetailTitle"
            :visible.sync="historyCostDetailVisible"
            width="80%"
            top="5vh"
            :close-on-click-modal="false">
            <!-- 历史租赁费用详情表格 -->
            <el-table
                v-if="historyCostDetailType === 'lease'"
                v-loading="historyCostDetailLoading"
                :data="historyCostDetailList"
                border
                stripe
                height="500">
                <el-table-column label="序号" align="center" type="index" width="60" />
                <el-table-column label="名称" align="center" prop="name" :show-overflow-tooltip="true" />
                <el-table-column label="型号" align="center" prop="model" :show-overflow-tooltip="true" />
                <el-table-column label="单位" align="center" prop="unit" width="80" />
                <el-table-column label="单价（元）" align="center" prop="unitPrice" width="100" />
                <el-table-column label="数量" align="center" prop="quantity" width="80" />
                <el-table-column label="归还数量" align="center" prop="returnQuantity" width="100" />
                <el-table-column label="租赁开始日期" align="center" prop="leaseDate" width="120" />
                <el-table-column label="租赁结束日期" align="center" prop="returnDate" width="120" />
                <el-table-column label="天数" align="center" prop="days" width="80" />
                <el-table-column label="费用（元）" align="center" prop="cost" width="100">
                    <template slot-scope="scope">
                        {{ scope.row.cost ? scope.row.cost.toFixed(2) : '0.00' }}
                    </template>
                </el-table-column>
            </el-table>

            <!-- 历史维修费用详情表格 -->
            <el-table
                v-if="historyCostDetailType === 'repair'"
                v-loading="historyCostDetailLoading"
                :data="historyCostDetailList"
                border
                stripe
                height="500">
                <el-table-column label="序号" align="center" type="index" width="60" />
                <el-table-column label="机具名称" align="center" prop="name" :show-overflow-tooltip="true" />
                <el-table-column label="规格型号" align="center" prop="model" :show-overflow-tooltip="true" />
                <el-table-column label="单位" align="center" prop="unit" width="80" />
                <el-table-column label="维修数量" align="center" prop="repairQuantity" width="100" />
                <el-table-column label="是否收费" align="center" prop="partType" width="100">
                    <template slot-scope="scope">
                        <span v-if="scope.row.partType === '收费'">收费</span>
                        <span v-else-if="scope.row.partType === '不收费'">不收费</span>
                        <span v-else>{{ scope.row.partType || '-' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="维修费用（元）" align="center" prop="cost" width="120">
                    <template slot-scope="scope">
                        {{ scope.row.cost ? scope.row.cost.toFixed(2) : '0.00' }}
                    </template>
                </el-table-column>
            </el-table>

            <!-- 历史丢失费用详情表格 -->
            <el-table
                v-if="historyCostDetailType === 'lose'"
                v-loading="historyCostDetailLoading"
                :data="historyCostDetailList"
                border
                stripe
                height="500">
                <el-table-column label="序号" align="center" type="index" width="60" />
                <el-table-column label="机具名称" align="center" prop="name" :show-overflow-tooltip="true" />
                <el-table-column label="规格型号" align="center" prop="model" :show-overflow-tooltip="true" />
                <el-table-column label="单位" align="center" prop="unit" width="80" />
                <el-table-column label="丢失数量" align="center" prop="loseQuantity" width="100" />
                <el-table-column label="丢失费用（元）" align="center" prop="cost" width="120">
                    <template slot-scope="scope">
                        {{ scope.row.cost ? scope.row.cost.toFixed(2) : '0.00' }}
                    </template>
                </el-table-column>
            </el-table>

            <!-- 历史报废费用详情表格 -->
            <el-table
                v-if="historyCostDetailType === 'scrap'"
                v-loading="historyCostDetailLoading"
                :data="historyCostDetailList"
                border
                stripe
                height="500">
                <el-table-column label="序号" align="center" type="index" width="60" />
                <el-table-column label="机具名称" align="center" prop="name" :show-overflow-tooltip="true" />
                <el-table-column label="机具规格" align="center" prop="model" :show-overflow-tooltip="true" />
                <el-table-column label="单位" align="center" prop="unit" width="80" />
                <el-table-column label="报废数量" align="center" prop="scrapQuantity" width="100" />
                <el-table-column label="报废费用（元）" align="center" prop="cost" width="120">
                    <template slot-scope="scope">
                        {{ scope.row.cost ? scope.row.cost.toFixed(2) : '0.00' }}
                    </template>
                </el-table-column>
            </el-table>

            <div slot="footer" class="dialog-footer">
                <el-button type="success" icon="el-icon-download" @click="exportHistoryCostDetail" :disabled="historyCostDetailList.length === 0">导出Excel</el-button>
                <el-button @click="historyCostDetailVisible = false">关闭</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
  getProjectList,
  getUnitList,
  getAgreementInfoById, getUnitListFilterTeam,
} from '@/api/back/index.js'
import {getSltList, costExamine, getSltReportedList, getSltReportList, getHistoryReportList,
    getHistoryLeaseCostDetails, getHistoryRepairCostDetails, getHistoryLoseCostDetails, getHistoryScrapCostDetails,
    getExportZipUnsettled,getExportZipProgress
} 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 * as XLSX from 'xlsx';
import request from '@/utils/request'

export default {
    name: 'UnreportHome',
    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: {
                disabled: false,
                pageNum: 1,
                pageSize: 10,
                keyWord: undefined,
                sltStatus: '',
                isCommit: '',
                unitId: null,
                projectId: null,
                agreementId: null,
                agreementCode: null,
                isFinish: null,
                settlementType: null,
            },
            openPrint: false,
            // 审批弹窗
            aform: { status: '2' },
            //审批弹窗是否开启
            applyVisible: false,
            id: '',
            agreementIdTemp: '',
            // 协议书内容
            agreementContent: {
                agreementCode: '',
                projectName: '',
                unitName: '',
                leaseCost: '', // 租赁费用
                repairCost: '', // 维修费用
                loseCost: '', // 丢失费用
                scrapCost: '', // 报废费用
                reductionCost: '', // 减免费用
                costAll: '', // 合计费用
                costAllUpper: '', // 合计费用大写
            },
            // 费用详情弹窗相关
            costDetailVisible: false,
            costDetailLoading: false,
            costDetailTitle: '',
            costDetailList: [],
            costDetailType: '', // 当前查看的费用类型
            // 历史报表相关
            historyReportDialogVisible: false,
            historyReportListVisible: false,
            historyReportLoading: false,
            historyReportTitle: '',
            historyReportList: [],
            historyReportParams: {
                yearMonth: null,
            },
            // 历史费用详情相关
            historyCostDetailVisible: false,
            historyCostDetailLoading: false,
            historyCostDetailTitle: '',
            historyCostDetailList: [],
            historyCostDetailType: '', // 当前查看的历史费用类型
            currentHistoryRow: {}, // 当前选中的历史报表行
            proStatus:[
                { id: 0, name: '未竣工' },
                { id: 1, name: '已竣工' },
                { id: 2, name: '空白' },
            ],


            //导出zip相关参数
            isExporting: false,
            showProgress: false,
            downloadComplete: false,
            progressPercentage: 0,
            currentItem: 0,
            totalItems: 0,
            currentFileName: '',
            progressText: '准备导出...',
            progressStatus: '',
            downloadSpeed: 0,
            downloadController: null,
            retryCount: 0,
            maxRetries: 3,
            downloadStartTime: 0,
            downloadedBytes: 0,
        }
    },
    computed: {
        /** 是否可以下载 */
        canDownload() {
            const can = this.ids.length > 0 && !this.isExporting;
            console.log('canDownload检查:', {
                ids: this.ids.length,
                isExporting: this.isExporting,
                can: can
            });
            return can;
        },

        /** 下载按钮文字 */
        exportButtonText() {
            if (this.isExporting) {
                return `导出中 ${this.progressPercentage}%`;
            }
            return `批量导出ZIP${this.ids.length > 0 ? ` (${this.ids.length})` : ''}`;
            },
    },
    created() {
        this.GetUnitData()
        this.GetProData()
        this.getList()
    },
    methods: {
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item)
            this.single = selection.length != 1
            this.multiple = !selection.length
        },

        /** 转换菜单数据结构 */
        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){
            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){
            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
            getSltReportList(this.queryParams).then((response) => {
            console.dir(response)
                this.tableList = response.rows
                this.total = response.total
                this.loading = false
            })
        },

        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.queryParams={
                pageNum: 1,
                pageSize: 10,
                sltStatus: '',
                isCommit:'',
                unitId: null,
                projectId: null,
                agreementId: '',
                agreementCode: '',
                isFinish: null,
                settlementType: null,
            }
            this.resetForm('queryForm')
            this.handleQuery()
        },
        //结算审批查看
        handleView(row) {
            let arr = [];
            arr.push(row);
            this.$emit("goDetail",JSON.stringify(arr));
        },
        //结算审批
        handleExame(row) {
            this.id = row.id
            this.agreementIdTemp = row.agreementId
            this.applyVisible = true
        },
        //提交按钮
        submitListForm() {
            let param = {
                id: this.id,
                status: this.aform.status,
                remark: this.aform.remark,
                agreementId: this.agreementIdTemp,
            }
            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' };
        },


        //********************************************************************** */
        //批量导出zip
        async exportZip() {
            if (!this.ids.length) {
                this.$message.error('请选择要导出的记录')
                return false
            }

            // 确认对话框
            try {
                await this.$confirm(`确定要导出 ${this.ids.length} 个选中项吗？`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                center: true
                });
            } catch (cancel) {
                console.log('用户取消导出');
                return;
            }

            // 初始化下载状态
            this.initializeDownload();
            try {
                let param = []
                this.ids.map(item => {
                    param.push({ agreementId: item.agreementId,settlementType:item.settlementType })
                })
                this.totalItems = param.length;

                const taskId = null
                const payload = {
                    list: param,
                    taskId:null,
                    zipName: `未结算批量明细导出_${new Date().getTime()}`,
                    stream: true
                };

                // 开始下载
                await this.streamDownload(payload);
                this.$refs.tableRef.clearSelection()
            } catch (err) {
                console.error('未结算批量明细导出失败', err);
                this.handleDownloadError(err);
            }

        },

        /** 初始化下载状态 */
        initializeDownload() {
            this.isExporting = true;
            this.showProgress = true;
            this.downloadComplete = false;
            this.progressPercentage = 0;
            this.currentItem = 0;
            this.totalItems = 0;
            this.currentFileName = '';
            this.progressText = '准备导出...';
            this.progressStatus = null;
            this.downloadSpeed = 0;
            this.retryCount = 0;
            this.downloadedBytes = 0;
            this.downloadStartTime = Date.now();
            this.downloadController = new AbortController();
        },

        /** 流式下载方法 - 使用原始的request方式 */
        async streamDownload(payload) {
        try {
            this.progressText = '正在连接服务器...';

            // 使用原始的request方法
            await this.downloadZip(
                '/material/slt_agreement_info/dlExProgress',
                JSON.stringify(payload),
                `${payload.zipName}.zip`,
                {
                    timeout: 0,
                    onDownloadProgress: (progressEvent) => {
                        this.handleDownloadProgress(progressEvent);
                    }
                }
            )
            // 完成状态
            this.handleDownloadComplete();

        } catch (error) {
            if (error.message && error.message.includes('canceled')) {
            this.progressText = '导出已取消';
            this.progressPercentage = 0;
            this.progressStatus = 'exception';
            } else {
            console.error('导出失败:', error);
            this.handleDownloadError(error);
            }
        }
        },

        /** 处理下载进度 */
        handleDownloadProgress(progressEvent) {
        if (progressEvent.total) {
            // ZIP 文件流阶段
            const percentage = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            this.progressPercentage = Math.min(percentage, 99);

            const elapsed = Date.now() - this.downloadStartTime;
            if (elapsed > 0) {
            this.downloadSpeed = progressEvent.loaded * 1000 / elapsed;
            this.progressText = `${this.formatBytes(progressEvent.loaded)} / ${this.formatBytes(progressEvent.total)}`;
            }
        } else {
            // 后端处理文件阶段（无进度）

            // ⭐⭐ 1. 下载中保证 currentItem 不超过总数
            if (this.totalItems > 0) {
            this.currentItem = Math.min(this.currentItem + 1, this.totalItems);
            }

            // ⭐ 2. 百分比始终不超过 100
            this.progressPercentage = Math.min(
            Math.round((this.currentItem / this.totalItems) * 100),
            100
            );

            this.progressText = `处理中：${this.currentItem}/${this.totalItems}`;
        }
        },




        /** 处理下载完成 */
        handleDownloadComplete() {
            // ⭐⭐ 2. 下载完成时补齐
            this.currentItem = this.totalItems;
            this.progressPercentage = 100;

            this.progressText = '导出完成';
            this.progressStatus = 'success';
            this.downloadComplete = true;
            this.isExporting = false;
            this.downloadSpeed = 0;

            this.$message({
                message: '导出完成！',
                type: 'success',
                duration: 3000
            });
        },


        /** 处理下载错误 */
        handleDownloadError(error) {
            console.error('导出失败:', error);

            if (this.retryCount < this.maxRetries) {
                this.retryCount++;
                this.progressText = `导出失败，正在重试 (${this.retryCount}/${this.maxRetries})...`;
                this.progressStatus = 'warning';

                // 3秒后重试
                setTimeout(() => {
                this.exportZip();
                }, 3000);
            } else {
                this.progressText = '导出失败，请重试';
                this.progressStatus = 'exception';
                this.isExporting = false;
                this.$message.error('导出失败: ' + (error.message || '未知错误'));
                }
        },

        /** 取消下载 */
        cancelDownload() {
            if (this.downloadController) {
                this.downloadController.abort();
            }
            this.isExporting = false;
            this.showProgress = false;
            this.$message.info('导出已取消');
        },

        /** 清除进度显示 */
        clearProgress() {
            this.showProgress = false;
            this.downloadComplete = false;
            this.progressPercentage = 0;
            this.currentItem = 0;
            this.totalItems = 0;
            this.downloadSpeed = 0;
            this.progressStatus = null;
            this.currentFileName = '';
        },
        /** 格式化字节大小 */
        formatBytes(bytes, decimals = 2) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const dm = decimals < 0 ? 0 : decimals;
            const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
        },

        //********************************************************************** */


        openPrintDialog(row){
            this.openPrint = true
            try {
                // 直接使用row中的数据，不再调用接口
                this.agreementContent = {
                    agreementCode: row.agreementCode,
                    projectName: row.projectName,
                    unitName: row.unitName,
                    leaseCost: row.leaseCost || 0,
                    repairCost: row.repairCost || 0,
                    loseCost: row.loseCost || 0,
                    scrapCost: row.scrapCost || 0,
                    reductionCost: row.reductionCost || 0
                };
                this.agreementContent.costAll = this.calculateTotalCost(row)
                // costAllUpper 中文大写
                this.agreementContent.costAllUpper = toChineseAmount(this.agreementContent.costAll.toFixed(2))
            } catch (error) {
                console.log('🚀 ~ openPrintDialog ~ error:', error)
            }
        },
        //维修任务单打印
        print() {
          this.$refs.remarksPrintRef.print();
        },

        // 显示费用详情 - 直接使用外层数据，不再调用接口
        showCostDetail(row, costType) {
            const costTypeMap = {
                'lease': '租赁费用',
                'repair': '维修费用',
                'lose': '丢失费用',
                'scrap': '报废费用',
                'reduction': '减免费用',
                'total': '合计费用'
            };

            this.costDetailTitle = `${costTypeMap[costType]}详情 - ${row.agreementCode}`;
            this.costDetailType = costType;
            this.costDetailVisible = true;
            this.costDetailLoading = false; // 直接使用数据，无需加载
            this.costDetailList = [];

            // 直接从row对象中获取已有的费用列表数据
            let sourceList = [];

            // 根据费用类型获取对应的数据列表
            switch (costType) {
                case 'lease':
                    sourceList = row.leaseList || [];
                    break;
                case 'repair':
                    sourceList = row.repairList || [];
                    break;
                case 'lose':
                    sourceList = row.loseList || [];
                    break;
                case 'scrap':
                    sourceList = row.scrapList || [];
                    break;
                case 'reduction':
                    sourceList = row.reductionList || [];
                    break;
                case 'total':
                    // 合计费用显示所有类型的数据
                    const allLists = [
                        ...(row.leaseList || []).map(item => ({...item, costType: 'lease'})),
                        ...(row.repairList || []).map(item => ({...item, costType: 'repair'})),
                        ...(row.loseList || []).map(item => ({...item, costType: 'lose'})),
                        ...(row.scrapList || []).map(item => ({...item, costType: 'scrap'})),
                        ...(row.reductionList || []).map(item => ({...item, costType: 'reduction'}))
                    ];
                    sourceList = allLists;
                    break;
                default:
                    sourceList = [];
            }

            // 根据不同费用类型处理数据
            this.costDetailList = sourceList.map(item => {
                const baseData = {
                    name: item.typeName || '',
                    model: item.modelName || '',
                    unit: item.mtUnitName || '',
                    cost: item.costs || 0,
                    costType: item.costType || costType
                };

                // 根据费用类型添加特定字段
                if (costType === 'lease' || (costType === 'total' && item.costType === 'lease')) {
                    return {
                        ...baseData,
                        unitPrice: item.leasePrice || 0,
                        quantity: item.num || 0,
                        returnQuantity: item.backNum || 0,
                        leaseDate: item.startTime || '',
                        returnDate: item.endTime || '',
                        days: item.leaseDays || 0
                    };
                } else if (costType === 'repair' || (costType === 'total' && item.costType === 'repair')) {
                    return {
                        ...baseData,
                        repairQuantity: item.num || 0,
                        partType: item.partType
                    };
                } else if (costType === 'lose' || (costType === 'total' && item.costType === 'lose')) {
                    return {
                        ...baseData,
                        loseQuantity: item.num || 0
                    };
                } else if (costType === 'scrap' || (costType === 'total' && item.costType === 'scrap')) {
                    return {
                        ...baseData,
                        scrapQuantity: item.num || 0
                    };
                } else if (costType === 'reduction' || (costType === 'total' && item.costType === 'reduction')) {
                    return {
                        ...baseData,
                        reductionQuantity: item.num || 0
                    };
                }

                return baseData;
            });
        },

        // 导出主表格Excel
        exportExcel(){
            if (!this.tableList || this.tableList.length === 0) {
                this.$modal.msgWarning('没有可导出的数据');
                return;
            }
            const formatTime = (date) => {
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0');
                return `${year}${month}${day}_${hours}${minutes}${seconds}`;
            };

            const currentTime = formatTime(new Date());
            this.download(
                '/material/slt_agreement_info/exportUnreported',
                {
                ...this.queryParams,
                disabled: false,
                },
                `未结算报表_${currentTime}.xlsx`
            )
        },

        // 导出费用详情为Excel
        exportCostDetail() {
            if (!this.costDetailList || this.costDetailList.length === 0) {
                this.$modal.msgWarning('没有可导出的数据');
                return;
            }

            try {
                // 根据费用类型定义不同的列配置
                let columns = [];
                let fileName = '';
                let sheetName = '';

                switch (this.costDetailType) {
                    case 'lease':
                        columns = [
                            { key: 'name', title: '名称' },
                            { key: 'model', title: '型号' },
                            { key: 'unit', title: '单位' },
                            { key: 'unitPrice', title: '单价（元）' },
                            { key: 'quantity', title: '数量' },
                            { key: 'returnQuantity', title: '归还数量' },
                            { key: 'leaseDate', title: '租赁开始日期' },
                            { key: 'returnDate', title: '租赁结束日期' },
                            { key: 'days', title: '天数' },
                            { key: 'cost', title: '费用（元）' }
                        ];
                        fileName = `${this.costDetailTitle}`;
                        sheetName = '租赁费用';
                        break;
                    case 'repair':
                        columns = [
                            { key: 'name', title: '机具名称' },
                            { key: 'model', title: '规格型号' },
                            { key: 'unit', title: '单位' },
                            { key: 'repairQuantity', title: '维修数量' },
                            { key: 'partType', title: '是否收费' },
                            { key: 'cost', title: '维修费用（元）' }
                        ];
                        fileName = `${this.costDetailTitle}`;
                        sheetName = '维修费用';
                        break;
                    case 'lose':
                        columns = [
                            { key: 'name', title: '机具名称' },
                            { key: 'model', title: '规格型号' },
                            { key: 'unit', title: '单位' },
                            { key: 'loseQuantity', title: '丢失数量' },
                            { key: 'cost', title: '丢失费用（元）' }
                        ];
                        fileName = `${this.costDetailTitle}`;
                        sheetName = '丢失费用';
                        break;
                    case 'scrap':
                        columns = [
                            { key: 'name', title: '机具名称' },
                            { key: 'model', title: '机具规格' },
                            { key: 'unit', title: '单位' },
                            { key: 'scrapQuantity', title: '报废数量' },
                            { key: 'cost', title: '报废费用（元）' }
                        ];
                        fileName = `${this.costDetailTitle}`;
                        sheetName = '报废费用';
                        break;
                    case 'reduction':
                        columns = [
                            { key: 'name', title: '机具名称' },
                            { key: 'model', title: '机具规格' },
                            { key: 'unit', title: '单位' },
                            { key: 'reductionQuantity', title: '减免数量' },
                            { key: 'cost', title: '减免费用（元）' }
                        ];
                        fileName = `${this.costDetailTitle}`;
                        sheetName = '减免费用';
                        break;
                    case 'total':
                        columns = [
                            { key: 'name', title: '名称' },
                            { key: 'model', title: '型号' },
                            { key: 'unit', title: '单位' },
                            { key: 'unitPrice', title: '单价（元）' },
                            { key: 'quantity', title: '数量' },
                            { key: 'returnQuantity', title: '归还数量' },
                            { key: 'leaseDate', title: '租赁开始日期' },
                            { key: 'returnDate', title: '租赁结束日期' },
                            { key: 'days', title: '天数' },
                            { key: 'cost', title: '费用（元）' },
                            { key: 'costType', title: '费用类型' }
                        ];
                        fileName = `${this.costDetailTitle}`;
                        sheetName = '合计费用';
                        break;
                    default:
                        this.$modal.msgError('未知的费用类型');
                        return;
                }

                // 准备Excel数据
                const excelData = [];

                // 添加表头
                const headerRow = columns.map(col => col.title);
                excelData.push(headerRow);

                // 添加数据行
                this.costDetailList.forEach(row => {
                    const dataRow = columns.map(col => {
                        let value = row[col.key] || '';

                        // 特殊处理费用类型字段
                        if (col.key === 'costType') {
                            const typeMap = {
                                'lease': '租赁费用',
                                'repair': '维修费用',
                                'lose': '丢失费用',
                                'scrap': '报废费用',
                                'reduction': '减免费用'
                            };
                            value = typeMap[value] || value;
                        }

                        // 特殊处理是否收费字段
                        if (col.key === 'partType') {
                            if (value === '收费') {
                                value = '收费';
                            } else if (value === '不收费') {
                                value = '不收费';
                            } else {
                                value = value || '-';
                            }
                        }

                        // 处理数值字段的格式
                        if (col.key === 'cost' || col.key === 'unitPrice') {
                            value = typeof value === 'number' ? parseFloat(value.toFixed(2)) : value;
                        }

                        return value;
                    });
                    excelData.push(dataRow);
                });

                // 创建工作簿和工作表
                const workbook = XLSX.utils.book_new();
                const worksheet = XLSX.utils.aoa_to_sheet(excelData);

                // 设置列宽
                const columnWidths = columns.map(col => {
                    // 根据列内容设置不同的宽度
                    if (col.key === 'name') return { wch: 20 };
                    if (col.key === 'model') return { wch: 15 };
                    if (col.key === 'leaseDate' || col.key === 'returnDate') return { wch: 12 };
                    if (col.key === 'cost' || col.key === 'unitPrice') return { wch: 12 };
                    if (col.key === 'costType') return { wch: 12 };
                    return { wch: 10 };
                });
                worksheet['!cols'] = columnWidths;

                // 添加工作表到工作簿
                XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);

                // 生成Excel文件并下载
                const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
                const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

                // 创建下载链接
                const link = document.createElement('a');
                const url = URL.createObjectURL(blob);
                link.setAttribute('href', url);
                link.setAttribute('download', `${fileName}_${new Date().toISOString().slice(0, 10)}.xlsx`);
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);

                // 清理URL对象
                URL.revokeObjectURL(url);

                this.$modal.msgSuccess('Excel导出成功');
            } catch (error) {
                console.error('导出Excel失败:', error);
                this.$modal.msgError('导出Excel失败，请稍后重试');
            }
        },

        // 计算合计费用
        calculateTotalCost(row) {
            const leaseCost = Number(row.leaseCost) || 0;
            const repairCost = Number(row.repairCost) || 0;
            const loseCost = Number(row.loseCost) || 0;
            const scrapCost = Number(row.scrapCost) || 0;
            const reductionCost = Number(row.reductionCost) || 0;

            return leaseCost + repairCost + loseCost + scrapCost - reductionCost;
        },

        // 显示历史报表选择弹窗
        showHistoryReportDialog() {
            this.historyReportParams.yearMonth = null;
            this.historyReportDialogVisible = true;
        },

        // 查询历史报表
        queryHistoryReport() {
            if (!this.historyReportParams.yearMonth) {
                this.$message.error('请选择年月');
                return;
            }

            this.historyReportLoading = true;
            const params = {
                yearMonth: this.historyReportParams.yearMonth
            };

            getHistoryReportList(params).then((response) => {
                this.historyReportList = response.rows || [];
                this.historyReportTitle = `${this.historyReportParams.yearMonth}历史报表`;
                this.historyReportDialogVisible = false;
                this.historyReportListVisible = true;
                this.historyReportLoading = false;
            }).catch(() => {
                this.historyReportLoading = false;
            });
        },

        // 显示历史费用详情
        showHistoryCostDetail(row, costType) {
            this.currentHistoryRow = row;
            const costTypeMap = {
                'lease': '租赁费用',
                'repair': '维修费用',
                'lose': '丢失费用',
                'scrap': '报废费用'
            };

            this.historyCostDetailTitle = `${costTypeMap[costType]}详情 - ${row.agreementCode}`;
            this.historyCostDetailType = costType;
            this.historyCostDetailVisible = true;
            this.historyCostDetailLoading = true;
            this.historyCostDetailList = [];

            // 根据费用类型调用不同的接口
            const params = {
                agreementId: row.agreementId,
                yearMonth: this.historyReportParams.yearMonth
            };

            let apiCall;
            switch (costType) {
                case 'lease':
                    apiCall = getHistoryLeaseCostDetails(params);
                    break;
                case 'repair':
                    apiCall = getHistoryRepairCostDetails(params);
                    break;
                case 'lose':
                    apiCall = getHistoryLoseCostDetails(params);
                    break;
                case 'scrap':
                    apiCall = getHistoryScrapCostDetails(params);
                    break;
                default:
                    this.historyCostDetailLoading = false;
                    return;
            }

            apiCall.then((response) => {
                const sourceList = response.rows || [];

                // 根据不同费用类型处理数据
                this.historyCostDetailList = sourceList.map(item => {
                    const baseData = {
                        name: item.typeName || '',
                        model: item.modelName || '',
                        unit: item.mtUnitName || '',
                        cost: item.costs || 0,
                        costType: costType
                    };

                    // 根据费用类型添加特定字段
                    if (costType === 'lease') {
                        return {
                            ...baseData,
                            unitPrice: item.leasePrice || 0,
                            quantity: item.num || 0,
                            returnQuantity: item.backNum || 0,
                            leaseDate: item.startTime || '',
                            returnDate: item.endTime || '',
                            days: item.leaseDays || 0
                        };
                    } else if (costType === 'repair') {
                        return {
                            ...baseData,
                            repairQuantity: item.num || 0,
                            partType: item.partType
                        };
                    } else if (costType === 'lose') {
                        return {
                            ...baseData,
                            loseQuantity: item.num || 0
                        };
                    } else if (costType === 'scrap') {
                        return {
                            ...baseData,
                            scrapQuantity: item.num || 0
                        };
                    }

                    return baseData;
                });

                this.historyCostDetailLoading = false;
            }).catch(() => {
                this.historyCostDetailLoading = false;
            });
        },

        // 导出历史报表列表为Excel
        exportHistoryReportList() {
            if (!this.historyReportList || this.historyReportList.length === 0) {
                this.$message.warning('没有可导出的数据');
                return;
            }

            try {
                // 定义Excel列配置
                const columns = [
                    { key: 'index', title: '序号' },
                    { key: 'agreementCode', title: '协议号' },
                    { key: 'unitName', title: '结算单位' },
                    { key: 'projectName', title: '结算工程' },
                    { key: 'settlementType', title: '结算类型' },
                    { key: 'leaseCost', title: '租赁费用' },
                    { key: 'repairCost', title: '维修费用' },
                    { key: 'loseCost', title: '丢失费用' },
                    { key: 'scrapCost', title: '报废费用' },
                    { key: 'totalCost', title: '合计费用（元）' }
                ];

                // 准备Excel数据
                const excelData = [];

                // 添加表头
                const headerRow = columns.map(col => col.title);
                excelData.push(headerRow);

                // 添加数据行
                this.historyReportList.forEach((row, index) => {
                    const dataRow = columns.map(col => {
                        let value = '';

                        if (col.key === 'index') {
                            value = index + 1;
                        } else if (col.key === 'settlementType') {
                            const typeMap = {
                                0: '总费用',
                                1: '工器具',
                                2: '安全工器具'
                            };
                            value = typeMap[row.settlementType] || '';
                        } else if (col.key === 'totalCost') {
                            // 合计费用：转换为数字，保留2位小数
                            value = parseFloat(this.calculateTotalCost(row).toFixed(2));
                        } else if (['leaseCost', 'repairCost', 'loseCost', 'scrapCost'].includes(col.key)) {
                            // 其他金额字段：转换为数字，保留2位小数
                            const numValue = row[col.key] || 0;
                            value = parseFloat(parseFloat(numValue).toFixed(2));
                        } else {
                            value = row[col.key] || '';
                        }

                        return value;
                    });
                    excelData.push(dataRow);
                });

                // 创建工作簿和工作表
                const ws = XLSX.utils.aoa_to_sheet(excelData);
                const wb = XLSX.utils.book_new();
                XLSX.utils.book_append_sheet(wb, ws, '历史报表');

                // 设置列宽
                const colWidths = [
                    { wch: 8 },   // 序号
                    { wch: 15 },  // 协议号
                    { wch: 15 },  // 结算单位
                    { wch: 15 },  // 结算工程
                    { wch: 12 },  // 结算类型
                    { wch: 12 },  // 租赁费用
                    { wch: 12 },  // 维修费用
                    { wch: 12 },  // 丢失费用
                    { wch: 12 },  // 报废费用
                    { wch: 15 }   // 合计费用
                ];
                ws['!cols'] = colWidths;

                // 设置边框和居中对齐
                const border = {
                    top: { style: 'thin' },
                    bottom: { style: 'thin' },
                    left: { style: 'thin' },
                    right: { style: 'thin' }
                };
                const alignment = { horizontal: 'center', vertical: 'center', wrapText: true };

                // 遍历所有单元格，添加边框和居中对齐
                for (let row = 0; row < excelData.length; row++) {
                    for (let col = 0; col < excelData[row].length; col++) {
                        const cellAddress = XLSX.utils.encode_cell({ r: row, c: col });
                        if (!ws[cellAddress]) {
                            ws[cellAddress] = {};
                        }
                        ws[cellAddress].border = border;
                        ws[cellAddress].alignment = alignment;
                    }
                }

                // 导出文件
                const fileName = `历史报表_${this.historyReportParams.yearMonth}.xlsx`;
                XLSX.writeFile(wb, fileName);

                this.$message.success('导出成功');
            } catch (error) {
                console.error('导出失败:', error);
                this.$message.error('导出失败');
            }
        },

        // 导出历史费用详情为Excel
        exportHistoryCostDetail() {
            if (!this.historyCostDetailList || this.historyCostDetailList.length === 0) {
                this.$message.warning('没有可导出的数据');
                return;
            }

            try {
                // 根据费用类型定义不同的列配置
                let columns = [];
                let fileName = '';
                let sheetName = '';

                switch (this.historyCostDetailType) {
                    case 'lease':
                        columns = [
                            { key: 'index', title: '序号' },
                            { key: 'name', title: '名称' },
                            { key: 'model', title: '型号' },
                            { key: 'unit', title: '单位' },
                            { key: 'unitPrice', title: '单价（元）' },
                            { key: 'quantity', title: '数量' },
                            { key: 'returnQuantity', title: '归还数量' },
                            { key: 'startTime', title: '租赁开始日期' },
                            { key: 'endTime', title: '租赁结束日期' },
                            { key: 'leaseDays', title: '租赁天数' },
                            { key: 'cost', title: '费用（元）' }
                        ];
                        fileName = `历史租赁费用详情_${this.currentHistoryRow.agreementCode}_${this.historyReportParams.yearMonth}`;
                        sheetName = '历史租赁费用';
                        break;
                    case 'repair':
                        columns = [
                            { key: 'index', title: '序号' },
                            { key: 'name', title: '机具名称' },
                            { key: 'model', title: '规格型号' },
                            { key: 'unit', title: '单位' },
                            { key: 'quantity', title: '维修数量' },
                            { key: 'cost', title: '维修费用（元）' }
                        ];
                        fileName = `历史维修费用详情_${this.currentHistoryRow.agreementCode}_${this.historyReportParams.yearMonth}`;
                        sheetName = '历史维修费用';
                        break;
                    case 'lose':
                        columns = [
                            { key: 'index', title: '序号' },
                            { key: 'name', title: '机具名称' },
                            { key: 'model', title: '规格型号' },
                            { key: 'unit', title: '单位' },
                            { key: 'quantity', title: '丢失数量' },
                            { key: 'cost', title: '丢失费用（元）' }
                        ];
                        fileName = `历史丢失费用详情_${this.currentHistoryRow.agreementCode}_${this.historyReportParams.yearMonth}`;
                        sheetName = '历史丢失费用';
                        break;
                    case 'scrap':
                        columns = [
                            { key: 'index', title: '序号' },
                            { key: 'name', title: '机具名称' },
                            { key: 'model', title: '机具规格' },
                            { key: 'unit', title: '单位' },
                            { key: 'quantity', title: '报废数量' },
                            { key: 'cost', title: '报废费用（元）' }
                        ];
                        fileName = `历史报废费用详情_${this.currentHistoryRow.agreementCode}_${this.historyReportParams.yearMonth}`;
                        sheetName = '历史报废费用';
                        break;
                    default:
                        this.$message.error('未知的费用类型');
                        return;
                }

                // 准备Excel数据
                const excelData = [];

                // 添加表头
                const headerRow = columns.map(col => col.title);
                excelData.push(headerRow);

                // 添加数据行
                this.historyCostDetailList.forEach((row, index) => {
                    const dataRow = columns.map(col => {
                        let value = '';

                        if (col.key === 'index') {
                            value = index + 1;
                        } else if (['cost', 'unitPrice'].includes(col.key)) {
                            // 金额字段：转换为数字，保留2位小数
                            const numValue = row[col.key] || 0;
                            value = parseFloat(parseFloat(numValue).toFixed(2));
                        } else {
                            value = row[col.key] || '';
                        }

                        return value;
                    });
                    excelData.push(dataRow);
                });

                // 创建工作簿和工作表
                const ws = XLSX.utils.aoa_to_sheet(excelData);
                const wb = XLSX.utils.book_new();
                XLSX.utils.book_append_sheet(wb, ws, sheetName);

                // 设置列宽
                const colWidths = columns.map(() => ({ wch: 15 }));
                ws['!cols'] = colWidths;

                // 设置边框和居中对齐
                const border = {
                    top: { style: 'thin' },
                    bottom: { style: 'thin' },
                    left: { style: 'thin' },
                    right: { style: 'thin' }
                };
                const alignment = { horizontal: 'center', vertical: 'center', wrapText: true };

                // 遍历所有单元格，添加边框和居中对齐
                for (let row = 0; row < excelData.length; row++) {
                    for (let col = 0; col < excelData[row].length; col++) {
                        const cellAddress = XLSX.utils.encode_cell({ r: row, c: col });
                        if (!ws[cellAddress]) {
                            ws[cellAddress] = {};
                        }
                        ws[cellAddress].border = border;
                        ws[cellAddress].alignment = alignment;
                    }
                }

                // 导出文件
                XLSX.writeFile(wb, `${fileName}.xlsx`);

                this.$message.success('导出成功');
            } catch (error) {
                console.error('导出失败:', error);
                this.$message.error('导出失败');
            }
        },

    },
}
</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;
}

//导出zip
/* 进度条容器样式 */
.progress-container {
  margin: 20px 0;
  padding: 20px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  background-color: #f9f9f9;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.progress-info {
  margin-top: 15px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.progress-text {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.progress-detail {
  font-size: 12px;
  color: #666;
}

.progress-speed {
  font-size: 12px;
  color: #409eff;
  font-weight: 500;
}

.progress-actions {
  margin-top: 15px;
  display: flex;
  justify-content: center;
  gap: 10px;
}

/* Element UI Progress 自定义样式 */
::v-deep .el-progress-bar__inner {
  background: linear-gradient(90deg, #409eff 0%, #67c23a 100%);
  transition: width 0.3s ease;
}

::v-deep .el-progress-bar__innerText {
  color: #fff;
  font-weight: bold;
  text-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .progress-container {
    padding: 15px;
    margin: 15px 0;
  }

  .progress-text {
    font-size: 13px;
  }

  .progress-detail,
  .progress-speed {
    font-size: 11px;
  }

  .el-button--mini {
    min-width: 80px;
    padding: 5px 12px;
    font-size: 12px;
  }
}



button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
//

</style>
