<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" v-show="showSearch" :inline="true" label-width="80px">
          <el-form-item label="分公司" prop="impUnitName">
            <el-select
              v-model="queryParams.impUnitName"
              placeholder="请选择分公司"
              clearable
              filterable
              style="width: 215px"
            >
              <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="unitId">
            <TreeSelect
              v-model="queryParams.unitId"
              :options="unitList"
              :normalizer="normalizer"
              :show-count="true"
              style="width: 215px"
              :disable-branch-nodes="true"
              noChildrenText="没有数据了"
              noOptionsText="没有数据"
              noResultsText="没有搜索结果"
              placeholder="请选择单位"
              @select="unitChange"
            />
          </el-form-item>

          <el-form-item label="选择工程" prop="projectId">
            <TreeSelect
              v-model="queryParams.projectId"
              :options="proList"
              :normalizer="normalizer"
              :show-count="true"
              style="width: 215px"
              :disable-branch-nodes="true"
              noChildrenText="没有数据了"
              noOptionsText="没有数据"
              noResultsText="没有搜索结果"
              placeholder="请选择工程"
              @select="proChange"
            />
          </el-form-item>

            <el-form-item label="协议号" prop="agreementCode">
                <el-input v-model="queryParams.agreementCode" placeholder="协议号" clearable/>
            </el-form-item>

            <el-form-item label="推送月份" prop="month">
                <el-date-picker
                  v-model="queryParams.month"
                  type="month"
                  placeholder="请选择月份"
                  value-format="yyyy-MM"
                  :clearable="false"
                  @input="handleMonthInput">
                </el-date-picker>
            </el-form-item>

<!--            <el-form-item label="是否过滤" prop="isFilter">-->
<!--                <el-select v-model="queryParams.isFilter" placeholder="请选择" clearable>-->
<!--                    <el-option label="已过滤" value="0"></el-option>-->
<!--                    <el-option label="未过滤" value="1"></el-option>-->
<!--                </el-select>-->
<!--            </el-form-item>-->
            <el-form-item label="是否结算" prop="isSettlement">
                <el-select v-model="queryParams.isSettlement" placeholder="请选择" clearable>
                    <el-option label="已结算" value="1"></el-option>
                    <el-option label="未结算" value="0"></el-option>
                </el-select>
            </el-form-item>

          <!-- <el-form-item label="费用归属" prop="settlementType">
            <el-select v-model="queryParams.settlementType" placeholder="请选择" clearable>
              <el-option label="工器具" value="1"></el-option>
              <el-option label="安全用品" value="2"></el-option>
            </el-select>
          </el-form-item> -->

            <el-form-item label="推送状态" prop="pushStatus">
                <el-select v-model="queryParams.pushStatus" placeholder="请选择" clearable>
                    <el-option label="未提交" value="0"></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="warning"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
                >导出</el-button
        >
        <el-button
                type="success"
                plain
                size="mini"
                @click="handleSubmit"
                >提交</el-button
        >
      </el-form-item>
    </el-form>
    <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>

    <el-table
      v-loading="loading"
      :data="pushReviewList"
      ref="multipleTable"
      row-key="id"
      @selection-change="handleSelectionChange"
      :span-method="objectSpanMethod"
      border
      :max-height="650"
    >
    <el-table-column type="selection" align="center"  :selectable="selectable"/>
      <el-table-column label="序号" align="center" type="index">
        <template scope="scope">
                    <span style="background-color: #f8f8f9;text-align: center;" v-if="scope.$index==pushReviewList.length-1">合计费用：</span>
                    <span v-else>{{ scope.$index+1 }} </span>
        </template>
      </el-table-column>
      <el-table-column label="协议号" align="center" prop="agreementCode"  show-overflow-tooltip width="120px"/>
      <el-table-column label="分公司" align="center" prop="impUnitName" width="150px":show-overflow-tooltip="true"/>
      <el-table-column label="单位名称" align="center" prop="unitName" width="180" />
      <el-table-column label="工程名称" align="center" prop="projectName" width="180" />
      <el-table-column label="推送月份" align="center" prop="month" width="100" >
        <template slot-scope="scope" >
          <span>
            {{originalMonthTrue}}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="费用所属" align="center" prop="settlementType" width="100" >
        <template slot-scope="scope" >
          <el-tag v-if="scope.row.settlementType == 1" type="primary" size="small">工器具</el-tag>
          <el-tag v-if="scope.row.settlementType == 2" type="warning" size="small">安全用品</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="租赁费用" align="center" prop="leaseMoney" width="140px">
        <template slot-scope="scope" >
          <span class="clickText" v-if="scope.row.leaseMoney!=null && scope.$index!=pushReviewList.length-1"  @click="openLease(scope.row)">
            {{scope.row.leaseMoney}}
          </span>
          <span  v-if="scope.row.leaseMoney!=null && scope.$index==pushReviewList.length-1"  >
            {{Number(scope.row.leaseMoney).toFixed(3)}}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="维修费用" align="center" prop="repairMoney"  show-overflow-tooltip width="120px">
        <template slot-scope="scope" >
          <span class="clickText" v-if="scope.row.repairMoney!=null && scope.$index!=pushReviewList.length-1" @click="openRepair(scope.row)">
            {{scope.row.repairMoney}}
          </span>
          <span v-if="scope.row.repairMoney!=null && scope.$index==pushReviewList.length-1"  >
            {{Number(scope.row.repairMoney).toFixed(3)}}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="报废费用" align="center" prop="scrapMoney"  show-overflow-tooltip width="120px">
        <template slot-scope="scope" >
          <span class="clickText" v-if="scope.row.scrapMoney!=null && scope.$index!=pushReviewList.length-1"  @click="openScrap(scope.row)">
            {{scope.row.scrapMoney}}
          </span>
          <span v-if="scope.row.scrapMoney!=null && scope.$index==pushReviewList.length-1"  >
            {{Number(scope.row.scrapMoney).toFixed(3)}}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="丢失费用" align="center" prop="lostMoney"  show-overflow-tooltip width="120px">
        <template slot-scope="scope" >
          <span class="clickText" v-if="scope.row.lostMoney!=null && scope.$index!=pushReviewList.length-1"  @click="openLose(scope.row)">
            {{scope.row.lostMoney}}
          </span>
          <span v-if="scope.row.lostMoney!=null && scope.$index==pushReviewList.length-1"  >
            {{Number(scope.row.lostMoney).toFixed(3)}}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="合计费用" align="center" prop="money"  show-overflow-tooltip width="120px">
        <template slot-scope="scope" >
          <span  v-if="scope.row.money!=null && scope.$index==pushReviewList.length-1"  >
            {{Number(scope.row.money).toFixed(3)}}
          </span>
          <span  v-if="scope.row.money!=null && scope.$index!=pushReviewList.length-1"  >
            {{scope.row.money}}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="是否结算" align="center" prop="isSettlement" width="100" >
        <template slot-scope="scope" >
          <span v-if="scope.row.isSettlement==1 || scope.row.isSettlement==2" style="color: #67c23a">已结算</span>
          <span v-if="scope.row.isSettlement==0" style="color: #f56c6c">未结算</span>
        </template>
      </el-table-column>
      <el-table-column label="是否推送" align="center" prop="pushStatus" width="100" >
        <template slot-scope="scope" >
          <span v-if="scope.row.pushStatus == 0" style="color: #f56c6c">未推送</span>
          <span v-else-if="scope.row.pushStatus == 1" style="color: #67c23a">已推送</span>
          <span v-else-if="scope.row.pushStatus == 2" style="color: #f56c6c">已退回</span>
        </template>
      </el-table-column>
      <el-table-column label="推送备注" align="center" prop="pushRemark" width="180" />
    </el-table>
    <!-- <div class="tabelFirstBottom">
                <div class="columnFirstNum">合计费用</div>
                <div style="display: flex;width:58%">
                <div class="columnFirst">{{ leaseAll.toFixed(2) }}</div>
                <div class="columnFirst">{{ repairAll.toFixed(2) }}</div>
                <div class="columnFirst">{{ scrapAll.toFixed(2) }}</div>
                <div class="columnFirst">{{ lostAll.toFixed(2) }}</div>
                <div class="columnFirst">{{ moneyAll.toFixed(2) }}</div>
                <div class="columnFirstRight"></div>
              </div>
    </div> -->

      <!-- 租赁费用弹窗-->
      <el-dialog :title="title" :visible.sync="showLease" width="1300px"  append-to-body>
        <el-form :model="dialogLease" ref="dialogLease" size="small" :inline="true" label-width="80px">
          <el-form-item label="物资名称" prop="typeName">
          <el-input
            v-model="dialogLease.typeName"
            placeholder="请输入物资名称"
            clearable :maxlength="30"
            style="width: 240px"/>
          </el-form-item>
          <el-form-item label="规格型号" prop="modelName">
          <el-input
            v-model="dialogLease.modelName"
            placeholder="请输入规格型号"
            clearable :maxlength="30"
            style="width: 240px"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary"
              icon="el-icon-search" size="mini"
              @click="handleQueryLease"
            >查询</el-button>
          </el-form-item>
          <el-form-item>
             <el-button
               type="warning"
               icon="el-icon-download"
               size="mini"
               @click="handleExportLease"
             >导出</el-button>
           </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="dialogLeaseList" height="500px" border>
          <el-table-column label="序号" align="center" width="80" type="index" />
          <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="unitName" :show-overflow-tooltip="true"/>
          <el-table-column label="租赁单价" align="center" prop="leasePrice" :show-overflow-tooltip="true"/>
          <el-table-column label="租赁数量" align="center" prop="leaseNum" :show-overflow-tooltip="true"/>
          <el-table-column label="计算开始时间" align="center" prop="leaseDate"  width="120px">
            <template slot-scope="scope">
                {{ formatDate(scope.row.leaseDate) }}
            </template>
          </el-table-column>
          <el-table-column label="计算结束时间" align="center" prop="backDate"  width="120px">
              <template slot-scope="scope">
                {{ formatDate(scope.row.backDate) }}
            </template>
          </el-table-column>
          <el-table-column label="租赁天数" align="center" prop="leaseDays" :show-overflow-tooltip="true"/>
          <el-table-column label="租赁费用" align="center" width="126px" prop="leaseMoney" :show-overflow-tooltip="true">
            <template slot-scope="scope">
                {{ scope.row.leaseMoney.toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
        <div class="tabelAllBottom">
                <div class="columnAllNum">合计费用</div>
                <div class="columnAll">
                {{ leaseAllMoney.toFixed(2) }}
                </div>
        </div>
      </el-dialog>

      <!-- 维修费用弹窗-->
      <el-dialog :title="title" :visible.sync="showRepair" width="1200px"  append-to-body>
        <el-form :model="dialogRepair" ref="dialogRepair" size="small" :inline="true" label-width="80px">
          <el-form-item label="物资名称" prop="typeName">
          <el-input
            v-model="dialogRepair.typeName"
            placeholder="请输入物资名称"
            clearable :maxlength="30"
            style="width: 240px"/>
          </el-form-item>
          <el-form-item label="规格型号" prop="modelName">
          <el-input
            v-model="dialogRepair.modelName"
            placeholder="请输入规格型号"
            clearable :maxlength="30"
            style="width: 240px"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary"
              icon="el-icon-search" size="mini"
              @click="handleQueryRepair"
            >查询</el-button>
          </el-form-item>
          <el-form-item>
             <el-button
               type="warning"
               icon="el-icon-download"
               size="mini"
               @click="handleExportRepair"
             >导出</el-button>
           </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="dialogRepairList" border>
          <el-table-column label="序号" align="center" width="80" type="index" />
          <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" width="130px" prop="costs" :show-overflow-tooltip="true">
            <template slot-scope="scope">
                {{ scope.row.costs.toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
        <div class="tabelAllBottom">
                <div class="columnAllNum">合计费用</div>
                <div class="columnAll">
                {{ repairAllMoney.toFixed(2) }}
                </div>
        </div>
      </el-dialog>

      <!-- 报废费用弹窗-->
      <el-dialog :title="title" :visible.sync="showScrap" width="1200px"  append-to-body>
        <el-form :model="dialogScrap" ref="dialogScrap" size="small" :inline="true" label-width="80px">
          <el-form-item label="物资名称" prop="typeName">
          <el-input
            v-model="dialogScrap.typeName"
            placeholder="请输入物资名称"
            clearable :maxlength="30"
            style="width: 240px"/>
          </el-form-item>
          <el-form-item label="规格型号" prop="modelName">
          <el-input
            v-model="dialogScrap.modelName"
            placeholder="请输入规格型号"
            clearable :maxlength="30"
            style="width: 240px"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary"
              icon="el-icon-search" size="mini"
              @click="handleQueryScrap"
            >查询</el-button>
          </el-form-item>
          <el-form-item>
             <el-button
               type="warning"
               icon="el-icon-download"
               size="mini"
               @click="handleExportScrap"
             >导出</el-button>
           </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="dialogScrapList" border>
          <el-table-column label="序号" align="center" width="80" type="index" />
          <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" width="130px" prop="costs" :show-overflow-tooltip="true">
            <template slot-scope="scope">
                {{ scope.row.costs.toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
        <div class="tabelAllBottom">
                <div class="columnAllNum">合计费用</div>
                <div class="columnAll">
                {{ scrapAllMoney.toFixed(2)}}
                </div>
        </div>
      </el-dialog>

      <!-- 丢失费用弹窗-->
      <el-dialog :title="title" :visible.sync="showLose" width="1200px"  append-to-body>
        <el-form :model="dialogLose" ref="dialogLose" size="small" :inline="true" label-width="80px">
          <el-form-item label="物资名称" prop="typeName">
          <el-input
            v-model="dialogLose.typeName"
            placeholder="请输入物资名称"
            clearable :maxlength="30"
            style="width: 240px"/>
          </el-form-item>
          <el-form-item label="规格型号" prop="modelName">
          <el-input
            v-model="dialogLose.modelName"
            placeholder="请输入规格型号"
            clearable :maxlength="30"
            style="width: 240px"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary"
              icon="el-icon-search" size="mini"
              @click="handleQueryLose"
            >查询</el-button>
          </el-form-item>
          <el-form-item>
             <el-button
               type="warning"
               icon="el-icon-download"
               size="mini"
               @click="handleExportLose"
             >导出</el-button>
           </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="dialogLoseList" border>
          <el-table-column label="序号" align="center" width="80" type="index" />
          <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" width="130px" prop="costs" :show-overflow-tooltip="true">
            <template slot-scope="scope">
                {{ scope.row.costs.toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
        <div class="tabelAllBottom">
                <div class="columnAllNum">合计费用</div>
                <div class="columnAll">
                {{ loseAllMoney.toFixed(2)}}
                </div>
        </div>
      </el-dialog>
  </div>
</template>

  <script>
import {
    getProjectList,
    getUnitList,
    getAgreementInfoById,
} from '@/api/back/index.js'
import {getPushReviewList,getLeaseListApi,getRepairList,getLoseList,getScrapList,submitPushCosts } from "@/api/costPush/costPush";
import { getImpUnitListApi } from "@/api/materialsStation"
import TreeSelect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import ExcelJS from 'exceljs';
export default {
    name: "PushReview",
  data() {
    return {
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,

      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,

      // 总条数
      total: 0,
      // 费用推送审核表格数据
      pushReviewList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 单位数据
      unitList: [],
      // 工程数据
      proList: [],

      //合计
      moneyAll: 0,
      //租赁合计
      leaseAll: 0,
      //维修合计
      repairAll: 0,
      //报废合计
      scrapAll: 0,
      //丢失合计
      lostAll: 0,

      // 查询参数
      queryParams: {
        unitId: null,
        projectId: null,
        agreementId: '',
        agreementCode: '',
        month: null,
        pushStatus: null,
        isSettlement: null,
        settlementType: 1,
        isFilter: null,
        impUnitName:null,
      },

      // 多选框选中数据
      ids: [],

      taskId:[],

      //租赁费用弹窗
      showLease: false,
      dialogLeaseList: [], //租赁费用列表
      dialogLease: {
        typeName: undefined,
        modelName: undefined,
      },
      dialogLeaseTotal: 0,
      leaseAllMoney: 0,
      currentLeaseRow: null, // 当前租赁费用行数据

      //维修费用弹窗
      showRepair: false,
      dialogRepairList: [], //维修费用列表
      dialogRepair: {
        typeName: undefined,
        modelName: undefined,
      },
      dialogRepairTotal: 0,
      repairAllMoney: 0,
      currentRepairRow: null, // 当前维修费用行数据

      //报废费用弹窗
      showScrap: false,
      dialogScrapList: [], //报废费用列表
      dialogScrap: {
        typeName: undefined,
        modelName: undefined
      },
      dialogScrapTotal: 0,
      scrapAllMoney: 0,
      currentScrapRow: null, // 当前报废费用行数据

      //丢失费用弹窗
      showLose: false,
      dialogLoseList: [], //丢失费用列表
      dialogLose: {
        typeName: undefined,
        modelName: undefined,
      },
      dialogLoseTotal: 0,
      loseAllMoney: 0,
      currentLoseRow: null, // 当前丢失费用行数据

      originalMonth: null, // 用于存储原始的月份值，防止键盘按键删除
      originalMonthTrue: null,
      impUnitOptions: [], // 分公司下拉选项
    };
  },
  created() {
    this.getMonth();
    this.getImpUnitOptions() //获取分公司下拉
    this.GetUnitData()
    this.GetProData()
    this.getList();
  },
  components: { TreeSelect },
    methods: {
    /** 获取分公司下拉 */
      async getImpUnitOptions() {
        try {
          const res = await getImpUnitListApi()
          this.impUnitOptions = res.data.map(item => ({
            label: item.impUnitName,
            value: item.impUnitName
          }))
          if (this.impUnitOptions.length === 1) {
            this.queryParams.impUnitName = this.impUnitOptions[0].value
            await this.onImpUnitChange(this.queryParams.impUnitName)
          }
        } catch (e) {
          console.error('获取分公司下拉失败:', e)
        }
      },


      getMonth() {
        // 默认当月
        var nowDate = new Date();
        var date = {
          year: nowDate.getFullYear(),
          month: nowDate.getMonth() + 1,
          day: nowDate.getDate()
        };
        const dayDate = date.year + "-" + (date.month >= 10 ? date.month : "0" + date.month);
        this.$set(this.queryParams, "month", dayDate.toString());
        this.originalMonth = dayDate.toString();
        this.originalMonthTrue = dayDate.toString();
      },

      formatDate(dateStr) {
          if (!dateStr) return '';
          // 处理日期格式，只保留年月日部分
          const date = new Date(dateStr);
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          return `${year}-${month}-${day}`;
        },

      //键盘按键删除触发返回效果
      handleMonthInput() {
      // 当用户输入时，检查是否为空
      if (!this.queryParams.month) {
          this.queryParams.month = this.originalMonth;
        }
      },

      // //多选框选中数据
      // handleSelectionChange(val) {
      //   this.ids = val.map(item => item.agreementId);
      // },

      /** 转换菜单数据结构 */
      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 getUnitList(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;
        // 重置合计变量，避免重复累加
        this.leaseAll = 0;
        this.repairAll = 0;
        this.scrapAll = 0;
        this.lostAll = 0;
        this.moneyAll = 0;

        console.log(this.queryParams.month)
        if(this.queryParams.isSettlement == 1){
          this.queryParams.isSettlement = true;
        }else if(this.queryParams.isSettlement == 0){
          this.queryParams.isSettlement = false;
        }
        getPushReviewList(this.queryParams).then((response) => {
          this.pushReviewList = response.rows;
          this.originalMonthTrue = this.queryParams.month;
          if(response.rows){
            response.rows.forEach(item => {
              this.leaseAll += (Number(item.leaseMoney) || 0);
              this.repairAll += (Number(item.repairMoney) || 0) ;
              this.scrapAll += (Number(item.scrapMoney) || 0);
              this.lostAll += (Number(item.lostMoney) || 0);
            })
            this.moneyAll = this.leaseAll + this.repairAll + this.scrapAll + this.lostAll;
          }
          let obj = {
            leaseMoney: this.leaseAll,
            repairMoney: this.repairAll,
            scrapMoney: this.scrapAll,
            lostMoney: this.lostAll,
            money: this.moneyAll,
          }
          this.pushReviewList.push(obj)
          this.loading = false;
        });
      },

      /** 重置按钮操作 */
      resetQuery() {
        // 重置合计变量
        this.leaseAll = 0;
        this.repairAll = 0;
        this.scrapAll = 0;
        this.lostAll = 0;
        this.moneyAll = 0;

        this.queryParams = {
          pageNum: 1,
          pageSize: 10,
          pushStatus: null,
          isPay: null,
          isFilter: null,
          unitId: null,
          projectId: null,
          agreementId: '',
          agreementCode: '',
          month: this.originalMonth,
          settlementType: 1,
        }
        this.resetForm('queryForm')
        this.handleQuery()
      },

      /** 搜索按钮操作 */
      handleQuery() {
        this.getList();
      },

      // 多选框选中数据
      handleSelectionChange(selection) {
        this.taskId = selection.map((item) => item.taskId).filter(id => id != null)
        this.ids = selection.map((item) => item.agreementId).filter(id => id != null)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },

      //是否可用勾选框
      selectable(row) {
        if (row.pushStatus == 1) {
          return false;
        } else {
          return true;
        }
      },

      //打开租赁费用弹窗
      openLease(row) {
        this.showLease = true
        this.dialogLease.typeName = ""
        this.dialogLease.modelName = ""
        this.dialogLease.id = row.id;
        this.currentLeaseRow = row; // 保存当前行数据
        this.getLeaseList(row)
      },
      //查询租赁费用
      getLeaseList(row) {
        this.loading = true;

        // 根据选择的月份计算开始日期和结束日期
        const selectedMonth = this.queryParams.month; // 格式: "2024-08"
        const startDate = selectedMonth + '-01'; // 月份第一天

        // 计算月份最后一天
        const year = parseInt(selectedMonth.split('-')[0]);
        const month = parseInt(selectedMonth.split('-')[1]);
        const endDate = new Date(year, month, 0).toISOString().split('T')[0]; // 当月最后一天

        let params = {
          month: this.queryParams.month,
          startDate: startDate,
          endDate: endDate,
          agreementId: row.agreementId,
          typeName: this.dialogLease.typeName,
          modelName: this.dialogLease.modelName,
          settlementType: 1,
        }
        getLeaseListApi(params).then((response) => {
          this.dialogLeaseList = response.rows;
          console.log("xxxxxxxxxxxxxx",this.dialogLeaseList)
          this.leaseAllMoney = 0;
          this.dialogLeaseList.forEach(item => {
            this.leaseAllMoney += Number(item.leaseMoney);
          })
          this.dialogLeaseTotal = response.total;
          this.loading = false;
        });
      },
      handleQueryLease() {
        this.getLeaseList(this.currentLeaseRow)
      },
      //导出租赁费用
      handleExportLease() {
      // this.download(
      //         'material/complex_query/exportOutRecord',
      //         {
      //             ...this.queryParams,
      //         },
      //         `租赁费用记录_${new Date().getTime()}.xlsx`,
      //     )
      },

      //打开维修费用弹窗
      openRepair(row) {
        this.showRepair = true
        this.dialogRepair.typeName = ""
        this.dialogRepair.modelName = ""
        this.dialogRepair.id = row.id;
        this.dialogRepair.agreementId = row.agreementId;
        this.currentRepairRow = row; // 保存当前行数据
        this.getRepairList()
      },
      //查询维修费用
      getRepairList() {
        this.loading = true;
        let params = {
          agreementId: this.dialogRepair.agreementId,
          settlementType: 1,
        }

        getRepairList(params).then((response) => {
          this.dialogRepairList = response.rows;
          this.repairAllMoney = 0;
          this.dialogRepairList.forEach(item => {
            if(item.partType == '收费'){
              this.repairAllMoney += Number(item.costs);
            }
          })
          this.dialogRepairTotal = response.total;
          this.loading = false;
        });
      },

      handleQueryRepair() {
        this.getRepairList()
      },
      //导出维修费用
      handleExportRepair() {
      // this.download(
      //         'material/complex_query/exportOutRecord',
      //         {
      //             ...this.queryParams,
      //         },
      //         `维修费用记录_${new Date().getTime()}.xlsx`,
      //     )
      },


      //打开报废费用弹窗
      openScrap(row) {
        this.showScrap = true
        this.dialogScrap.typeName = ""
        this.dialogScrap.modelName = ""
        this.dialogScrap.id = row.id;
        this.dialogScrap.agreementId = row.agreementId;
        this.currentScrapRow = row; // 保存当前行数据
        this.getScrapList()
      },
      //查询报废费用
      getScrapList() {
        this.loading = true;

        let params = {
          agreementId: this.dialogScrap.agreementId,
          settlementType: 1,
        }

        getScrapList(params).then((response) => {
          this.dialogScrapList = response.rows;
          this.scrapAllMoney = 0;
          this.dialogScrapList.forEach(item => {
            if(item.partType == '收费'){
              this.scrapAllMoney += Number(item.costs);
            }
          })
          this.dialogScrapTotal = response.total;
          this.loading = false;
        });
      },
      handleQueryScrap() {
        this.getScrapList()
      },
      //导出报废费用
      handleExportScrap() {
      // this.download(
      //         'material/complex_query/exportOutRecord',
      //         {
      //             ...this.queryParams,
      //         },
      //         `报废费用记录_${new Date().getTime()}.xlsx`,
      //     )
      },


      //打开丢失费用弹窗
      openLose(row) {
        this.showLose = true
        this.dialogLose.typeName = ""
        this.dialogLose.modelName = ""
        this.dialogLose.id = row.id;
        this.dialogLose.agreementId = row.agreementId;
        this.getLoseList()
      },
      //查询丢失费用
      getLoseList() {
        this.loading = true;

        let params = {
          agreementId: this.dialogLose.agreementId,
          settlementType: 1,
        }

        getLoseList(params).then((response) => {
          this.dialogLoseList = response.rows;
          this.loseAllMoney = 0;
          this.dialogLoseList.forEach(item => {
              this.loseAllMoney += Number(item.costs);
          })
          this.dialogLoseTotal = response.total;
          this.loading = false;
        });
      },
      handleQueryLose() {
        this.getLoseList()
      },
      handleExportLose() {
      // this.download(
      //         'material/complex_query/exportOutRecord',
      //         {
      //             ...this.queryParams,
      //         },
      //         `丢失费用记录_${new Date().getTime()}.xlsx`,
      //     )
      },
      /** 外层导出 */
      async handleExport() {
        if (!this.pushReviewList || this.pushReviewList.length === 0) {
          this.$modal.msgWarning('没有可导出的数据');
          return;
        }

        try {
          // 创建工作簿
          const workbook = new ExcelJS.Workbook();
          const worksheet = workbook.addWorksheet('费用推送审核记录');

          // 定义列配置
          const columns = [
            { header: '序号', key: 'index', width: 8 },
            { header: '协议号', key: 'agreementCode', width: 18 },
            { header: '单位名称', key: 'unitName', width: 20 },
            { header: '工程名称', key: 'projectName', width: 20 },
            { header: '推送月份', key: 'month', width: 12 },
            { header: '费用所属', key: 'settlementType', width: 12 },
            { header: '租赁费用（元）', key: 'leaseMoney', width: 18 },
            { header: '维修费用（元）', key: 'repairMoney', width: 18 },
            { header: '报废费用（元）', key: 'scrapMoney', width: 18 },
            { header: '丢失费用（元）', key: 'lostMoney', width: 18 },
            { header: '合计费用（元）', key: 'money', width: 18 },
            { header: '是否结算', key: 'isSettlement', width: 12 },
            { header: '推送状态', key: 'pushStatus', width: 12 },
            { header: '推送备注', key: 'pushRemark', width: 12 },
          ];

          worksheet.columns = columns;

          // 定义表头样式
          const headerStyle = {
            font: { bold: true, color: { argb: 'FFFFFFFF' }, size: 11 },
            fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF4472C4' } },
            alignment: { horizontal: 'center', vertical: 'center', wrapText: true },
            border: {
              top: { style: 'thin', color: { argb: 'FF000000' } },
              bottom: { style: 'thin', color: { argb: 'FF000000' } },
              left: { style: 'thin', color: { argb: 'FF000000' } },
              right: { style: 'thin', color: { argb: 'FF000000' } }
            }
          };

          // 定义数据行样式
          const dataStyle = {
            alignment: { horizontal: 'center', vertical: 'center' },
            border: {
              top: { style: 'thin', color: { argb: 'FF000000' } },
              bottom: { style: 'thin', color: { argb: 'FF000000' } },
              left: { style: 'thin', color: { argb: 'FF000000' } },
              right: { style: 'thin', color: { argb: 'FF000000' } }
            }
          };

          // 定义合计行样式
          const totalStyle = {
            font: { bold: true, size: 11 },
            fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFF8F8F9' } },
            alignment: { horizontal: 'center', vertical: 'center' },
            border: {
              top: { style: 'thin', color: { argb: 'FF000000' } },
              bottom: { style: 'thin', color: { argb: 'FF000000' } },
              left: { style: 'thin', color: { argb: 'FF000000' } },
              right: { style: 'thin', color: { argb: 'FF000000' } }
            }
          };

          // 设置表头样式
          worksheet.getRow(1).eachCell((cell) => {
            cell.style = headerStyle;
          });

          // 添加数据行（排除最后一行合计行）
          const dataRows = this.pushReviewList.slice(0, -1);
          dataRows.forEach((row, index) => {
            const dataRow = {
              index: String(index + 1),  // 转换为字符串，避免被格式化为小数
              agreementCode: row.agreementCode || '',
              unitName: row.unitName || '',
              projectName: row.projectName || '',
              month: this.originalMonthTrue || row.month || '',
              settlementType: row.settlementType === 1 ? '工器具' : (row.settlementType === 2 ? '安全用品' : ''),
              leaseMoney: row.leaseMoney ? parseFloat(row.leaseMoney) : 0,
              repairMoney: row.repairMoney ? parseFloat(row.repairMoney) : 0,
              scrapMoney: row.scrapMoney ? parseFloat(row.scrapMoney) : 0,
              lostMoney: row.lostMoney ? parseFloat(row.lostMoney) : 0,
              money: row.money ? parseFloat(row.money) : 0,
              isSettlement: row.isSettlement === 1 || row.isSettlement === 2 ? '已结算' : '未结算',
              pushStatus: row.pushStatus == 1 ? '已推送' :  row.pushStatus == 0 ? '未推送' : '已退回',
              pushRemark: row.pushRemark || '',
            };

            const newRow = worksheet.addRow(dataRow);

            // 设置数据行样式
            newRow.eachCell((cell) => {
              cell.style = dataStyle;
            });

            // 设置费用列的数字格式（2位小数）
            newRow.getCell(7).numFmt = '0.00';   // 租赁费用
            newRow.getCell(8).numFmt = '0.00';   // 维修费用
            newRow.getCell(9).numFmt = '0.00';   // 报废费用
            newRow.getCell(10).numFmt = '0.00';  // 丢失费用
            newRow.getCell(11).numFmt = '0.00';  // 合计费用
          });

          // 添加合计行
          const totalRow = this.pushReviewList[this.pushReviewList.length - 1];
          const totalDataRow = {
            index: '合计',
            agreementCode: '',
            unitName: '',
            projectName: '',
            month: '',
            settlementType: '',
            leaseMoney: totalRow.leaseMoney ? parseFloat(totalRow.leaseMoney) : 0,
            repairMoney: totalRow.repairMoney ? parseFloat(totalRow.repairMoney) : 0,
            scrapMoney: totalRow.scrapMoney ? parseFloat(totalRow.scrapMoney) : 0,
            lostMoney: totalRow.lostMoney ? parseFloat(totalRow.lostMoney) : 0,
            money: totalRow.money ? parseFloat(totalRow.money) : 0,
            isSettlement: '',
            pushStatus: '',
            pushRemark: ''
          };

          const newTotalRow = worksheet.addRow(totalDataRow);

          // 设置合计行样式
          newTotalRow.eachCell((cell) => {
            cell.style = totalStyle;
          });

          // 设置合计行费用列的数字格式
          newTotalRow.getCell(7).numFmt = '0.00';   // 租赁费用
          newTotalRow.getCell(8).numFmt = '0.00';   // 维修费用
          newTotalRow.getCell(9).numFmt = '0.00';   // 报废费用
          newTotalRow.getCell(10).numFmt = '0.00';  // 丢失费用
          newTotalRow.getCell(11).numFmt = '0.00';  // 合计费用

          // 生成文件名
          const fileName = `费用推送审核记录_${new Date().toISOString().slice(0, 10)}.xlsx`;

          // 生成Excel文件并下载
          const buffer = await workbook.xlsx.writeBuffer();
          const blob = new Blob([buffer], { 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);
          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失败，请稍后重试');
        }
      },

      /** 提交 */
      handleSubmit() {
        this.ids = this.ids.filter(id => id != null)
        console.log("xxxxxxxxxxxxxxx",this.ids)
        if (this.ids.length == 0) {
              this.$message({
                type: 'warning',
                message: '请选择数据',
              })
            return;
        }
        this.$modal
              .confirm('是否确认提交？')
          .then(() => {
                  let params = {
                    agreementIds: this.ids.filter(id => id != null),
                    taskId: this.taskId.filter(id => id!= null)[0]
                  }
                  console.log("xxxxxxxxxxxx",params)
                  submitPushCosts(params).then((response) => {
                      this.$message({
                          type: 'success',
                          message: '提交成功',
                      })
                      // 清空勾选框选择状态
                      if (this.$refs.multipleTable) {
                        this.$refs.multipleTable.clearSelection()
                      }
                      // 清空ids数组
                      this.ids = []
                      this.getList()
                  })
              })
              .catch(() => {})
     },

      // 合并单元格 rowIndex=行数  columnIndex=列数
      // 这里是合并table的除表头外的第一行的第二列 + 除表头外的第二行的第二列
      // 注意列数和行数从 0 开始
      objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
        if (rowIndex === this.pushReviewList.length-1 && columnIndex == 1) {
          let rowspan = 2
          let colspan = 7  // 增加了结算类型列，所以从6改为7
          return { rowspan, colspan }
        }
        // 解决偏移的重要代码
        // 重点在 else if 判断必须加因为合并单元格数据会出现偏移、
        // 否则如果是 第二行 的 第二列 那么隐藏原有第二行 的 第二列的数据使他隐藏
        else if (rowIndex === this.pushReviewList.length-1 && columnIndex < 7) {  // 从6改为7
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      },
  },
};
</script>
<style lang="scss" scoped>
.uploadImg {
  padding-top: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.deviceCode {
  margin-top: 10px;
  padding-bottom: 20px;
  font-size: 18px;
}
::v-deep.el-table .fixed-width .el-button--mini {
    width: 60px !important;
    margin-bottom: 10px;
}
.clickText {
  color: #02a7f0;
  cursor: pointer;
}

.tabelAllBottom {
  display: flex;
  border: 1px solid #dfe6ec;
  width:100%;
  border-bottom: 1px solid #dfe6ec;
  border-top: none;
}
.columnAll {
  flex: 1;
  display: flex;
  padding: 5px;
  border-left: 1px solid #dfe6ec;
  width:100%;
  align-items: center;
  text-align: center;
  justify-content: center; /* 将内容对齐到中间 */
}
.columnAllNum {
  padding: 5px;
  text-align: center;
  width:88.6%;
  border-left: none;
}

.tabelFirstBottom {
  display: flex;
  border: 1px solid #dfe6ec;
  width:100%;
  border-bottom: 1px solid #dfe6ec;
  border-top: none;
}
.columnFirst {
  display: flex ;
  background-color: #f8f8f9;
  padding: 5px;
  border-left: 1px solid #dfe6ec;
  width:14.5%;
  align-items: center;
  text-align: center;
  justify-content: center; /* 将内容对齐到中间 */
}
.columnFirstRight {
  padding: 5px;
  background-color: #f8f8f9;
  border-left: 1px solid #dfe6ec;
  width:28.5%;
  align-items: center;
  text-align: center;
  justify-content: center; /* 将内容对齐到中间 */
}
.columnFirstNum {
  background-color: #f8f8f9;
  padding: 5px;
  text-align: center;
  width:41.7%;
  border-left: none;
}
</style>
