<template>
  <div class="app-container">
    <el-tabs v-model="activeTab" type="border-card" @tab-change="handleTabChange">
      <el-tab-pane label="本单位工程隐患" name="selfEng">
        <div ref="containerRef" 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-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" 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 link type="primary" @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" @click="handleCancelApply(scope.row)">销号申请</el-button>
              <span v-else-if="scope.row.hiddStat==='2' && scope.row.cancelState==='1'" style="color:#E6A23C">待销号</span>
              <span v-else-if="scope.row.hiddStat==='2' && scope.row.cancelState==='2'" style="color:#67C23A">已销号</span>
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" />
              <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" />
            </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 label="下级单位隐患" name="subEng">
        <div ref="containerRef2" class="table-page-wrap">
        <el-form :model="queryParams2" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="工程名称" prop="engName">
            <el-input v-model="queryParams2.engName" placeholder="请输入" clearable style="width: 200px" />
          </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 label="采集时间" prop="collTime">
            <el-date-picker v-model="queryParams2.collTime" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" clearable style="width: 160px" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery2">搜索</el-button>
            <el-button type="warning" plain icon="Download" @click="handleExport2">导出</el-button>
          </el-form-item>
        </el-form>

        <el-table :height="tableHeight" v-loading="loading2" :data="list2" border style="width:100%" :header-cell-style="{ 'text-align': 'center' }">
          <el-table-column label="序号" align="center" type="index" width="60" />
          <el-table-column label="工程名称" align="center" prop="engName" min-width="150" :show-overflow-tooltip="true" />
          <el-table-column label="管理单位" align="center" prop="orgName" min-width="140" :show-overflow-tooltip="true" />
          <el-table-column label="总数" align="center" prop="totalCount" width="80" />
          <el-table-column label="一般隐患" align="center" prop="normalCount" width="90" />
          <el-table-column label="重大隐患" align="center" prop="majorCount" width="90" />
          <el-table-column label="已整改隐患" align="center" prop="solvedCount" width="100" />
        </el-table>

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

      <el-tab-pane label="本单位标段隐患" name="bidEng">
        <div class="table-page-wrap">
        <el-form :model="queryParams3" :inline="true" v-show="showSearch" label-width="80px">
          <el-form-item label="标段名称" prop="engName">
            <el-input v-model="queryParams3.engName" placeholder="请输入" clearable style="width: 200px" />
          </el-form-item>
          <el-form-item label="单位名称" prop="orgName">
            <el-input v-model="queryParams3.orgName" placeholder="请输入" clearable style="width: 200px" />
          </el-form-item>
          <el-form-item label="采集时间" prop="collTime">
            <el-date-picker v-model="queryParams3.collTime" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" clearable style="width: 160px" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery3">搜索</el-button>
            <el-button type="warning" plain icon="Download" @click="handleExport3">导出</el-button>
          </el-form-item>
        </el-form>

        <el-table :height="tableHeight" v-loading="loading3" :data="list3" border style="width:100%" :header-cell-style="{ 'text-align': 'center' }">
          <el-table-column label="序号" align="center" type="index" width="60" />
          <el-table-column label="标段名称" align="center" prop="engName" min-width="150" :show-overflow-tooltip="true" />
          <el-table-column label="管理单位" align="center" prop="orgName" min-width="140" :show-overflow-tooltip="true" />
          <el-table-column label="总数" align="center" prop="totalCount" width="80" />
          <el-table-column label="一般隐患" align="center" prop="normalCount" width="90" />
          <el-table-column label="重大隐患" align="center" prop="majorCount" width="90" />
          <el-table-column label="已整改隐患" align="center" prop="solvedCount" width="100" />
        </el-table>

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

      <el-tab-pane 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="engName">
            <el-input v-model="queryParams4.engName" placeholder="请输入" clearable style="width: 200px" />
          </el-form-item>
          <el-form-item label="单位名称" prop="orgName">
            <el-input v-model="queryParams4.orgName" placeholder="请输入" clearable style="width: 200px" />
          </el-form-item>
          <el-form-item label="采集时间" prop="collTime">
            <el-date-picker v-model="queryParams4.collTime" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" clearable style="width: 160px" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery4">搜索</el-button>
            <el-button type="warning" plain icon="Download" @click="handleExport4">导出</el-button>
          </el-form-item>
        </el-form>

        <el-table :height="tableHeight" v-loading="loading4" :data="list4" border style="width:100%" :header-cell-style="{ 'text-align': 'center' }">
          <el-table-column label="序号" align="center" type="index" width="60" />
          <el-table-column label="工程名称" align="center" prop="engName" min-width="150" :show-overflow-tooltip="true" />
          <el-table-column label="管理单位" align="center" prop="orgName" min-width="140" :show-overflow-tooltip="true" />
          <el-table-column label="总数" align="center" prop="totalCount" width="80" />
          <el-table-column label="一般隐患" align="center" prop="normalCount" width="90" />
          <el-table-column label="重大隐患" align="center" prop="majorCount" width="90" />
          <el-table-column label="已整改隐患" align="center" prop="solvedCount" width="100" />
        </el-table>

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

      <el-tab-pane 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="engName">
            <el-input v-model="queryParams5.engName" placeholder="请输入" clearable style="width: 200px" />
          </el-form-item>
          <el-form-item label="单位名称" prop="orgName">
            <el-input v-model="queryParams5.orgName" placeholder="请输入" clearable style="width: 200px" />
          </el-form-item>
          <el-form-item label="采集时间" prop="collTime">
            <el-date-picker v-model="queryParams5.collTime" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" clearable style="width: 160px" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery5">搜索</el-button>
            <el-button type="warning" plain icon="Download" @click="handleExport5">导出</el-button>
          </el-form-item>
        </el-form>

        <el-table :height="tableHeight" v-loading="loading5" :data="list5" border style="width:100%" :header-cell-style="{ 'text-align': 'center' }">
          <el-table-column label="序号" align="center" type="index" width="60" />
          <el-table-column label="工程名称" align="center" prop="engName" min-width="150" :show-overflow-tooltip="true" />
          <el-table-column label="管理单位" align="center" prop="orgName" min-width="140" :show-overflow-tooltip="true" />
          <el-table-column label="总数" align="center" prop="totalCount" width="80" />
          <el-table-column label="一般隐患" align="center" prop="normalCount" width="90" />
          <el-table-column label="重大隐患" align="center" prop="majorCount" width="90" />
          <el-table-column label="已整改隐患" align="center" prop="solvedCount" width="100" />
        </el-table>

        <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="800px" top="5vh" append-to-body>
      <div class="rectify-section">
        <div class="rectify-section-title">隐患整改落实</div>
        <table class="rectify-table">
          <tr>
            <td class="td-head">治理责任单位</td>
            <td>{{ rectForm.goverRespWiunName || '--' }}</td>
            <td class="td-head">整改责任人</td>
            <td>{{ rectForm.rectLegPers || '--' }}</td>
          </tr>
          <tr>
            <td class="td-head">责任人电话</td>
            <td>{{ rectForm.rectPersOffiTel || '--' }}</td>
            <td class="td-head">整改完成日期</td>
            <td>{{ rectForm.requCompDate || '--' }}</td>
          </tr>
          <tr>
            <td class="td-head">累计落实治理资金</td>
            <td colspan="3">{{ rectForm.acimpGoverFund ? rectForm.acimpGoverFund + '元' : '--' }}</td>
          </tr>
          <tr>
            <td class="td-head">治理目标任务</td>
            <td colspan="3">{{ rectForm.goveObjeTasks || '--' }}</td>
          </tr>
          <tr>
            <td class="td-head">安全措施应急预案</td>
            <td colspan="3">{{ rectForm.emerPlanSame || '--' }}</td>
          </tr>
          <tr>
            <td class="td-head">整改措施描述</td>
            <td colspan="3">{{ rectForm.corrMeas || '--' }}</td>
          </tr>
        </table>
      </div>

      <div class="rectify-section">
        <div class="rectify-section-title">隐患整改进展情况</div>
        <el-table :data="rectProgList" border size="small">
          <el-table-column label="序号" align="center" type="index" width="60" />
          <el-table-column label="进展情况" align="center" prop="rectProg" :show-overflow-tooltip="true" />
          <el-table-column label="填报人" align="center" prop="recPers" width="100" />
          <el-table-column label="填报时间" align="center" width="120">
            <template #default="scope">
              {{ scope.row.collTime ? scope.row.collTime.substring(0, 10) : '--' }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="rectify-section">
        <div class="rectify-section-title">隐患整改验收情况</div>
        <table class="rectify-table">
          <tr>
            <td class="td-head">验收责任人</td>
            <td>{{ rectAcceForm.accepLegPers || '--' }}</td>
            <td class="td-head">整改完成日期</td>
            <td>{{ rectAcceForm.requCompDate || '--' }}</td>
          </tr>
        </table>
      </div>

      <template #footer>
        <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="选择日期" value-format="YYYY-MM-DD" 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="form-section-title">基本信息</div>
        <table class="form-table">
          <tr>
            <td class="label-cell"><span class="required">*</span>隐患名称</td>
            <td class="value-cell">
              <div class="input-with-action">
                <el-input v-model="form.hiddName" placeholder="请输入隐患名称" size="small" />
                <el-button type="primary" size="small" link>选择</el-button>
              </div>
            </td>
            <td class="label-cell"><span class="required">*</span>所属工程</td>
            <td class="value-cell">
              <el-select v-model="form.engName" placeholder="请选择所属工程" size="small" style="width:100%">
                <el-option v-for="dict in engList" :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-date-picker v-model="form.inspDate" type="date" placeholder="请选择排查日期" value-format="YYYY-MM-DD" size="small" style="width:100%" />
            </td>
            <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>
          </tr>
            <tr>
              <td class="label-cell"><span class="required">*</span>所属工程</td>
              <td class="value-cell">
                <el-input v-model="form.engName" placeholder="请选择所属工程" size="small" />
              </td>
              <td class="label-cell"><span class="required">*</span>排查单位</td>
              <td class="value-cell">
                <el-input v-model="form.orgName" placeholder="请输入排查单位" size="small" />
              </td>
            </tr>
          <tr>
            <td class="label-cell">发现人</td>
            <td class="value-cell">
              <el-input v-model="form.inspLeader" placeholder="请输入发现人" size="small" />
            </td>
            <td class="label-cell">职务</td>
            <td class="value-cell">
              <el-input v-model="form.inspLeaderPost" placeholder="请输入职务" size="small" />
            </td>
          </tr>
          <tr>
            <td class="label-cell"><span class="required">*</span>隐患部位</td>
            <td class="value-cell">
              <el-input v-model="form.proPart" placeholder="请输入隐患部位" size="small" />
            </td>
            <td class="label-cell"><span class="required">*</span>隐患情况描述</td>
            <td class="value-cell">
              <el-input v-model="form.hiddDesc" placeholder="请输入隐患情况描述" size="small" />
            </td>
          </tr>
          <tr>
            <td class="label-cell"><span class="required">*</span>现场照片附件</td>
            <td class="value-cell" colspan="3">
              <div class="upload-warning">
                <p>本平台为互联网涉密平台，严禁处理、传输国家秘密</p>
                <p>严禁在本互联网涉密平台处理、传输国家秘密，请确认以扫描、传输的文件资料不涉及国家秘密。</p>
              </div>
              <el-upload ref="uploadRef" action="#" :auto-upload="false" :limit="10" accept=".jpg,.jpeg,.png,.pdf">
                <el-button type="primary" size="small">添加文件</el-button>
                <el-button type="success" size="small" @click="uploadFiles">上传文件</el-button>
                <span style="color:#999;font-size:12px;margin-left:8px;">最多只能上传10个文件</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>
  </div>
</template>

<script setup name="OrgEngQuery">
import { listObjHidd, delObjHidd, addObjHidd, updateObjHidd, compoundSaveHidd, getHiddGroupBy, listBisHiddRectImpl, listBisHiddRectAcce, listBisHiddRectProg } from "@/api/slaj/hidd"
import { useTableHeight } from '@/hooks/useTableHeight'

const { tableHeight, containerRef } = useTableHeight()
const { proxy } = getCurrentInstance()
const { hidd_grad, hidd_stat, sup_stat, hidd_clas } = proxy.useDict("hidd_grad", "hidd_stat", "sup_stat", "hidd_clas")

const activeTab = ref('selfEng')
const showSearch = ref(true)

// 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({})

// 隐患详情弹窗（对应旧版 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).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 handleAdd() {
  formTitle.value = '本级单位工程隐患新增'
  form.value = { hiddSort: '1', hiddGrad: '1', hiddStat: '0', inspDate: '', inspLeader: '', inspLeaderPost: '', proPart: '', hiddDesc: '', engGuid: '', orgGuid: '' }
  formDrawer.value = true
}

function handleUpdate(row) {
  const guid = row ? row.guid : ids.value[0]
  if (!guid) { proxy.$modal.msgWarning('请先选择一条数据'); return }
  listObjHidd({ guid: guid }).then(res => {
    if (res.rows && res.rows.length > 0) {
      const data = res.rows[0]
      form.value = {
        ...data,
        inspLeader: data.inspLeader || '',
        inspLeaderPost: data.inspLeaderPost || '',
        hiddDesc: data.otlcolQiffFnvu || data.hiddDesc || ''
      }
      // 查询整改落实
      listBisHiddRectImpl({ hiddGuid: guid }).then(rectRes => {
        if (rectRes.rows && rectRes.rows.length > 0) {
          const r = rectRes.rows[0]
          form.value = { ...form.value, ...r, goverRespWiunName: r.goverRespWiunName || r.goverRespWiun || '' }
        }
        // 查询整改验收
        listBisHiddRectAcce({ hiddGuid: guid }).then(acceRes => {
          if (acceRes.rows && acceRes.rows.length > 0) {
            const a = acceRes.rows[0]
            form.value = { ...form.value, accepDate: a.accepDate, accepLegPers: a.accepLegPers, requCompDate: a.requCompDate }
          }
        })
      })
      formTitle.value = '修改隐患'
      formDrawer.value = true
    }
  })
}

function uploadFiles() {
  proxy.$modal.msgInfo('文件上传功能待实现')
}

function submitFormDrawer() {
  if (!form.value.hiddName) { proxy.$modal.msgWarning('请输入隐患名称'); return }
  formLoading.value = true
  const data = {
    hiddName: form.value.hiddName,
    engGuid: form.value.engGuid || '',
    hiddGrad: form.value.hiddGrad,
    hiddClas: form.value.hiddClas,
    hiddStat: form.value.hiddStat || '0',
    proPart: form.value.proPart,
    hiddDesc: form.value.hiddDesc || form.value.otlcolQiffFnvu,
    hiddSort: form.value.hiddSort || '1',
    orgGuid: form.value.orgGuid || form.value.revoOrgGuid || '',
    isList: form.value.isList || '0',
    bisHiddInveDto: [{
      inspDate: form.value.inspDate ? form.value.inspDate + ' 00:00:00' : '',
      inspOrgGuid: form.value.orgGuid || form.value.revoOrgGuid || '',
      recPers: form.value.inspLeader || '',
      inspLeaderPost: form.value.inspLeaderPost || ''
    }]
  }
  if (form.value.guid) {
    data.guid = form.value.guid
  }
  compoundSaveHidd(data).then(() => {
    proxy.$modal.msgSuccess(form.value.guid ? '修改成功' : '新增成功')
    formDrawer.value = false
    formLoading.value = false
    getList()
  }).catch(() => { formLoading.value = false })
}

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

function handleDelete(row) {
  const guids = row.guid || ids.value.join(',')
  proxy.$modal.confirm('是否确认删除？').then(() => delObjHidd(guids)).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
    proxy.$modal.msgSuccess('销号申请已提交')
    cancelOpen.value = false
  })
}

// Tab2-5 统计聚合
const list2 = ref([]); const loading2 = ref(false); const total2 = ref(0)
const queryParams2 = reactive({ pageNum: 1, pageSize: 10, hiddSort: '1', engName: undefined, orgName: undefined, collTime: undefined })
const list3 = ref([]); const loading3 = ref(false); const total3 = ref(0)
const queryParams3 = reactive({ pageNum: 1, pageSize: 10, hiddSort: '1', engName: undefined, orgName: undefined, collTime: undefined })
const list4 = ref([]); const loading4 = ref(false); const total4 = ref(0)
const queryParams4 = reactive({ pageNum: 1, pageSize: 10, hiddSort: '1', engName: undefined, orgName: undefined, collTime: undefined })
const list5 = ref([]); const loading5 = ref(false); const total5 = ref(0)
const queryParams5 = reactive({ pageNum: 1, pageSize: 10, hiddSort: '1', engName: undefined, orgName: undefined, collTime: undefined })

function loadGroup(params, listRef, loadingRef, totalRef) {
  loadingRef.value = true
  getHiddGroupBy(params).then(res => {
    listRef.value = res.data || []
    totalRef.value = listRef.value.length
    loadingRef.value = false
  }).catch(() => { loadingRef.value = false })
}
function getList2() { loadGroup(queryParams2, list2, loading2, total2) }
function getList3() { loadGroup(queryParams3, list3, loading3, total3) }
function getList4() { loadGroup(queryParams4, list4, loading4, total4) }
function getList5() { loadGroup(queryParams5, list5, loading5, total5) }
function handleQuery2() { queryParams2.pageNum = 1; getList2() }
function handleQuery3() { queryParams3.pageNum = 1; getList3() }
function handleQuery4() { queryParams4.pageNum = 1; getList4() }
function handleQuery5() { queryParams5.pageNum = 1; getList5() }
function handleExport2() { proxy.download("hidd/objhidd/export", { ...queryParams2 }, `下级单位隐患_${new Date().getTime()}.xlsx`) }
function handleExport3() { proxy.download("hidd/objhidd/export", { ...queryParams3 }, `标段隐患_${new Date().getTime()}.xlsx`) }
function handleExport4() { proxy.download("hidd/objhidd/export", { ...queryParams4 }, `施工单位隐患_${new Date().getTime()}.xlsx`) }
function handleExport5() { proxy.download("hidd/objhidd/export", { ...queryParams5 }, `参建单位隐患_${new Date().getTime()}.xlsx`) }

function handleRectify(row) {
  const hiddGuid = row.guid
  rectifyTitle.value = '隐患整改落实 - ' + (row.hiddName || '')
  rectForm.value = {}
  rectProgList.value = []
  rectAcceForm.value = {}
  rectifyOpen.value = true
  // 查询整改落实
  listBisHiddRectImpl({ hiddGuid: hiddGuid }).then(res => {
    if (res.rows && res.rows.length > 0) {
      rectForm.value = res.rows[0]
    }
  })
  // 查询整改验收
  listBisHiddRectAcce({ hiddGuid: hiddGuid }).then(res => {
    if (res.rows && res.rows.length > 0) {
      rectAcceForm.value = res.rows[0]
    }
  })
  // 查询整改进展
  listBisHiddRectProg({ hiddGuid: hiddGuid }).then(res => {
    rectProgList.value = res.rows || []
  })
}

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: 16px;
}
.rectify-section-title {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 8px;
  padding: 6px 12px;
  background-color: #F2F2F2;
  border-left: 3px solid #409EFF;
}
.rectify-table {
  width: 100%;
  border-collapse: collapse;
  text-align: center;
}
.rectify-table td {
  border: 1px solid #e4e7ed;
  padding: 8px 12px;
  font-size: 13px;
}
.td-head {
  font-weight: bold;
  width: 20%;
  background-color: #fafafa;
}
.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: 12px;
  font-size: 12px;
  color: #606266;
  line-height: 1.6;
}
.info-tip i {
  margin-right: 4px;
}
.form-section-title {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e4e7ed;
}
.form-table {
  width: 100%;
  border-collapse: collapse;
}
.form-table td {
  padding: 6px 8px;
  font-size: 13px;
}
.label-cell {
  width: 15%;
  text-align: right;
  vertical-align: middle;
  color: #606266;
  white-space: nowrap;
}
.value-cell {
  width: 35%;
  vertical-align: middle;
}
.required {
  color: #f56c6c;
  margin-right: 2px;
}
.input-with-action {
  display: flex;
  align-items: center;
  gap: 8px;
}
.upload-warning {
  color: #f56c6c;
  font-size: 12px;
  margin-bottom: 8px;
  line-height: 1.6;
}
</style>
