<template>
  <div class="app-container">
    <el-tabs v-model="activeTab" type="border-card" @tab-change="handleTabChange">
      <el-tab-pane v-if="hasTabPermi('selfEng')" label="本单位工程隐患" name="selfEng">
        <div class="table-page-wrap">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="隐患名称" prop="hiddName">
            <el-input v-model="queryParams.hiddName" placeholder="请输入" clearable style="width: 200px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          </el-form-item>
          <el-form-item style="margin-left:auto;">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['hidd:objhidd:add']">新建</el-button>
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['hidd:objhidd:export']">导出</el-button>
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['hidd:objhidd:remove']">删除</el-button>
            <el-button type="success" plain icon="Upload" :disabled="ids.length === 0" @click="handleReport" v-hasPermi="['hidd:objhidd:report']">上报</el-button>
          </el-form-item>
        </el-form>

        <div class="table-wrapper">
        <el-table :height="tableHeight" v-loading="loading" :data="list" @selection-change="handleSelectionChange" border style="width:100%" :header-cell-style="{ 'text-align': 'center' }">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" type="index" width="60" />
          <el-table-column label="排查单位" align="center" prop="orgName" min-width="140" :show-overflow-tooltip="true" />
          <el-table-column label="隐患名称" align="center" prop="hiddName" min-width="160" :show-overflow-tooltip="true" />
          <el-table-column label="所属工程" align="center" prop="engName" min-width="140" :show-overflow-tooltip="true" />
          <el-table-column label="隐患级别" align="center" width="100">
            <template #default="scope">
              <dict-tag :options="hidd_grad" :value="scope.row.hiddGrad" />
            </template>
          </el-table-column>
          <el-table-column label="隐患类型" align="center" width="100">
            <template #default="scope">
              <dict-tag :options="hidd_clas" :value="scope.row.hiddClas" />
            </template>
          </el-table-column>
          <el-table-column label="隐患来源" align="center" width="100">
            <template #default="scope">
              <dict-tag :options="hidd_sour" :value="scope.row.hiddSour" />
            </template>
          </el-table-column>
          <el-table-column label="排查日期" align="center" width="100" prop="inspDate" />
          <el-table-column label="要求整改完成日期" align="center" width="120" prop="requCompDate" />
          <el-table-column label="督办状态" align="center" width="90">
            <template #default="scope">
              <dict-tag :options="sup_stat" :value="scope.row.supStat" />
            </template>
          </el-table-column>
          <el-table-column label="隐患状态" align="center" width="90">
            <template #default="scope">
              <dict-tag :options="hidd_stat" :value="scope.row.hiddStat" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="200" fixed="right">
            <template #default="scope">
              <el-button v-if="scope.row.hiddStat==='0' || scope.row.hiddStat==='1'" link type="primary" v-hasPermi="['hidd:objhidd:rectify']" @click="handleRectify(scope.row)">整改</el-button>
              <el-button v-if="scope.row.hiddStat==='2' && scope.row.supStat==='1' && scope.row.cancelState==='0'" link type="warning" v-hasPermi="['hidd:objhidd:writeoff']" @click="handleCancelApply(scope.row)">销号申请</el-button>
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['hidd:objhidd:edit']" />
              <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['hidd:objhidd:remove']" />
            </template>
          </el-table-column>
        </el-table>
        </div>

        <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
        </div>
      </el-tab-pane>

      <el-tab-pane v-if="hasTabPermi('subEng')" label="下级单位隐患" name="subEng">
        <div class="table-page-wrap">
        <el-form :model="queryParams2" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="隐患名称" prop="hiddName">
            <el-input v-model="queryParams2.hiddName" placeholder="请输入" clearable style="width: 200px" @keyup.enter="handleQuery2" />
          </el-form-item>
          <el-form-item label="选择单位" prop="orgName">
            <el-input v-model="queryParams2.orgName" placeholder="请输入" clearable style="width: 200px" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery2">搜索</el-button>
          </el-form-item>
          <el-form-item style="margin-left:auto;">
            <el-button type="warning" plain icon="Download" @click="handleExport2">导出</el-button>
            <el-button type="primary" plain icon="Position" :disabled="!ids2 || ids2.length === 0" @click="handleSupFromSub" v-hasPermi="['hidd:objhidd:supervise']">督办</el-button>
            <el-button type="warning" plain icon="Back" :disabled="!ids2 || ids2.length === 0" @click="handleReturnFromSub" v-hasPermi="['hidd:objhidd:return']">退回</el-button>
            <el-button type="success" plain icon="Upload" :disabled="!ids2 || ids2.length === 0" @click="handleReport2" v-hasPermi="['hidd:objhidd:report']">上报</el-button>
          </el-form-item>
        </el-form>

        <div class="table-wrapper">
        <el-table :height="tableHeight" v-loading="loading2" :data="list2" border style="width:100%" :header-cell-style="{ 'text-align': 'center' }" @selection-change="rows => ids2 = rows.map(r => r.guid)">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" type="index" width="60" />
          <el-table-column label="排查单位" align="center" prop="orgName" min-width="140" :show-overflow-tooltip="true" />
          <el-table-column label="隐患名称" align="center" prop="hiddName" min-width="160" :show-overflow-tooltip="true" />
          <el-table-column label="所属工程" align="center" prop="engName" min-width="150" :show-overflow-tooltip="true" />
          <el-table-column label="隐患类型" align="center" width="100">
            <template #default="scope">
              <dict-tag :options="hidd_clas" :value="scope.row.hiddClas" />
            </template>
          </el-table-column>
          <el-table-column label="隐患来源" align="center" width="100">
            <template #default="scope">
              <dict-tag :options="hidd_sour" :value="scope.row.hiddSour" />
            </template>
          </el-table-column>
          <el-table-column label="录入时间" align="center" width="100" prop="collTime" />
          <el-table-column label="排查日期" align="center" width="100" prop="inspDate" />
          <el-table-column label="要求完成整改日期" align="center" width="130" prop="requCompDate" />
          <el-table-column label="督办状态" align="center" width="90">
            <template #default="scope">
              <dict-tag :options="sup_stat" :value="scope.row.supStat" />
            </template>
          </el-table-column>
          <el-table-column label="隐患状态" align="center" width="90">
            <template #default="scope">
              <dict-tag :options="hidd_stat" :value="scope.row.hiddStat" />
            </template>
          </el-table-column>
        </el-table>
        </div>

        <pagination :total="total2" v-model:page="queryParams2.pageNum" v-model:limit="queryParams2.pageSize" @pagination="getList2" />
        </div>
      </el-tab-pane>

      <el-tab-pane v-if="hasTabPermi('bidEng')" label="本单位标段隐患" name="bidEng">
        <div class="table-page-wrap">
        <el-form :model="queryParams3" ref="queryRef3" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="隐患名称" prop="hiddName">
            <el-input v-model="queryParams3.hiddName" placeholder="请输入" clearable style="width: 200px" @keyup.enter="handleQuery3" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery3">搜索</el-button>
          </el-form-item>
          <el-form-item style="margin-left:auto;">
            <el-button type="primary" plain icon="Plus" @click="handleAdd3">新建</el-button>
            <el-button type="warning" plain icon="Download" @click="handleExport3">导出</el-button>
            <el-button type="danger" plain icon="Delete" :disabled="multiple3" @click="handleDelete3">删除</el-button>
            <el-button type="success" plain icon="Upload" :disabled="ids3.length === 0" @click="handleReport3" v-hasPermi="['hidd:objhidd:report']">上报</el-button>
          </el-form-item>
        </el-form>

        <div class="table-wrapper">
        <el-table :height="tableHeight" v-loading="loading3" :data="list3" @selection-change="handleSelectionChange3" border style="width:100%" :header-cell-style="{ 'text-align': 'center' }">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" type="index" width="60" />
          <el-table-column label="排查单位" align="center" prop="orgName" min-width="140" :show-overflow-tooltip="true" />
          <el-table-column label="隐患名称" align="center" prop="hiddName" min-width="160" :show-overflow-tooltip="true" />
          <el-table-column label="所属标段" align="center" prop="tendName" min-width="150" :show-overflow-tooltip="true" />
          <el-table-column label="隐患级别" align="center" width="100">
            <template #default="scope">
              <dict-tag :options="hidd_grad" :value="scope.row.hiddGrad" />
            </template>
          </el-table-column>
          <el-table-column label="隐患类型" align="center" width="100">
            <template #default="scope">
              <dict-tag :options="hidd_clas" :value="scope.row.hiddClas" />
            </template>
          </el-table-column>
          <el-table-column label="隐患来源" align="center" width="100">
            <template #default="scope">
              <dict-tag :options="hidd_sour" :value="scope.row.hiddSour" />
            </template>
          </el-table-column>
          <el-table-column label="录入时间" align="center" width="100" prop="collTime" />
          <el-table-column label="排查日期" align="center" width="100" prop="inspDate" />
          <el-table-column label="要求整改完成日期" align="center" width="130" prop="requCompDate" />
          <el-table-column label="督办状态" align="center" width="90">
            <template #default="scope">
              <dict-tag :options="sup_stat" :value="scope.row.supStat" />
            </template>
          </el-table-column>
          <el-table-column label="隐患状态" align="center" width="90">
            <template #default="scope">
              <dict-tag :options="hidd_stat" :value="scope.row.hiddStat" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="150" fixed="right">
            <template #default="scope">
              <el-button v-if="scope.row.hiddStat==='0' || scope.row.hiddStat==='1'" link type="primary" v-hasPermi="['hidd:objhidd:rectify']" @click="handleRectify(scope.row)">整改</el-button>
              <el-button v-if="scope.row.hiddStat==='2' && scope.row.supStat==='1' && scope.row.cancelState==='0'" link type="warning" v-hasPermi="['hidd:objhidd:writeoff']" @click="handleCancelApply(scope.row)">销号申请</el-button>
              <el-button link type="primary" icon="Edit" @click="handleUpdate3(scope.row)" v-hasPermi="['hidd:objhidd:edit']" />
              <el-button link type="danger" icon="Delete" @click="handleDelete3(scope.row)" v-hasPermi="['hidd:objhidd:remove']" />
            </template>
          </el-table-column>
        </el-table>
        </div>

        <pagination :total="total3" v-model:page="queryParams3.pageNum" v-model:limit="queryParams3.pageSize" @pagination="getList3" />
        </div>
      </el-tab-pane>

      <el-tab-pane v-if="hasTabPermi('consEng')" label="施工单位隐患" name="consEng">
        <div class="table-page-wrap">
        <el-form :model="queryParams4" :inline="true" v-show="showSearch" label-width="80px">
          <el-form-item label="隐患名称" prop="hiddName">
            <el-input v-model="queryParams4.hiddName" placeholder="请输入" clearable style="width: 200px" @keyup.enter="handleQuery4" />
          </el-form-item>
          <el-form-item label="选择单位" prop="orgName">
            <el-input v-model="queryParams4.orgName" placeholder="请输入" clearable style="width: 200px" @keyup.enter="handleQuery4" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery4">搜索</el-button>
          </el-form-item>
          <el-form-item style="margin-left:auto;">
            <el-button type="primary" plain icon="Plus" @click="handleAdd4">新建</el-button>
            <el-button type="warning" plain icon="Download" @click="handleExport4">导出</el-button>
            <el-button type="danger" plain icon="Delete" :disabled="multiple4" @click="handleDelete4">删除</el-button>
            <el-button type="success" plain icon="Upload" :disabled="ids4.length === 0" @click="handleReport4" v-hasPermi="['hidd:objhidd:report']">上报</el-button>
          </el-form-item>
        </el-form>

        <div class="table-wrapper">
        <el-table :height="tableHeight" v-loading="loading4" :data="list4" @selection-change="handleSelectionChange4" border style="width:100%" :header-cell-style="{ 'text-align': 'center' }">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" type="index" width="60" />
          <el-table-column label="排查单位" align="center" prop="orgName" min-width="140" :show-overflow-tooltip="true" />
          <el-table-column label="隐患名称" align="center" prop="hiddName" min-width="160" :show-overflow-tooltip="true" />
          <el-table-column label="所属标段" align="center" prop="tendName" min-width="150" :show-overflow-tooltip="true" />
          <el-table-column label="隐患级别" align="center" width="100">
            <template #default="scope">
              <dict-tag :options="hidd_grad" :value="scope.row.hiddGrad" />
            </template>
          </el-table-column>
          <el-table-column label="隐患类型" align="center" width="100">
            <template #default="scope">
              <dict-tag :options="hidd_clas" :value="scope.row.hiddClas" />
            </template>
          </el-table-column>
          <el-table-column label="隐患来源" align="center" width="100">
            <template #default="scope">
              <dict-tag :options="hidd_sour" :value="scope.row.hiddSour" />
            </template>
          </el-table-column>
          <el-table-column label="录入时间" align="center" width="100" prop="collTime" />
          <el-table-column label="排查日期" align="center" width="100" prop="inspDate" />
          <el-table-column label="要求整改完成日期" align="center" width="130" prop="requCompDate" />
          <el-table-column label="督办状态" align="center" width="90">
            <template #default="scope">
              <dict-tag :options="sup_stat" :value="scope.row.supStat" />
            </template>
          </el-table-column>
          <el-table-column label="隐患状态" align="center" width="90">
            <template #default="scope">
              <dict-tag :options="hidd_stat" :value="scope.row.hiddStat" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="100" fixed="right">
            <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handleUpdate4(scope.row)" v-hasPermi="['hidd:objhidd:edit']" />
              <el-button link type="danger" icon="Delete" @click="handleDelete4(scope.row)" v-hasPermi="['hidd:objhidd:remove']" />
            </template>
          </el-table-column>
        </el-table>
        </div>

        <pagination :total="total4" v-model:page="queryParams4.pageNum" v-model:limit="queryParams4.pageSize" @pagination="getList4" />
        </div>
      </el-tab-pane>

      <el-tab-pane v-if="hasTabPermi('partEng')" label="参建单位隐患" name="partEng">
        <div class="table-page-wrap">
        <el-form :model="queryParams5" :inline="true" v-show="showSearch" label-width="80px">
          <el-form-item label="隐患名称" prop="hiddName">
            <el-input v-model="queryParams5.hiddName" placeholder="请输入" clearable style="width: 200px" @keyup.enter="handleQuery5" />
          </el-form-item>
          <el-form-item label="选择单位" prop="orgName">
            <el-input v-model="queryParams5.orgName" placeholder="请输入" clearable style="width: 200px" @keyup.enter="handleQuery5" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery5">搜索</el-button>
          </el-form-item>
          <el-form-item style="margin-left:auto;">
            <el-button type="primary" plain icon="Plus" @click="handleAdd5">新建</el-button>
            <el-button type="warning" plain icon="Download" @click="handleExport5">导出</el-button>
            <el-button type="danger" plain icon="Delete" :disabled="multiple5" @click="handleDelete5">删除</el-button>
            <el-button type="success" plain icon="Upload" :disabled="ids5.length === 0" @click="handleReport5" v-hasPermi="['hidd:objhidd:report']">上报</el-button>
          </el-form-item>
        </el-form>

        <div class="table-wrapper">
        <el-table :height="tableHeight" v-loading="loading5" :data="list5" @selection-change="handleSelectionChange5" border style="width:100%" :header-cell-style="{ 'text-align': 'center' }">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" type="index" width="60" />
          <el-table-column label="排查单位" align="center" prop="orgName" min-width="140" :show-overflow-tooltip="true" />
          <el-table-column label="隐患名称" align="center" prop="hiddName" min-width="160" :show-overflow-tooltip="true" />
          <el-table-column label="所属标段" align="center" prop="tendName" min-width="150" :show-overflow-tooltip="true" />
          <el-table-column label="隐患级别" align="center" width="100">
            <template #default="scope">
              <dict-tag :options="hidd_grad" :value="scope.row.hiddGrad" />
            </template>
          </el-table-column>
          <el-table-column label="隐患类型" align="center" width="100">
            <template #default="scope">
              <dict-tag :options="hidd_clas" :value="scope.row.hiddClas" />
            </template>
          </el-table-column>
          <el-table-column label="隐患来源" align="center" width="100">
            <template #default="scope">
              <dict-tag :options="hidd_sour" :value="scope.row.hiddSour" />
            </template>
          </el-table-column>
          <el-table-column label="录入时间" align="center" width="100" prop="collTime" />
          <el-table-column label="排查日期" align="center" width="100" prop="inspDate" />
          <el-table-column label="要求整改完成日期" align="center" width="130" prop="requCompDate" />
          <el-table-column label="督办状态" align="center" width="90">
            <template #default="scope">
              <dict-tag :options="sup_stat" :value="scope.row.supStat" />
            </template>
          </el-table-column>
          <el-table-column label="隐患状态" align="center" width="90">
            <template #default="scope">
              <dict-tag :options="hidd_stat" :value="scope.row.hiddStat" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="100" fixed="right">
            <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handleUpdate5(scope.row)" v-hasPermi="['hidd:objhidd:edit']" />
              <el-button link type="danger" icon="Delete" @click="handleDelete5(scope.row)" v-hasPermi="['hidd:objhidd:remove']" />
            </template>
          </el-table-column>
        </el-table>
        </div>

        <pagination :total="total5" v-model:page="queryParams5.pageNum" v-model:limit="queryParams5.pageSize" @pagination="getList5" />
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 整改弹窗 -->
    <el-dialog :title="rectifyTitle" v-model="rectifyOpen" width="850px" top="5vh" append-to-body>
      <div class="form-drawer-body">
        <div class="rectify-section">
          <div class="rectify-section-title">基本信息</div>
          <table class="info-table">
            <tr>
              <td class="label-cell">隐患名称</td>
              <td class="value-cell">{{ rectifyRow.hiddName || '' }}</td>
              <td class="label-cell">排查日期</td>
              <td class="value-cell">{{ rectifyRow.inspDate || '' }}</td>
            </tr>
            <tr>
              <td class="label-cell">所属工程</td>
              <td class="value-cell">{{ rectifyRow.engName || '' }}</td>
              <td class="label-cell">所属标段</td>
              <td class="value-cell">{{ rectifyRow.tendName || '' }}</td>
            </tr>
            <tr>
              <td class="label-cell">隐患级别</td>
              <td class="value-cell">{{ rectifyRow.hiddGrad === '1' ? '重大隐患' : '一般隐患' }}</td>
              <td class="label-cell">隐患类型</td>
              <td class="value-cell">{{ rectifyRow.hiddClas === '1' ? '工程隐患' : '非工程隐患' }}</td>
            </tr>
            <tr>
              <td class="label-cell">排查单位</td>
              <td class="value-cell">{{ rectifyRow.orgName || '' }}</td>
              <td class="label-cell">发现人</td>
              <td class="value-cell">{{ rectifyRow.inspLeader || '' }}</td>
            </tr>
            <tr>
              <td class="label-cell">职务</td>
              <td class="value-cell">{{ rectifyRow.inspLeaderPost || '' }}</td>
              <td class="label-cell">隐患部位</td>
              <td class="value-cell">{{ rectifyRow.proPart || '' }}</td>
            </tr>
            <tr>
              <td class="label-cell">隐患情况描述</td>
              <td class="value-cell" colspan="3">{{ rectifyRow.hiddDesc || '' }}</td>
            </tr>
            <tr>
              <td class="label-cell">现场照片附件</td>
              <td class="value-cell" colspan="3">
                <span v-if="(rectifyRow.fileList || []).length === 0" style="color:#999;">暂无附件</span>
                <span v-else>{{ rectifyRow.fileList.map(f => f.name || f.medName).join('；') }}</span>
              </td>
            </tr>
          </table>
        </div>

        <div class="rectify-section">
          <div class="rectify-section-title">整改落实</div>
          <table class="form-table">
            <tr>
              <td class="label-cell">治理责任单位<span style="color:red">*</span></td>
              <td class="value-cell">
                <el-input v-model="rectForm.goverRespWiunName" placeholder="请输入" size="small" />
              </td>
              <td class="label-cell">整改责任人<span style="color:red">*</span></td>
              <td class="value-cell">
                <el-input v-model="rectForm.rectLegPers" placeholder="请输入" size="small" />
              </td>
            </tr>
            <tr>
              <td class="label-cell">责任人电话</td>
              <td class="value-cell">
                <el-input v-model="rectForm.rectPersOffiTel" placeholder="请输入" size="small" />
              </td>
              <td class="label-cell">要求完成整改日期<span style="color:red">*</span></td>
              <td class="value-cell">
                <el-date-picker v-model="rectForm.requCompDate" type="date" placeholder="选择日期" size="small" style="width:100%" />
              </td>
            </tr>
            <tr>
              <td class="label-cell">累计落实治理资金（元）</td>
              <td class="value-cell" colspan="3">
                <el-input v-model="rectForm.acimpGoverFund" placeholder="请输入金额" size="small" />
              </td>
            </tr>
          </table>
          <table class="form-table" style="margin-top:8px;">
            <tr>
              <td class="label-cell" style="width:120px">治理目标任务<span style="color:red">*</span></td>
              <td class="value-cell">
                <el-input v-model="rectForm.goveObjeTasks" type="textarea" :rows="2" placeholder="请输入（500字以内）" size="small" />
              </td>
              <td class="label-cell" style="width:120px">安全措施应急预案<span style="color:red">*</span></td>
              <td class="value-cell">
                <el-input v-model="rectForm.emerPlanSame" type="textarea" :rows="2" placeholder="请输入（500字以内）" size="small" />
              </td>
            </tr>
            <tr>
              <td class="label-cell" style="width:120px">整改措施描述<span style="color:red">*</span></td>
              <td class="value-cell" colspan="3">
                <el-input v-model="rectForm.corrMeas" type="textarea" :rows="2" placeholder="请输入（500字以内）" size="small" />
              </td>
            </tr>
          </table>
        </div>

        <div class="rectify-section">
          <div class="rectify-section-title">整改进展情况</div>
          <el-button size="small" type="primary" @click="addProgRow" style="margin-bottom:8px;">添加</el-button>
          <el-table :data="rectProgList" border size="small" style="width:100%">
            <el-table-column label="进展情况" align="center" min-width="200">
              <template #default="scope">
                <el-input v-model="scope.row.rectProg" placeholder="请输入" size="small" />
              </template>
            </el-table-column>
            <el-table-column label="填报人" align="center" width="120">
              <template #default="scope">
                <el-input v-model="scope.row.recPersName" placeholder="请输入" size="small" />
              </template>
            </el-table-column>
            <el-table-column label="填报时间" align="center" width="140">
              <template #default="scope">
                <el-input v-model="scope.row.collTime" placeholder="选择日期" size="small" />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="60">
              <template #default="scope">
                <el-button link type="danger" icon="Delete" @click="removeProgRow(scope['$index'])" />
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="rectify-section">
          <div class="rectify-section-title">整改完成</div>
          <table class="form-table">
            <tr>
              <td class="label-cell">完成日期</td>
              <td class="value-cell">
                <el-date-picker v-model="rectAcceForm.requCompDate" type="date" placeholder="选择日期" size="small" style="width:100%" />
              </td>
              <td class="label-cell">治理责任单位验收责任人</td>
              <td class="value-cell">
                <el-input v-model="rectAcceForm.accepLegPers" placeholder="请输入" size="small" />
              </td>
            </tr>
          </table>
        </div>
      </div>
      <template #footer>
        <el-button type="primary" @click="submitRectify" :loading="rectifyLoading">保 存</el-button>
        <el-button @click="rectifyOpen = false">取 消</el-button>
      </template>
    </el-dialog>

    <!-- 整改消耗弹窗（验收/销号，对应旧版 openDialog1） -->
    <el-dialog title="整改消耗信息" v-model="cancelOpen" width="550px" append-to-body>
      <el-form :model="cancelForm" ref="cancelFormRef" label-width="80px">
        <el-form-item label="责任人" prop="accepPers" :rules="[{ required: true, message: '请输入责任人', trigger: 'blur' }]">
          <el-input v-model="cancelForm.accepPers" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="消耗时间">
          <el-date-picker v-model="cancelForm.accepDate" type="date" placeholder="选择日期" style="width:100%" />
        </el-form-item>
        <el-form-item label="验收意见" prop="accepOpin" :rules="[{ required: true, message: '请输入验收意见', trigger: 'blur' }]">
          <el-input v-model="cancelForm.accepOpin" type="textarea" :rows="3" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitCancel">确 认</el-button>
        <el-button @click="cancelOpen = false">取 消</el-button>
      </template>
    </el-dialog>

    <!-- 隐患详情弹窗（对应旧版 hiddInfo.jsp） -->
    <el-dialog title="隐患信息" v-model="detailOpen" width="700px" append-to-body>
      <table class="rectify-table">
        <tr>
          <td class="td-head">隐患名称</td>
          <td>{{ detailForm.hiddName || '--' }}</td>
          <td class="td-head">所属工程</td>
          <td>{{ detailForm.engName || '--' }}</td>
        </tr>
        <tr>
          <td class="td-head">排查日期</td>
          <td>{{ detailForm.inspDate || '--' }}</td>
          <td class="td-head">隐患级别</td>
          <td>{{ detailForm.hiddGrad === '2' ? '重大隐患' : '一般隐患' }}</td>
        </tr>
        <tr>
          <td class="td-head">隐患类别</td>
          <td><dict-tag :options="hidd_clas" :value="detailForm.hiddClas" /></td>
          <td class="td-head">排查单位</td>
          <td>{{ detailForm.orgName || '--' }}</td>
        </tr>
        <tr>
          <td class="td-head">涉及部位</td>
          <td>{{ detailForm.proPart || '--' }}</td>
          <td class="td-head">隐患状态</td>
          <td><dict-tag :options="hidd_stat" :value="detailForm.hiddStat" /></td>
        </tr>
        <tr>
          <td class="td-head">隐患描述</td>
          <td colspan="3">{{ detailForm.otlcolQiffFnvu || '--' }}</td>
        </tr>
        <tr>
          <td class="td-head">备注</td>
          <td colspan="3">{{ detailForm.note || '--' }}</td>
        </tr>
      </table>
      <template #footer>
        <el-button @click="detailOpen = false">关 闭</el-button>
      </template>
    </el-dialog>

    <!-- 新建/修改弹窗 -->
    <el-dialog v-model="formDrawer" :title="formTitle" width="750px" top="5vh" append-to-body>
      <div class="form-drawer-body">
        <div class="info-tip">
          <i class="el-icon-info" style="color:#409EFF;"></i>
          上传的附件文件命名应为中文，按照多个附件文件，文件名称格式为中文+序号（001，按照增加），例如演练照片001。用于说明该文件内容。文件名称中文部分内容长度不可超过10个文字。文件类型为jpg、jpeg、png、pdf，单个文件大小不能超过10MB。
        </div>

        <div class="rectify-section-title">基本信息</div>
        <table class="form-table">
          <tr>
            <td class="label-cell"><span class="required">*</span>隐患名称</td>
            <td class="value-cell">
              <el-autocomplete v-model="form.hiddName" :fetch-suggestions="queryHiddName" placeholder="请输入隐患名称（支持模糊搜索）" size="small" :trigger-on-focus="true" clearable style="width:100%" />
            </td>
            <td class="label-cell"><span class="required">*</span>排查日期</td>
            <td class="value-cell">
              <el-date-picker v-model="form.inspDate" type="date" placeholder="请选择排查日期" size="small" style="width:100%" />
            </td>
          </tr>
          <tr v-if="activeTab !== 'partEng' && activeTab !== 'consEng'">
            <td class="label-cell">所属工程</td>
            <td class="value-cell">
              <el-select v-model="form.engGuid" placeholder="请选择" size="small" style="width:100%"
                @change="val => { form.engName = (engList.find(e => e.value === val) || {}).label || ''; form.tendGuid = ''; form.tendName = '' }">
                <el-option v-for="item in engList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </td>
            <td class="label-cell">所属标段</td>
            <td class="value-cell">
              <el-select v-model="form.tendGuid" placeholder="请先选择所属工程" size="small" style="width:100%"
                :disabled="!form.engGuid"
                @change="val => { form.tendName = (filteredTendList.find(e => e.value === val) || {}).label || '' }">
                <el-option v-for="item in filteredTendList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </td>
          </tr>
          <tr v-else>
            <td class="label-cell">所属标段</td>
            <td class="value-cell" colspan="3">
              <el-select v-model="form.tendGuid" placeholder="请选择" size="small" style="width:100%"
                @change="val => { form.tendName = (filteredTendList.find(e => e.value === val) || {}).label || '' }">
                <el-option v-for="item in filteredTendList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </td>
          </tr>
          <tr>
            <td class="label-cell"><span class="required">*</span>隐患级别</td>
            <td class="value-cell">
              <el-select v-model="form.hiddGrad" placeholder="请输入隐患级别" size="small" style="width:100%">
                <el-option v-for="dict in hidd_grad" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </td>
            <td class="label-cell"><span class="required">*</span>隐患类型</td>
            <td class="value-cell">
              <el-select v-model="form.hiddClas" placeholder="请选择隐患类型" size="small" style="width:100%">
                <el-option v-for="dict in hidd_clas" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </td>
          </tr>
          <tr>
            <td class="label-cell"><span class="required">*</span>隐患来源</td>
            <td class="value-cell" colspan="3">
              <el-select v-model="form.hiddSour" placeholder="请选择隐患来源" size="small" style="width:100%">
                <el-option v-for="dict in hidd_sour" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </td>
          </tr>
          <tr>
            <td class="label-cell"><span class="required">*</span>排查单位</td>
            <td class="value-cell">
              <el-input v-model="form.orgName" placeholder="请输入排查单位" size="small" />
            </td>
            <td class="label-cell">发现人</td>
            <td class="value-cell">
              <el-input v-model="form.inspLeader" placeholder="请输入发现人" size="small" />
            </td>
          </tr>
          <tr v-if="activeTab === 'consEng'">
            <td class="label-cell"><span class="required">*</span>目标施工单位</td>
            <td class="value-cell" colspan="3">
              <el-select v-model="form.orgGuid" placeholder="请选择目标施工单位" size="small" style="width:100%" filterable
                @change="val => { const o = consOrgList.find(o => o.value === val); if (o) form.orgName = o.label }">
                <el-option v-for="item in consOrgList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </td>
          </tr>
          <tr>
            <td class="label-cell">职务</td>
            <td class="value-cell">
              <el-input v-model="form.inspLeaderPost" placeholder="请输入职务" size="small" />
            </td>
            <td class="label-cell"><span class="required">*</span>隐患部位</td>
            <td class="value-cell">
              <el-input v-model="form.proPart" placeholder="请输入隐患部位" size="small" />
            </td>
          </tr>
          <tr>
            <td class="label-cell"><span class="required">*</span>隐患情况描述</td>
            <td class="value-cell" colspan="3">
              <el-input v-model="form.hiddDesc" type="textarea" :rows="3" placeholder="请输入隐患情况描述" size="small" />
            </td>
          </tr>
          <tr>
            <td class="label-cell">现场照片附件</td>
            <td class="value-cell" colspan="3">
              <el-upload
                ref="uploadRef"
                :action="uploadUrl"
                :headers="uploadHeaders"
                :multiple="true"
                :limit="10"
                :on-success="handleUploadSuccess"
                :on-remove="handleUploadRemove"
                :file-list="uploadFileList"
                accept=".doc,.docx,.xls,.xlsx,.txt,.pdf,.zip,.rar,.jpg,.jpeg,.png,.gif"
                list-type="text"
              >
                <el-button type="primary" size="small">选择文件</el-button>
                <span class="upload-warning ml8">（最多上传5个文件）</span>
              </el-upload>
            </td>
          </tr>
        </table>
      </div>
      <template #footer>
        <el-button @click="formDrawer = false">取 消</el-button>
        <el-button type="primary" @click="submitFormDrawer" :loading="formLoading">保 存</el-button>
      </template>
    </el-dialog>

    <!-- 退回弹窗 -->
    <el-dialog title="隐患退回" v-model="returnOpen" width="500px" append-to-body>
      <el-form :model="returnForm" label-width="80px">
        <el-form-item label="退回说明" required>
          <el-input v-model="returnForm.returnDesc" type="textarea" :rows="4" maxlength="500" show-word-limit placeholder="请输入退回说明（500字以内）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitReturn">确 定</el-button>
        <el-button @click="returnOpen = false">取 消</el-button>
      </template>
    </el-dialog>

    <!-- 督办弹窗（从subEng发起） -->
    <el-dialog title="隐患督办" v-model="supDialogOpen" width="700px" append-to-body>
      <el-form :model="supDialogForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="隐患名称">
              <el-input v-model="supDialogForm.hiddName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="隐患级别">
              <el-input :value="supDialogForm.hiddGrad === '2' ? '重大隐患' : '一般隐患'" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="督办文号" required>
              <el-input v-model="supDialogForm.supLareId" placeholder="请输入督办文号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="整改期限" required>
              <el-date-picker v-model="supDialogForm.rectPeri" type="date" value-format="YYYY-MM-DD" placeholder="选择整改期限" style="width:100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="督办意见" required>
          <el-input v-model="supDialogForm.supOpin" type="textarea" :rows="4" placeholder="请输入督办意见" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitSupDialog">确 定</el-button>
        <el-button @click="supDialogOpen = false">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="OrgEngQuery">
import { listObjHidd, delObjHidd, addObjHidd, updateObjHidd, compoundSaveHidd, getHiddGroupBy, listBisHiddRectImpl, addBisHiddRectImpl, updateBisHiddRectImpl, listBisHiddRectAcce, addBisHiddRectAcce, updateBisHiddRectAcce, listBisHiddRectProg, addBisHiddRectProg, listAttEngBase, listNextDepHidd, writeOffBisMajHiddSup, getHiddListByName, listAttOrgBase, applyWriteOffBisMajHiddSup, approveWriteOffBisMajHiddSup, reportHidd, returnHidd, addBisMajHiddSup } from "@/api/slaj/hidd"
import { getToken } from "@/utils/auth"
import useUserStore from '@/store/modules/user'

const tableHeight = ref('calc(100vh - 240px)')
const { proxy } = getCurrentInstance()
const { hidd_grad, hidd_stat, sup_stat, hidd_sour, hidd_clas } = proxy.useDict("hidd_grad", "hidd_stat", "sup_stat", "hidd_sour", "hidd_clas")
const userStore = useUserStore()

const tabPermiMap = {
  selfEng: 'hidd:tab:selfEng',
  subEng: 'hidd:tab:subEng',
  bidEng: 'hidd:tab:bidEng',
  consEng: 'hidd:tab:consEng',
  partEng: 'hidd:tab:partEng'
}
function hasTabPermi(name) {
  const permi = tabPermiMap[name]
  if (!permi) return true
  return proxy.$auth.hasPermi(permi)
}
const activeTab = ref(Object.keys(tabPermiMap).find(k => hasTabPermi(k)) || 'selfEng')
const showSearch = ref(true)

watch(activeTab, (val) => {
  if (!hasTabPermi(val)) {
    const first = Object.keys(tabPermiMap).find(k => hasTabPermi(k))
    if (first) activeTab.value = first
  }
})

// Tab1 本单位工程隐患
const list = ref([]); const loading = ref(false); const total = ref(0)
const ids = ref([]); const single = ref(true); const multiple = ref(true)
const queryParams = reactive({ pageNum: 1, pageSize: 10, hiddSort: '1', hiddName: undefined })

// 整改弹窗
const rectifyOpen = ref(false)
const rectifyTitle = ref('隐患整改')
const rectForm = ref({})
const rectProgList = ref([])
const rectAcceForm = ref({})
const rectifyLoading = ref(false)
const rectifyHiddGuid = ref('')
const rectifyRow = ref({})

// 附件上传
const uploadUrl = import.meta.env.VITE_APP_BASE_API + '/common/upload'
const uploadHeaders = { Authorization: 'Bearer ' + getToken() }
const uploadFileList = ref([])
const uploadRef = ref(null)
const fileAttachList = ref([])

// 工程列表
const engList = ref([])

const tendList = ref([])
const consOrgList = ref([])
const filteredTendList = computed(() => {
  if (!form.value.engGuid) return tendList.value
  return tendList.value.filter(t => t.engGuid === form.value.engGuid)
})

// 隐患详情弹窗（对应旧版 hiddInfo.jsp）
const detailOpen = ref(false)
const detailForm = ref({})

// 整改消耗弹窗
const cancelOpen = ref(false)
const cancelForm = ref({})
const cancelFormRef = ref(null)

function getList() {
  loading.value = true
  listObjHidd({ ...queryParams, pageNum: queryParams.pageNum, pageSize: queryParams.pageSize }).then(res => {
    list.value = res.rows || []
    total.value = res.total || 0
    loading.value = false
  }).catch(() => { loading.value = false })
}
function handleQuery() { queryParams.pageNum = 1; getList() }
function handleSelectionChange(selection) { ids.value = selection.map(item => item.guid); single.value = selection.length !== 1; multiple.value = !selection.length }
// 新建/修改抽屉
const formDrawer = ref(false)
const formTitle = ref('新建隐患')
const form = ref({})
const formLoading = ref(false)
const isEditMode = computed(() => !!form.value.guid)

function queryHiddName(queryString, cb) {
  if (!queryString) { cb([]); return }
  getHiddListByName({ hiddName: queryString, pageSize: 20 }).then(res => {
    const list = (res.rows || []).map(item => ({ value: item.hiddName, hiddGrad: item.hiddGrad, hiddClas: item.hiddClas, proPart: item.proPart }))
    cb(list)
  }).catch(() => cb([]))
}

function handleAdd() {
  formTitle.value = '本级单位工程隐患新增'
  form.value = { hiddSort: '1', hiddGrad: '1', hiddStat: '0', inspDate: '', inspLeader: '', inspLeaderPost: '', proPart: '', hiddDesc: '', engGuid: '', tendGuid: '', engName: '', tendName: '', orgGuid: userStore.orgGuid || '' }
  listAttEngBase({}).then(res => { engList.value = (res.rows || []).map(e => ({ value: e.guid, label: e.engName })) })
  fileAttachList.value = []
  uploadFileList.value = []
  formDrawer.value = true
}

function handleUpdate(row) {
  const guid = row ? row.guid : ids.value[0]
  if (!guid) { proxy.$modal.msgWarning('请先选择一条数据'); return }
  const data = list.value.find(d => d.guid === guid)
  if (data) {
    form.value = { ...data, engGuid: data.engGuid || '', tendGuid: data.tendGuid || '' }
    listAttEngBase({}).then(res => { engList.value = (res.rows || []).map(e => ({ value: e.guid, label: e.engName })) })
    formTitle.value = '本级单位工程隐患修改'
    fileAttachList.value = []
    uploadFileList.value = []
    formDrawer.value = true
  }
}

function handleUploadSuccess(response, file, fileList) {
  if (response.code === 200) {
    fileAttachList.value.push({ name: file.name, path: response.fileName })
  }
  uploadFileList.value = fileList
}
function handleUploadRemove(file, fileList) {
  const idx = fileAttachList.value.findIndex(f => f.name === file.name && f.path === (file.response?.fileName || ''))
  if (idx >= 0) fileAttachList.value.splice(idx, 1)
  uploadFileList.value = fileList
}

function submitFormDrawer() {
  if (!form.value.hiddName) { proxy.$modal.msgWarning('请输入隐患名称'); return }
  formLoading.value = true
  const params = {
    ...form.value,
    hiddDesc: form.value.hiddDesc,
    fileList: fileAttachList.value,
    bisHiddInveDto: [{
      inspDate: form.value.inspDate,
      inspOrgGuid: form.value.orgGuid,
      recPers: form.value.inspLeader,
      inspLeaderPost: form.value.inspLeaderPost
    }]
  }
  compoundSaveHidd(params).then(res => {
    proxy.$modal.msgSuccess(form.value.guid ? '修改成功' : '新增成功')
    formDrawer.value = false
    formLoading.value = false
    fileAttachList.value = []
    uploadFileList.value = []
    if (activeTab.value === 'partEng') { getList5() }
    else if (activeTab.value === 'consEng') { getList4() }
    else if (activeTab.value === 'bidEng') { getList3() }
    else { getList() }
  }).catch(() => {
    formLoading.value = false
  })
}

function handleExport() { proxy.download("hidd/objhidd/export", { ...queryParams }, `本单位工程隐患_${new Date().getTime()}.xlsx`) }
function handleExport2() { proxy.download("hidd/objhidd/export", { ...queryParams2 }, `下级单位隐患_${new Date().getTime()}.xlsx`) }

function handleReport() {
  if (!ids.value.length) { proxy.$modal.msgWarning('请先选择要上报的隐患'); return }
  proxy.$modal.confirm('确认上报选中的隐患？').then(() => {
    reportHidd(ids.value).then(() => {
      proxy.$modal.msgSuccess('上报成功')
      getList()
    })
  }).catch(() => {})
}
function handleReport2() {
  if (!ids2.value || !ids2.value.length) { proxy.$modal.msgWarning('请先选择要上报的隐患'); return }
  proxy.$modal.confirm('确认逐级上报选中的隐患？').then(() => {
    reportHidd(ids2.value).then(() => {
      proxy.$modal.msgSuccess('上报成功')
      getList2()
    })
  }).catch(() => {})
}
function handleReport3() {
  if (!ids3.value.length) { proxy.$modal.msgWarning('请先选择要上报的隐患'); return }
  proxy.$modal.confirm('确认上报选中的隐患？').then(() => {
    reportHidd(ids3.value).then(() => {
      proxy.$modal.msgSuccess('上报成功')
      getList3()
    })
  }).catch(() => {})
}
function handleReport4() {
  if (!ids4.value.length) { proxy.$modal.msgWarning('请先选择要上报的隐患'); return }
  proxy.$modal.confirm('确认上报选中的隐患？').then(() => {
    reportHidd(ids4.value).then(() => {
      proxy.$modal.msgSuccess('上报成功')
      getList4()
    })
  }).catch(() => {})
}
function handleReport5() {
  if (!ids5.value.length) { proxy.$modal.msgWarning('请先选择要上报的隐患'); return }
  proxy.$modal.confirm('确认上报选中的隐患？').then(() => {
    reportHidd(ids5.value).then(() => {
      proxy.$modal.msgSuccess('上报成功')
      getList5()
    })
  }).catch(() => {})
}

const returnForm = ref({})
const returnOpen = ref(false)
function handleReturnFromSub() {
  if (!ids2.value || !ids2.value.length) { proxy.$modal.msgWarning('请先选择要退回的隐患'); return }
  returnForm.value = { guids: ids2.value, returnDesc: '' }
  returnOpen.value = true
}
function submitReturn() {
  if (!returnForm.value.returnDesc) { proxy.$modal.msgWarning('请填写退回说明'); return }
  returnHidd(returnForm.value.guids, returnForm.value.returnDesc).then(() => {
    proxy.$modal.msgSuccess('退回成功')
    returnOpen.value = false
    getList2()
  })
}

const supDialogOpen = ref(false)
const supDialogForm = ref({})
function handleSupFromSub() {
  if (!ids2.value || !ids2.value.length) { proxy.$modal.msgWarning('请先选择要督办的隐患'); return }
  supDialogForm.value = { hiddGuids: ids2.value, hiddName: list2.value.find(r => ids2.value.includes(r.guid))?.hiddName || '', hiddGrad: list2.value.find(r => ids2.value.includes(r.guid))?.hiddGrad || '', proPart: list2.value.find(r => ids2.value.includes(r.guid))?.proPart || '', engName: list2.value.find(r => ids2.value.includes(r.guid))?.engName || '', supLareId: '', supDate: '', supWiunName: '', rectPeri: '', isList: '0', supOpin: '' }
  supDialogOpen.value = true
}
function submitSupDialog() {
  if (!supDialogForm.value.supOpin) { proxy.$modal.msgWarning('请填写督办意见'); return }
  if (!supDialogForm.value.supLareId) { proxy.$modal.msgWarning('请填写督办文号'); return }
  if (!supDialogForm.value.rectPeri) { proxy.$modal.msgWarning('请选择整改期限'); return }
  const hiddGuid = supDialogForm.value.hiddGuids[0]
  addBisMajHiddSup({ ...supDialogForm.value, hiddGuid }).then(() => {
    proxy.$modal.msgSuccess('督办成功')
    supDialogOpen.value = false
    getList2()
  })
}

function handleDelete(row) {
  const guids = row ? [row.guid] : ids.value
  if (!guids.length) { proxy.$modal.msgWarning('请先选择一条数据'); return }
  proxy.$modal.confirm('是否确认删除？').then(() => {
    delObjHidd(guids.join(',')).then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
  }).catch(() => {})
}

function handleCancelApply(row) {
  cancelForm.value = { guid: row.guid, accepPers: '', accepDate: '', accepOpin: '' }
  cancelOpen.value = true
}
function submitCancel() {
  cancelFormRef.value.validate(valid => {
    if (!valid) return
    applyWriteOffBisMajHiddSup({ guid: cancelForm.value.guid }).then(() => {
      proxy.$modal.msgSuccess('销号申请已提交，等待上级审批')
      cancelOpen.value = false
      if (activeTab.value === 'bidEng') { getList3() } else if (activeTab.value === 'consEng') { getList4() } else if (activeTab.value === 'partEng') { getList5() } else { getList() }
    }).catch(() => {})
  })
}

// Tab2-5 下级/标段/施工/参建
const list2 = ref([]); const loading2 = ref(false); const total2 = ref(0)
const ids2 = ref([])
const queryParams2 = reactive({ pageNum: 1, pageSize: 10, hiddName: undefined, orgName: undefined })
const list3 = ref([]); const loading3 = ref(false); const total3 = ref(0)
const ids3 = ref([]); const single3 = ref(true); const multiple3 = ref(true)
const queryParams3 = reactive({ pageNum: 1, pageSize: 10, hiddName: undefined })
const list4 = ref([]); const loading4 = ref(false); const total4 = ref(0)
const ids4 = ref([]); const single4 = ref(true); const multiple4 = ref(true)
const queryParams4 = reactive({ pageNum: 1, pageSize: 10, hiddName: undefined, orgName: undefined })
const list5 = ref([]); const loading5 = ref(false); const total5 = ref(0)
const ids5 = ref([]); const single5 = ref(true); const multiple5 = ref(true)
const queryParams5 = reactive({ pageNum: 1, pageSize: 10, hiddName: undefined, orgName: undefined })

function getList4() {
  loading4.value = true
  listObjHidd({ ...queryParams4, pageNum: queryParams4.pageNum, pageSize: queryParams4.pageSize, wiunProp: '7' }).then(res => {
    list4.value = res.rows || []
    total4.value = res.total || 0
    loading4.value = false
  }).catch(() => { loading4.value = false })
}
function handleAdd4() {
  formTitle.value = '施工单位隐患新增'
  form.value = { hiddSort: '1', hiddGrad: '1', hiddStat: '0', hiddSour: '1', inspDate: '', inspLeader: '', inspLeaderPost: '', proPart: '', hiddDesc: '', engGuid: '', tendGuid: '', engName: '', tendName: '', orgName: '', orgGuid: userStore.orgGuid || '' }
  listAttEngBase({}).then(res => { engList.value = (res.rows || []).map(e => ({ value: e.guid, label: e.engName })) })
  listAttOrgBase({ orgNature: '7' }).then(res => {
    consOrgList.value = (res.rows || []).map(o => ({ value: o.guid, label: o.orgName }))
  })
  fileAttachList.value = []
  uploadFileList.value = []
  formDrawer.value = true
}
function handleUpdate4(row) {
  const data = row || (ids4.value.length ? list4.value.find(d => d.guid === ids4.value[0]) : null)
  if (!data) { proxy.$modal.msgWarning('请先选择一条数据'); return }
  form.value = { ...data, engGuid: data.engGuid || '', tendGuid: data.tendGuid || '' }
  listAttEngBase({}).then(res => { engList.value = (res.rows || []).map(e => ({ value: e.guid, label: e.engName })) })
  formTitle.value = '施工单位隐患修改'
  fileAttachList.value = []
  uploadFileList.value = []
  formDrawer.value = true
}
function handleDelete4(row) {
  const guids = row ? [row.guid] : ids4.value
  if (!guids.length) { proxy.$modal.msgWarning('请先选择一条数据'); return }
  proxy.$modal.confirm('是否确认删除？').then(() => {
    delObjHidd(guids.join(',')).then(() => {
      getList4()
      proxy.$modal.msgSuccess('删除成功')
    })
  }).catch(() => {})
}
function handleSelectionChange4(selection) { ids4.value = selection.map(item => item.guid); single4.value = selection.length !== 1; multiple4.value = !selection.length }
function handleQuery4() { queryParams4.pageNum = 1; getList4() }
function handleExport4() { proxy.download("hidd/objhidd/export", { ...queryParams4, wiunProp: '7' }, `施工单位隐患_${new Date().getTime()}.xlsx`) }
function getList2() {
  loading2.value = true
  listNextDepHidd({ ...queryParams2, pageNum: queryParams2.pageNum, pageSize: queryParams2.pageSize, orgGuid: userStore.orgGuid || undefined, hiddSort: '1' }).then(res => {
    list2.value = res.rows || []
    total2.value = res.total || 0
    loading2.value = false
  }).catch(() => { loading2.value = false })
}
function getList3() {
  loading3.value = true
  listObjHidd({ ...queryParams3, pageNum: queryParams3.pageNum, pageSize: queryParams3.pageSize, orgGuid: userStore.orgGuid || undefined, hiddSort: '1' }).then(res => {
    list3.value = res.rows || []
    total3.value = res.total || 0
    loading3.value = false
  }).catch(() => { loading3.value = false })
}
function getList5() {
  loading5.value = true
  listObjHidd({ ...queryParams5, pageNum: queryParams5.pageNum, pageSize: queryParams5.pageSize, wiunProp: '6' }).then(res => {
    list5.value = res.rows || []
    total5.value = res.total || 0
    loading5.value = false
  }).catch(() => { loading5.value = false })
}
function handleAdd5() {
  formTitle.value = '参建单位隐患新增'
  form.value = { hiddSort: '1', hiddGrad: '1', hiddStat: '0', inspDate: '', inspLeader: '', inspLeaderPost: '', proPart: '', hiddDesc: '', engGuid: '', tendGuid: '', engName: '', tendName: '', orgGuid: userStore.orgGuid || '' }
  listAttEngBase({}).then(res => { engList.value = (res.rows || []).map(e => ({ value: e.guid, label: e.engName })) })
  fileAttachList.value = []
  uploadFileList.value = []
  formDrawer.value = true
}
function handleUpdate5(row) {
  const data = row || (ids5.value.length ? list5.value.find(d => d.guid === ids5.value[0]) : null)
  if (!data) { proxy.$modal.msgWarning('请先选择一条数据'); return }
  form.value = { ...data, engGuid: data.engGuid || '', tendGuid: data.tendGuid || '' }
  listAttEngBase({}).then(res => { engList.value = (res.rows || []).map(e => ({ value: e.guid, label: e.engName })) })
  formTitle.value = '参建单位隐患修改'
  fileAttachList.value = []
  uploadFileList.value = []
  formDrawer.value = true
}
function handleDelete5(row) {
  const guids = row ? [row.guid] : ids5.value
  if (!guids.length) { proxy.$modal.msgWarning('请先选择一条数据'); return }
  proxy.$modal.confirm('是否确认删除？').then(() => {
    delObjHidd(guids.join(',')).then(() => {
      getList5()
      proxy.$modal.msgSuccess('删除成功')
    })
  }).catch(() => {})
}
function handleSelectionChange5(selection) { ids5.value = selection.map(item => item.guid); single5.value = selection.length !== 1; multiple5.value = !selection.length }
function handleQuery5() { queryParams5.pageNum = 1; getList5() }
function handleExport5() { proxy.download("hidd/objhidd/export", { ...queryParams5, wiunProp: '6' }, `参建单位隐患_${new Date().getTime()}.xlsx`) }
function handleQuery2() { queryParams2.pageNum = 1; getList2() }
function handleQuery3() { queryParams3.pageNum = 1; getList3() }
function handleSelectionChange3(selection) { ids3.value = selection.map(item => item.guid); single3.value = selection.length !== 1; multiple3.value = !selection.length }
function handleAdd3() {
  formTitle.value = '本级单位标段隐患新增'
  form.value = { hiddSort: '1', hiddGrad: '1', hiddStat: '0', inspDate: '', inspLeader: '', inspLeaderPost: '', proPart: '', hiddDesc: '', engGuid: '', tendGuid: '', engName: '', tendName: '', orgGuid: userStore.orgGuid || '' }
  listAttEngBase({}).then(res => { engList.value = (res.rows || []).map(e => ({ value: e.guid, label: e.engName })) })
  fileAttachList.value = []
  uploadFileList.value = []
  formDrawer.value = true
}
function handleUpdate3(row) {
  const guid = row ? row.guid : ids3.value[0]
  if (!guid) { proxy.$modal.msgWarning('请先选择一条数据'); return }
  const data = list3.value.find(d => d.guid === guid)
  if (data) {
    form.value = { ...data, engGuid: data.engGuid || '', tendGuid: data.tendGuid || '' }
    listAttEngBase({}).then(res => { engList.value = (res.rows || []).map(e => ({ value: e.guid, label: e.engName })) })
    formTitle.value = '本级单位标段隐患修改'
    fileAttachList.value = []
    uploadFileList.value = []
    formDrawer.value = true
  }
}
function handleDelete3(row) {
  const guids = row ? [row.guid] : ids3.value
  if (!guids.length) { proxy.$modal.msgWarning('请先选择一条数据'); return }
  proxy.$modal.confirm('是否确认删除？').then(() => {
    delObjHidd(guids.join(',')).then(() => {
      getList3()
      proxy.$modal.msgSuccess('删除成功')
    })
  }).catch(() => {})
}
function handleExport3() { proxy.download("hidd/objhidd/export", { ...queryParams3 }, `本单位标段隐患_${new Date().getTime()}.xlsx`) }

function handleRectify(row) {
  const hiddGuid = row.guid
  rectifyHiddGuid.value = hiddGuid
  rectifyRow.value = { ...row }
  rectifyTitle.value = '工程隐患整改记录维护'
  rectForm.value = {
    goverRespWiunName: row.orgName || '',
    rectLegPers: '',
    rectPersOffiTel: '',
    requCompDate: '',
    acimpGoverFund: '',
    goveObjeTasks: '',
    emerPlanSame: '',
    corrMeas: ''
  }
  rectProgList.value = []
  rectAcceForm.value = { requCompDate: '', accepLegPers: '' }
  rectifyOpen.value = true
}

function addProgRow() {
  rectProgList.value.push({ rectProg: '', recPersName: '', collTime: '' })
}

function removeProgRow(index) {
  rectProgList.value.splice(index, 1)
}

function submitRectify() {
  if (!rectForm.value.goverRespWiunName) { proxy.$modal.msgWarning('请填写治理责任单位'); return }
  if (!rectForm.value.rectLegPers) { proxy.$modal.msgWarning('请填写整改责任人'); return }
  if (!rectForm.value.requCompDate) { proxy.$modal.msgWarning('请选择要求完成整改日期'); return }
  if (!rectForm.value.goveObjeTasks) { proxy.$modal.msgWarning('请填写治理目标任务'); return }
  if (!rectForm.value.emerPlanSame) { proxy.$modal.msgWarning('请填写安全措施应急预案'); return }
  if (!rectForm.value.corrMeas) { proxy.$modal.msgWarning('请填写整改措施描述'); return }
  rectifyLoading.value = true
  const hiddGuid = rectifyHiddGuid.value
  const p1 = listBisHiddRectImpl({ hiddGuid }).then(res => {
    const data = {
      hiddGuid,
      goverRespWiun: rectForm.value.goverRespWiunName,
      rectLegPers: rectForm.value.rectLegPers,
      rectPersOffiTel: rectForm.value.rectPersOffiTel,
      requCompDate: rectForm.value.requCompDate,
      acimpGoverFund: rectForm.value.acimpGoverFund ? Number(rectForm.value.acimpGoverFund) : null,
      goveObjeTasks: rectForm.value.goveObjeTasks,
      emerPlanSame: rectForm.value.emerPlanSame,
      corrMeas: rectForm.value.corrMeas
    }
    const rows = res.rows || []
    if (rows.length > 0) {
      data.guid = rows[0].guid
      return updateBisHiddRectImpl(data)
    } else {
      return addBisHiddRectImpl(data)
    }
  })
  const p2 = listBisHiddRectProg({ hiddGuid }).then(res => {
    const oldProgs = res.rows || []
    const delPromises = oldProgs.map(p => delBisHiddRectProg(p.guid))
    return Promise.all(delPromises).then(() => {
      const addPromises = rectProgList.value
        .filter(item => item.rectProg)
        .map(item => addBisHiddRectProg({ hiddGuid, rectProg: item.rectProg, recPers: item.recPersName, collTime: item.collTime }))
      return Promise.all(addPromises)
    })
  })
  const p3 = listBisHiddRectAcce({ hiddGuid }).then(res => {
    if (!rectAcceForm.value.requCompDate && !rectAcceForm.value.accepLegPers) return
    const data = {
      hiddGuid,
      requCompDate: rectAcceForm.value.requCompDate,
      accepLegPers: rectAcceForm.value.accepLegPers
    }
    const rows = res.rows || []
    if (rows.length > 0) {
      data.guid = rows[0].guid
      return updateBisHiddRectAcce(data)
    } else {
      return addBisHiddRectAcce(data)
    }
  })
  Promise.all([p1, p2, p3]).then(() => {
    const completedRect = !!(rectAcceForm.value.requCompDate && rectAcceForm.value.accepLegPers)
    const newHiddStat = completedRect ? '2' : '1'
    if (rectifyRow.value.hiddStat !== newHiddStat) {
      updateObjHidd({ guid: hiddGuid, hiddStat: newHiddStat }).catch(() => {})
    }
    proxy.$modal.msgSuccess('保存成功')
    rectifyOpen.value = false
    rectifyLoading.value = false
    if (activeTab.value === 'bidEng') { getList3() } else if (activeTab.value === 'consEng') { getList4() } else if (activeTab.value === 'partEng') { getList5() } else { getList() }
  }).catch(() => {
    rectifyLoading.value = false
  })
}

function handleTabChange() {
  if (activeTab.value === 'selfEng') getList()
  else if (activeTab.value === 'subEng') getList2()
  else if (activeTab.value === 'bidEng') getList3()
  else if (activeTab.value === 'consEng') getList4()
  else if (activeTab.value === 'partEng') getList5()
}

onMounted(() => { getList() })
</script>

<style scoped>
.rectify-section {
  margin-bottom: 20px;
  background: #fff;
  border-radius: 4px;
}
.rectify-section-title {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 12px;
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-left: 3px solid #409EFF;
  border-radius: 2px;
  color: #303133;
}
/* 只读信息表格 - 旧版风格 */
.info-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #e4e7ed;
}
.info-table td {
  border: 1px solid #e4e7ed;
  padding: 8px 12px;
  font-size: 13px;
  line-height: 1.6;
}
.info-table .label-cell {
  width: 100px;
  text-align: right;
  font-weight: normal;
  background-color: #fafafa;
  color: #606266;
  white-space: nowrap;
}
.info-table .value-cell {
  text-align: left;
  color: #303133;
  min-width: 120px;
}
/* 可编辑表单表格 */
.form-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #e4e7ed;
}
.form-table td {
  padding: 6px 8px;
  font-size: 13px;
  border: 1px solid #e4e7ed;
}
.form-table .label-cell {
  width: 110px;
  text-align: right;
  vertical-align: middle;
  background-color: #fafafa;
  color: #606266;
  white-space: nowrap;
  padding-right: 12px;
}
.form-table .value-cell {
  vertical-align: middle;
  padding: 6px 8px;
  min-width: 120px;
}
.required {
  color: #f56c6c;
  margin-right: 2px;
}
.form-drawer-body {
  padding: 0;
  max-height: 65vh;
  overflow-y: auto;
}
.info-tip {
  background: #EBF3FF;
  border: 1px solid #C2D7FF;
  border-radius: 4px;
  padding: 8px 12px;
  margin-bottom: 16px;
  font-size: 12px;
  color: #606266;
  line-height: 1.6;
}
.info-tip i {
  margin-right: 4px;
}
.upload-warning {
  color: #f56c6c;
  font-size: 12px;
  margin-bottom: 8px;
  line-height: 1.6;
}
</style>
