<template>
  <div class="app-container">
    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-form :inline="true" label-width="80px" style="margin-bottom: 20px;">
      <el-form-item label="分公司" prop="impUnitName">
        <el-select
          v-model="queryParams.impUnitName"
          placeholder="请选择分公司"
          clearable
          filterable
          style="width: 240px"
          @change="handleImpUnitChange"
        >
          <el-option
            v-for="item in impUnitOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="项目部" prop="departName">
        <el-select
          v-model="queryParams.departName"
          placeholder="请选择项目部"
          clearable
          filterable
          style="width: 240px"
          @change="handleDepartChange"
        >
          <el-option
            v-for="item in departOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
        <el-form-item label="结算工程">
          <el-select
          v-model="selectedProject"
          placeholder="请选择工程"
          clearable
          filterable
          style="width: 240px"
          @change="loadTeamList"
        >
          <el-option
            v-for="item in projectList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        </el-form-item>

        <el-form-item label="结算班组">
          <el-select
            v-model="selectedTeams"
            placeholder="请选择班组"
            clearable
            filterable
            multiple
            style="width: 240px"
          >
            <el-option
              v-for="item in teamList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
        </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery" >查询</el-button>
          <el-button @click="reset">重置</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 结算数据展示 -->
    <div>
      <el-row style="width: 100%">
        <el-col :span="18">
          <el-button type="primary" size="mini" @click="handleExport1" :disabled="!hasData">租赁明细导出</el-button>
          <el-button type="primary" size="mini" @click="handleExport3" :disabled="!hasData">维修明细导出</el-button>
          <el-button type="primary" size="mini" @click="handleExport4" :disabled="!hasData">报废明细导出</el-button>
          <el-button type="primary" size="mini" @click="handleExport2" :disabled="!hasData">未归还明细导出</el-button>
          <el-button type="primary" size="mini" @click="handleExport5" :disabled="!hasData">减免明细导出</el-button>
          <el-button type="warning" size="mini" @click="handleExportAll" :disabled="!hasData">全部明细导出</el-button>
          <!-- <el-button type="warning" size="mini" @click="handleExportEach" :disabled="!hasData">各结算明细导出</el-button> -->
          <el-button type="success" size="mini" @click="handleAdd" :disabled="!hasData">提交</el-button>
        </el-col>
      </el-row>

      <div style="margin-top: 20px">
        <div class="tabelAllTop">
          <div class="costTop">结算费用</div>
        </div>
        <div class="tabelAllTopUnit">
          <div class="costTopUnit">结算班组</div>
          <div class="costRightUnit">
            {{ unitName || '请先选择班组并查询' }}
          </div>
        </div>
        <div class="tabelAllTopUnit">
          <div class="costTopUnit">结算工程</div>
          <div class="costRightUnit">
            {{ projectName || '请先选择工程并查询' }}
          </div>
        </div>
        <div class="tabelAllTopUnit">
          <div class="costTopUnit">出场日期</div>
          <div class="costRightUnit">
            {{ actualTimeAndName || '请先选择班组并查询' }}
          </div>
        </div>

        <!-- 租赁费用明细 -->
        <el-table :data="leaseList"   max-height="500px">
          <el-table-column label="租赁（超期）费用明细" align="center" >
            <el-table-column label="序号" align="center" type="index" width="60" />
            <el-table-column label="单位名称" align="center" prop="unitName" :show-overflow-tooltip="true" width="150" />
            <el-table-column label="设备名称" align="center" prop="typeName" :show-overflow-tooltip="true" />
            <el-table-column label="规格型号" align="center" prop="modelName" :show-overflow-tooltip="true" />
            <el-table-column label="计量单位" align="center" prop="mtUnitName" :show-overflow-tooltip="true" />
            <el-table-column label="租赁单价" align="center" prop="leasePrice" :show-overflow-tooltip="true">
              <template slot-scope="scope" v-show="scope.row.leasePrice">
                {{ scope.row.leasePrice.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="租赁数量" align="center" prop="num" :show-overflow-tooltip="true"/>
            <el-table-column label="租赁开始日期" align="center" prop="startTime" :show-overflow-tooltip="true" />
            <el-table-column label="租赁结束日期 " align="center" prop="endTime" :show-overflow-tooltip="true" />
            <el-table-column label="租赁天数" align="center" prop="leaseDays" :show-overflow-tooltip="true"/>
            <el-table-column label="出场日期" align="center" prop="actualExitTime" :show-overflow-tooltip="true"/>
            <el-table-column label="超期日期" align="center" prop="overTime" :show-overflow-tooltip="true"/>
            <el-table-column label="超期天数" align="center" prop="overDay" :show-overflow-tooltip="true"/>
            <el-table-column label="超期费用（元）" align="center" prop="costs" :show-overflow-tooltip="true">
              <template slot-scope="scope" v-show="scope.row.costs">
                {{ scope.row.costs.toFixed(2) }}
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
        <div class="tabelAll">
          <div class="columnAllNum">费用小计：</div>
          <div class="columnAll">
            {{ leaseCost || '0.00' }}
          </div>
        </div>
      </div>

      <!-- 维修费用明细 -->
      <div>
        <el-table :data="repairList" max-height="500px">
          <el-table-column label="维修费用明细" align="center" >
            <el-table-column label="序号" align="center" type="index" width="60" />
            <el-table-column label="单位名称" align="center" prop="unitName" :show-overflow-tooltip="true" width="150" />
            <el-table-column label="设备名称" align="center" prop="typeName" :show-overflow-tooltip="true" />
            <el-table-column label="规格型号" align="center" prop="modelName" :show-overflow-tooltip="true" />
            <el-table-column label="计量单位" align="center" prop="mtUnitName" :show-overflow-tooltip="true" />
            <el-table-column label="维修数量" align="center" prop="num" :show-overflow-tooltip="true"/>
            <el-table-column label="是否收费" align="center" prop="partType" :show-overflow-tooltip="true" />
            <el-table-column label="维修费用（元）" align="center" prop="costs" :show-overflow-tooltip="true">
              <template slot-scope="scope" v-show="scope.row.costs">
                {{ scope.row.costs.toFixed(2) }}
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
        <div class="tabelAll">
          <div class="columnAllNum">费用小计：</div>
          <div class="columnAll">
            {{ repairCost || '0.00' }}
          </div>
        </div>
      </div>

      <!-- 报废费用明细 -->
      <div>
        <el-table :data="scrapList" max-height="500px">
          <el-table-column label="报废费用明细" align="center">
            <el-table-column label="序号" align="center" type="index" width="60" />
            <el-table-column label="单位名称" align="center" prop="unitName" :show-overflow-tooltip="true" width="150" />
            <el-table-column label="设备名称" align="center" prop="typeName" :show-overflow-tooltip="true" />
            <el-table-column label="规格型号" align="center" prop="modelName" :show-overflow-tooltip="true" />
            <el-table-column label="计量单位" align="center" prop="mtUnitName" :show-overflow-tooltip="true" />
            <el-table-column label="报废数量" align="center" prop="num" :show-overflow-tooltip="true"/>
            <el-table-column label="是否收费" align="center" prop="partType" :show-overflow-tooltip="true" />
            <el-table-column label="报废费用（元）" align="center" prop="costs" :show-overflow-tooltip="true">
              <template slot-scope="scope" v-show="scope.row.costs">
                {{ scope.row.costs.toFixed(2) }}
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
        <div class="tabelAll">
          <div class="columnAllNum">费用小计：</div>
          <div class="columnAll">
            {{ scrapCost || '0.00' }}
          </div>
        </div>
      </div>

      <!-- 丢失费用明细 -->
      <div>
        <el-table :data="loseList" max-height="500px">
          <el-table-column label="未归还费用明细" align="center">
            <el-table-column label="序号" align="center" type="index" width="60" />
            <el-table-column label="单位名称" align="center" prop="unitName" :show-overflow-tooltip="true" width="150" />
            <el-table-column label="设备名称" align="center" prop="typeName" :show-overflow-tooltip="true" />
            <el-table-column label="规格型号" align="center" prop="modelName" :show-overflow-tooltip="true" />
            <el-table-column label="计量单位" align="center" prop="mtUnitName" :show-overflow-tooltip="true" />
            <el-table-column label="丢失数量" align="center" prop="num" :show-overflow-tooltip="true"/>
            <el-table-column label="原值（元）" align="center" prop="buyPrice" :show-overflow-tooltip="true" >
              <template slot-scope="scope" v-show="scope.row.buyPrice">
                {{ scope.row.buyPrice.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="未归还费用（元）" align="center" prop="costs" :show-overflow-tooltip="true">
              <template slot-scope="scope" v-show="scope.row.costs">
                {{ scope.row.costs.toFixed(2) }}
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
        <div class="tabelAll">
          <div class="columnAllNum">费用小计：</div>
          <div class="columnAll">
            {{ loseCost || '0.00' }}
          </div>
        </div>
      </div>

      <!-- 减免费用明细 -->
      <div>
        <el-table :data="reducList">
          <el-table-column label="减免费用明细" align="center">
            <el-table-column label="序号" align="center" type="index" width="60" />
            <el-table-column label="单位名称" align="center" prop="unitName" :show-overflow-tooltip="true" width="150" />
            <el-table-column label="设备名称" align="center" prop="typeName" :show-overflow-tooltip="true" />
            <el-table-column label="规格型号" align="center" prop="modeName" :show-overflow-tooltip="true" />
            <el-table-column label="计量单位" align="center" prop="mtUnitName" :show-overflow-tooltip="true" />
            <el-table-column label="租赁单价" align="center" prop="leasePrice" :show-overflow-tooltip="true" />
            <el-table-column label="减免数量" align="center" prop="reduceNum" :show-overflow-tooltip="true" />
            <el-table-column label="减免开始日期" align="center" prop="startTime" :show-overflow-tooltip="true" />
            <el-table-column label="减免结束日期" align="center" prop="endTime" :show-overflow-tooltip="true" />
            <el-table-column label="减免天数" align="center" prop="days" :show-overflow-tooltip="true" />
            <el-table-column label="减免原因" align="center" prop="remark" :show-overflow-tooltip="true" />
            <el-table-column label="减免费用（元）" align="center" prop="leaseMoney" :show-overflow-tooltip="true">
              <template slot-scope="scope" v-show="scope.row.leaseMoney">
                {{ scope.row.leaseMoney.toFixed(2) }}
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
        <div class="tabelAllBottom">
          <div class="columnAllNum">费用小计：</div>
          <div class="columnAll">
            {{ reducCost || '0.00' }}
          </div>
        </div>
        <div class="tabelAllBottom">
          <div class="columnAllNum">合计：</div>
          <div class="columnAll">
            {{ costAll ? costAll.toFixed(2) : '0.00' }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getClzSltInfo, submitClzCosts } from '@/api/cost/cost'
import {
   getClzProjectListApi,getClzTeamListApi,getImpUnitListApi,getDepartListByImpUnitApi
} from '@/api/materialsStation'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'SettlementAdd',
  components: {
    Treeselect
  },
  data() {
    return {
      loading: false,
      hasQueried: false,
      selectedTeams: [],
      selectedProject: '',
      teamList: [],
      projectList: [],
      leaseList: [], //租赁费用列表
      leaseCost: 0,
      repairList: [], //维修费用列表
      repairCost: 0,
      scrapList: [], //报废费用列表
      scrapCost: 0,
      loseList: [], //丢失费用列表
      loseCost: 0,
      reducList: [], //减免费用列表
      reducCost: 0,
      costAll: 0,
      applyList: [],
      projectName: '', //结算工程
      unitName: '', //结算班组
      actualTimeAndName: '', //实际时间和对应的班组名称
      rowData: [],
      queryParams: {
        impUnitName: '', // 分公司
        departName: '', // 项目部
      },
      impUnitOptions: [], // 分公司下拉选项
      departOptions: [], // 项目部下拉选项
    }
  },
  computed: {
    hasData() {
      return this.leaseList.length > 0 || this.repairList.length > 0 ||
             this.scrapList.length > 0 || this.loseList.length > 0 || this.reducList.length > 0
    }
  },
  async created() {
    // await this.loadProjectList()
    this.getImpUnitOptions()
    this.handleImpUnitChange()
    this.handleDepartChange()
  },
  methods: {
    /** 获取分公司下拉 */
    async getImpUnitOptions() {
      try {
        const res = await getImpUnitListApi() // 调后台接口
        this.impUnitOptions = res.data.map(item => ({
          label: item.impUnitName,   // 这里根据实际字段替换
          value: item.impUnitName
        }))
      } catch (e) {
        console.error('获取分公司下拉失败:', e)
      }
    },
    /** 分公司选择变化，加载项目部 */
    async handleImpUnitChange() {
      this.queryParams.departName = null // 清空项目部已选
      this.departOptions = []            // 清空原有下拉

      try {
        const params = {
          impUnitName: this.queryParams.impUnitName, // 分公司名称
        }
        const res = await getDepartListByImpUnitApi(params)
        this.departOptions = res.data.map(item => ({
          label: item.departName,   // 项目部名称字段
          value: item.departName
        }))
      } catch (e) {
        console.error('获取项目部下拉失败:', e)
      }
    },
    /** 项目部选择变化，加载工程 */
    async handleDepartChange() {
      this.selectedProject = null // 清空工程已选
      this.projectList = []            // 清空原有下拉

      try {
        // 同时传入分公司和项目部参数
        const params = {
          impUnitName: this.queryParams.impUnitName, // 分公司名称
          departName: this.queryParams.departName, // 项目部名称
        }
        const res = await getClzProjectListApi(params)
        this.projectList = res.data.map(item => ({
          label: item.proName,   // 工程名称字段
          value: item.proId
        }))
      } catch (e) {
        console.error('获取工程下拉失败:', e)
      }
    },
    async loadProjectList() {
      try {
        const params = {
          impUnitName: this.queryParams.impUnitName, // 分公司名称
          departName: this.queryParams.departName, // 项目部名称
        }
        const res = await getClzProjectListApi(params)
        if (res.code === 200) {
          // this.projectList = response.data || []
          this.projectList = res.data.map(item => ({
          label: item.proName,   // 工程名称字段
          value: item.proId,
          projectId: item.projectId
        }))
        }
      } catch (error) {
        console.error('获取工程列表失败:', error)
        this.$message.error('获取工程列表失败')
      }
    },

    async loadTeamList() {
      try {
        this.selectedTeams = [] // 清空已选择的班组
        const params = {
          proId: this.selectedProject,
        }
        const res = await getClzTeamListApi(params)
        if (res.code === 200) {
          // this.teamList = response.data || []
          this.teamList = res.data.map(item => ({
          label: item.unitName,   // 工程名称字段
          value: item.unitId
        }))
        }
      } catch (error) {
        console.error('获取班组列表失败:', error)
        this.$message.error('获取班组列表失败')
      }
    },

    async handleQuery() {
      if (this.selectedTeams.length === 0) {
        this.$message.warning('请选择结算班组')
        return
      }
      if (!this.selectedProject) {
        this.$message.warning('请选择结算工程')
        return
      }

      this.loading = true
      this.hasQueried = true

        try {
          // 构造查询参数，模拟原有的rowData结构
          this.rowData = {
            unitIds: this.selectedTeams,
            projectId: this.selectedProject
          }

          await this.getDataAll()
        } catch (error) {
        console.error('查询结算数据失败:', error)
        this.$message.error('查询结算数据失败')
      } finally {
        this.loading = false
      }
    },

    /** 查询列表 */
    async getDataAll() {
      try {
        const response = await getClzSltInfo(this.rowData)
        console.log('接口返回数据:', response)

        // 处理返回的数据结构，合并所有班组的数据
        const dataArray = Array.isArray(response.data) ? response.data : [response.data]
        console.log('数据数组:', dataArray)

        // 初始化合并后的数据
        this.leaseList = []
        this.repairList = []
        this.scrapList = []
        this.loseList = []
        this.reducList = []

        // 收集项目名称和班组名称
        const projectNames = []
        const unitNames = []
        const actualTimeAndNames = [] // 用于存储实际时间和对应的班组名称

        let totalRepairCost = 0
        let totalScrapCost = 0

        // 遍历所有班组数据进行合并
        dataArray.forEach((data, index) => {
          console.log(`处理第${index + 1}个班组数据:`, data)

          // 获取当前班组的单位名称
          const currentUnitName = data.unitName || ''

          // 合并各项费用列表，并为每个明细项设置正确的单位名称
          if (data.leaseList && data.leaseList.length > 0) {
            const leaseListWithUnit = data.leaseList.map(item => ({
              ...item,
              unitName: item.unitName || currentUnitName
            }))
            this.leaseList = [...this.leaseList, ...leaseListWithUnit]
          }
          if (data.repairList && data.repairList.length > 0) {
            const repairListWithUnit = data.repairList.map(item => ({
              ...item,
              unitName: item.unitName || currentUnitName
            }))
            this.repairList = [...this.repairList, ...repairListWithUnit]
          }
          if (data.scrapList && data.scrapList.length > 0) {
            const scrapListWithUnit = data.scrapList.map(item => ({
              ...item,
              unitName: item.unitName || currentUnitName
            }))
            this.scrapList = [...this.scrapList, ...scrapListWithUnit]
          }
          if (data.loseList && data.loseList.length > 0) {
            const loseListWithUnit = data.loseList.map(item => ({
              ...item,
              unitName: item.unitName || currentUnitName
            }))
            this.loseList = [...this.loseList, ...loseListWithUnit]
          }
          if (data.reductionList && data.reductionList.length > 0) {
            const reducListWithUnit = data.reductionList.map(item => ({
              ...item,
              unitName: item.unitName || currentUnitName
            }))
            this.reducList = [...this.reducList, ...reducListWithUnit]
          }

          // 收集项目和班组名称
          if (data.projectName && !projectNames.includes(data.projectName)) {
            projectNames.push(data.projectName)
          }
          if (data.unitName && !unitNames.includes(data.unitName)) {
            unitNames.push(data.unitName)
          }
          if(data.unitName && data.actualExitTime){
              const timeAndName = `${data.unitName} ( ${data.actualExitTime} )`;
              // 检查是否已存在该元素，不存在才添加
              if(!actualTimeAndNames.includes(timeAndName)) {
                actualTimeAndNames.push(timeAndName);
              }
          }else if(data.unitName && !data.actualExitTime){
              const timeAndName = `${data.unitName} ( 暂无 )`;
              // 检查是否已存在该元素，不存在才添加
              if(!actualTimeAndNames.includes(timeAndName)) {
                actualTimeAndNames.push(timeAndName);
              }
          }

          // 累计维修和报废费用
          if (data.repairCost) {
            totalRepairCost += Number(data.repairCost)
          }
          if (data.scrapCost) {
            totalScrapCost += Number(data.scrapCost)
          }
        })

        console.log('合并后的租赁列表:', this.leaseList)
        console.log('合并后的维修列表:', this.repairList)
        console.log('合并后的报废列表:', this.scrapList)
        console.log('合并后的丢失列表:', this.loseList)
        console.log('合并后的减免列表:', this.reducList)

        // 设置项目和班组名称（多个用逗号分隔）
        this.projectName = projectNames.join(', ')
        this.unitName = unitNames.join(', ')
        this.actualTimeAndName = actualTimeAndNames.join(', ')
        console.log('项目名称:', this.projectName)
        console.log('班组名称:', this.unitName)

        // 计算各项费用
        this.leaseCost = this.countCost(this.leaseList)
        this.repairCost = totalRepairCost.toFixed(2)
        this.scrapCost = totalScrapCost.toFixed(2)
        this.loseCost = this.countCost(this.loseList)

        // 计算减免费用
        this.reducCost = 0
        if (this.reducList.length > 0) {
          this.reducList.forEach(item => {
            this.reducCost = Number(this.reducCost) + Number(item.leaseMoney || 0)
          })
        }

        console.log('租赁费用:', this.leaseCost)
        console.log('维修费用:', this.repairCost)
        console.log('报废费用:', this.scrapCost)
        console.log('丢失费用:', this.loseCost)
        console.log('减免费用:', this.reducCost)

        // 计算总费用
        let costSum =
          Number(this.leaseCost) +
          Number(this.repairCost) +
          Number(this.scrapCost) +
          Number(this.loseCost) -
          Number(this.reducCost)
        this.costAll = costSum

        console.log('各项数据长度:', {
          leaseList: this.leaseList.length,
          repairList: this.repairList.length,
          scrapList: this.scrapList.length,
          loseList: this.loseList.length,
          reducList: this.reducList.length
        })
        console.log('hasData结果:', this.hasData)
        console.log('总费用:', this.costAll)
      } catch (error) {
        console.error('获取结算数据失败:', error)
        this.$message.error('获取结算数据失败')
      }
    },

    //计算金额
    countCost(list) {
      let arrCost = 0
      list.forEach(item => {
        // 对于租赁和丢失费用，直接累加costs字段
        // partType和scrapType为null的情况也需要计算
        if (item.costs && item.costs > 0) {
          arrCost = arrCost + Number(item.costs)
        }
      })
      return arrCost.toFixed(2)
    },

    //提交按钮
    handleAdd() {
      this.$modal
        .confirm('超期未归还将变成丢失费用，是否确认提交？')
        .then(() => {
          // 从费用明细数据中提取协议ID
          const agreementIds = this.getAgreementIds()

          let params = {
            agreementIds: agreementIds,
            totalCostAll: this.costAll,
            leaseList: this.leaseList,
            repairList: this.repairList,
            scrapList: this.scrapList,
            loseList: this.loseList,
            reductionList: this.reducList
          }
          console.log('提交参数:', params)
          console.log('协议ID列表:', agreementIds)
          submitClzCosts(params).then(response => {
            this.$message({
              type: 'success',
              message: '提交成功'
            })
            this.reset()
          })
        })
        .catch(() => {})
    },

    // 提取协议ID
    getAgreementIds() {
      const agreementIds = new Set()

      // 从租赁费用明细中提取协议ID
      this.leaseList.forEach(item => {
        if (item.agreementId) {
          agreementIds.add(item.agreementId)
        }
      })

      // 从维修费用明细中提取协议ID
      this.repairList.forEach(item => {
        if (item.agreementId) {
          agreementIds.add(item.agreementId)
        }
      })

      // 从报废费用明细中提取协议ID
      this.scrapList.forEach(item => {
        if (item.agreementId) {
          agreementIds.add(item.agreementId)
        }
      })

      // 从丢失费用明细中提取协议ID
      this.loseList.forEach(item => {
        if (item.agreementId) {
          agreementIds.add(item.agreementId)
        }
      })

      // 从减免费用明细中提取协议ID
      this.reducList.forEach(item => {
        if (item.agreementId) {
          agreementIds.add(item.agreementId)
        }
      })

      // 转换为数组并返回
      return Array.from(agreementIds)
    },

    reset() {
      this.selectedTeams = []
      this.selectedProject = ''
      this.actualTimeAndName = ''
      this.queryParams.impUnitName = '' // 清空分公司
      this.queryParams.departName = '' // 清空项目部
      this.teamList = []
      this.handleImpUnitChange()
      this.handleDepartChange()
      this.hasQueried = false
      this.clearData()
    },

    clearData() {
      this.leaseList = []
      this.leaseCost = 0
      this.repairList = []
      this.repairCost = 0
      this.scrapList = []
      this.scrapCost = 0
      this.loseList = []
      this.loseCost = 0
      this.reducList = []
      this.reducCost = 0
      this.costAll = 0
      this.projectName = ''
      this.unitName = ''
      this.rowData = []
    },

    goBack() {
      this.$router.go(-1)
    },

    // 导出功能
    handleExport1() {
      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())
      let data = _.cloneDeep(this.rowData)
      const params = { params: JSON.stringify(data) }
      this.download('material/material_sltAgreementInfo/exportLease', { ...params }, `租赁费用明细_${currentTime}.xlsx`)
    },

    handleExport2() {
      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())
      let data = _.cloneDeep(this.rowData)
      const params = { params: JSON.stringify(data) }
      this.download('material/material_sltAgreementInfo/exportLose', { ...params }, `丢失费用明细_${currentTime}.xlsx`)
    },

    handleExport3() {
      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())
      let data = _.cloneDeep(this.rowData)
      const params = { params: JSON.stringify(data) }
      this.download('material/material_sltAgreementInfo/exportRepair', { ...params }, `维修费用明细_${currentTime}.xlsx`)
    },

    handleExport4() {
      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())
      let data = _.cloneDeep(this.rowData)
      const params = { params: JSON.stringify(data) }
      this.download('material/material_sltAgreementInfo/exportScrap', { ...params }, `报废费用明细_${currentTime}.xlsx`)
    },

    handleExport5() {
      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())
      let data = _.cloneDeep(this.rowData)
      const params = { params: JSON.stringify(data) }
      this.download('material/material_sltAgreementInfo/exportReduction', { ...params }, `减免费用明细_${currentTime}.xlsx`)
    },

    handleExportAll() {
      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())
      let data = _.cloneDeep(this.rowData)
      const params = { params: JSON.stringify(data) }
      this.download('material/material_sltAgreementInfo/exportAll', { ...params }, `全部费用明细_${currentTime}.xlsx`)
    },

    handleExportEach() {
      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())
      let data = _.cloneDeep(this.rowData)
      const params = { params: JSON.stringify(data) }
      this.download('material/material_sltAgreementInfo/exportEach', { ...params }, `各费用明细_${currentTime}.xlsx`)
    },

    // 监听器已不需要，工程列表独立加载
  },

  mounted() {
    // 不再需要监听器
  }
}
</script>

<style lang="scss" scoped>
.operation-bar {
  //background: #f5f7fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

::v-deep .el-table .fixed-width .el-button--mini {
  width: 80px !important;
  margin-bottom: 10px;
}

.tabelAllTop {
  display: flex;
  border: 1px solid #dfe6ec;
  width: 100%;
  height: 50px;
  background-color: #f8f8f9;
  border-left: none;
  border-bottom: none;

  .costTop {
    display: flex;
    padding: 5px;
    border-left: 1px solid #dfe6ec;
    align-items: center;
    text-align: center;
    justify-content: center; /* 将内容对齐到中间 */
    width: 100%;
    font-weight: bold; /* 添加字体加粗样式 */
  }
}

.tabelAllTopUnit {
  display: flex;
  border: 1px solid #dfe6ec;
  width: 100%;
  height: 50px;
  background-color: #f8f8f9;
  border-bottom: none;

  .costTopUnit {
    display: flex;
    padding: 5px;
    width: 21.4%;
    border-left: none;
    align-items: center;
    text-align: center;
    justify-content: center; /* 将内容对齐到中间 */
  }

  .costRightUnit {
    display: flex;
    padding: 5px;
    border-left: 1px solid #dfe6ec;
    text-align: center;
    align-items: center;
    width: 100%;
    justify-content: center; /* 将内容对齐到中间 */
    // padding-left: 20px; /* 添加左内边距 */
  }
}

.tabelAll {
  display: flex;
  border: 1px solid #ecedf3;
  width: 100%;
  border-bottom: 1px solid #dfe6ec;
  border-top: none;
  margin-bottom: 15px;
}

.tabelAllBottom {
  display: flex;
  border: 1px solid #dfe6ec;
  width: 100%;
  border-bottom: 1px solid #dfe6ec;
  border-top: none;
}

.columnAll {
  display: flex;
  padding: 5px;
  border-left: 1px solid #dfe6ec;
  text-align: center;
  align-items: center;
  width: 100%;
  justify-content: flex-end; /* 将内容对齐到右侧 */
  margin-right: 60px; /* 添加右边距 */
}

.columnAllNum {
  padding: 5px;
  text-align: center;
  width: 21.4%;
  border-left: none;
}

/* 最后一列无右边框 */
.tabelAll .column:last-child {
  border-right: none;
}
</style>
