<template>
  <div class="app-container">
    <!-- 查询条件区域 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px" label-position="top">
      <el-form-item label="工单编码" prop="workOrderProjectNo" label-position="top">
        <el-input
            v-model="queryParams.workOrderProjectNo"
            placeholder="请输入工单编码"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="风机编号" prop="pcsDeviceName" label-position="top">
        <el-input
            v-model="queryParams.pcsDeviceName"
            placeholder="请输入风机编号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="维保中心" prop="gxtCenter" label-position="top">
        <el-select
            v-model="queryParams.gxtCenter"
            placeholder="请选择维保中心"
            clearable
            @change="handleMaintenanceCenterChange"
        >
          <el-option
              v-for="item in maintenanceCenterOptions"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptName">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="场站" prop="pcsStationName" label-position="top">
        <el-select
            v-model="queryParams.pcsStationName"
            placeholder="请选择场站"
            clearable
            :disabled="!queryParams.gxtCenter"
        >
          <el-option
              v-for="item in stationOptions"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptName">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工单状态" prop="workOrderStatus" label-position="top">
        <el-select v-model="queryParams.workOrderStatus" placeholder="请选择工单状态" clearable>
          <el-option
              v-for="dict in gxt_work_order_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label-position="top">
          <div class="item-search">&nbsp;</div>
          <div class="item-search">
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          </div>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <!-- 空的按钮区域，保持与其他页面一致的间距 -->
    </el-row>

    <!-- 工单列表 -->
    <el-table
        v-loading="loading"
        :data="orderList"
        style="width: 100%"
        :max-height="tableHeight"
    >
      <el-table-column label="工单类型" align="center" prop="orderType" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.orderType === 1" type="danger">维修工单</el-tag>
          <el-tag v-else type="success">维保工单</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="工单编码" align="center" prop="workOrderProjectNo" width="160" fixed>
        <template #default="scope">
          <el-button link type="primary" @click="handleView(scope.row)">
            {{ scope.row.workOrderProjectNo }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="风机编号" align="center" prop="pcsDeviceName" width="120" :show-overflow-tooltip="true">
        <template #default="scope">
          {{ scope.row.pcsDeviceName || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="工单状态" align="center" prop="workOrderStatus" min-width="100">
        <template #default="scope">
          <dict-tag :options="gxt_work_order_status" :value="scope.row.workOrderStatus" />
        </template>
      </el-table-column>
      <el-table-column label="维保中心" align="center" prop="gxtCenter"  width="150" :show-overflow-tooltip="true">
        <template #default="scope">
          {{ scope.row.gxtCenter || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="场站" align="center" prop="pcsStationName" width="150" :show-overflow-tooltip="true">
        <template #default="scope">
          {{ scope.row.pcsStationName || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="品牌" align="center" prop="brand" width="120" :show-overflow-tooltip="true">
        <template #default="scope">
          {{ scope.row.brand || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="机型" align="center" prop="model" width="120" :show-overflow-tooltip="true">
        <template #default="scope">
          {{ scope.row.model || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="接单人" align="center" prop="acceptUserName" width="100" >
        <template #default="scope">
          {{ scope.row.acceptUserName || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="接单时间" align="center" prop="acceptTime" width="150">
        <template #default="scope">
          <span>{{ scope.row.acceptTime ? parseTime(scope.row.acceptTime, '{y}-{m}-{d} {h}:{i}') : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="工作负责人" align="center" prop="teamLeaderName" width="100" >
        <template #default="scope">
          {{ scope.row.teamLeaderName || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="realStartTime" width="150">
        <template #default="scope">
          <span>{{ scope.row.realStartTime ? parseTime(scope.row.realStartTime, '{y}-{m}-{d} {h}:{i}') : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="realEndTime" width="150">
        <template #default="scope">
          <span>{{ scope.row.realEndTime ? parseTime(scope.row.realEndTime, '{y}-{m}-{d} {h}:{i}') : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="200" fixed="right">
        <template #default="scope">
          <!-- 维修工单操作按钮 -->
          <template v-if="scope.row.orderType === 1">

            <el-button
                v-if="scope.row.workOrderStatus === 'to_issue' || scope.row.workOrderStatus === 'accept_return'"
                type="primary"
                link
                @click="handleUpdate(scope.row)"
                v-hasPermi="['gxt:repairOrder:edit']"
            ><i class="fa fa-user-plus"></i>下发</el-button>

            <el-button
                v-if="scope.row.workOrderStatus === 'assigned'"
                type="primary"
                link
                @click="handleAccept(scope.row)"
                v-hasPermi="['gxt:repairOrder:accept']"
            ><i class="fa fa-check"></i>接单</el-button>
            <el-button
                v-if="(scope.row.workOrderStatus === 'to_finish') && (scope.row.teamLeaderId == userStore.id || userStore.roles.includes('admin'))"
                type="danger"
                link
                @click="handleRepairSuspend(scope.row)"
                v-hasPermi="['gxt:repairOrder:suspend']"
            ><i class="fa fa-stop"></i>挂起</el-button>
            <el-button
                v-if="(scope.row.workOrderStatus === 'to_finish') && (scope.row.teamLeaderId == userStore.id || userStore.roles.includes('admin'))"
                type="warning"
                link
                @click="handleReturn(scope.row)"
                v-hasPermi="['gxt:repairOrder:return']"
            ><i class="fa fa-sign-in"></i>退回</el-button> <!--结单退回，负责人退回至班长 -->
            <el-button
                v-if="scope.row.workOrderStatus === 'return'|| scope.row.workOrderStatus === 'assigned'"
                type="warning"
                link
                @click="handleReturn(scope.row)"
                v-hasPermi="['gxt:repairOrder:acceptReturn']"
            ><i class="fa fa-sign-in"></i>退回</el-button> <!--接单退回，班长退回至下发环节 -->
            <el-button
                v-if="scope.row.workOrderStatus === 'to_finish' && (scope.row.teamLeaderId == userStore.id || userStore.roles.includes('admin'))"
                type="success"
                link
                @click="handleRepairOrderFinalize(scope.row)"
                v-hasPermi="['gxt:repairOrder:finalize']"
            ><i class="fa fa-check"></i>结单</el-button>
            <el-button
                v-if="scope.row.workOrderStatus === 'to_finish' && (scope.row.teamLeaderId == userStore.id || userStore.roles.includes('admin'))"
                type="primary"
                link
                @click="handleReset(scope.row)"
                v-hasPermi="['gxt:repairOrder:finalize']"
            ><i class="fa fa-refresh"></i>复启</el-button>
            <el-button
                v-if="scope.row.workOrderStatus === 'to_approve'"
                type="primary"
                link
                @click="handleApprove(scope.row)"
                v-hasPermi="['gxt:repairOrder:approve']"
            ><i class="fa fa-check-circle"></i>审批</el-button>

            <el-button
                v-if="scope.row.restartTime == null && scope.row.workOrderStatus != 'to_issue' && scope.row.workOrderStatus != 'auto_suspend' && scope.row.workOrderStatus != 'accept_return'"
                type="success"
                link
                @click="handleRestart(scope.row)"
                v-hasPermi="['gxt:repairOrder:restart']"
            ><i class="fa fa-refresh"></i>复运</el-button>
          </template>

          <!-- 维保工单操作按钮 -->
          <template v-else>
            <el-button
                v-if="scope.row.workOrderStatus === 'to_issue'"
                type="primary"
                link
                @click="handleUpdate(scope.row)"
                v-hasPermi="['gxt:maintenance:order:edit']"
            ><i class="fa fa-user-plus"></i>下发</el-button>

            <el-button
                v-if="scope.row.workOrderStatus === 'assigned'"
                type="primary"
                link
                @click="handleAccept(scope.row)"
                v-hasPermi="['gxt:maintenance:order:accept']"
            ><i class="fa fa-check"></i>接单</el-button>

            <el-button
                v-if="(scope.row.workOrderStatus === 'to_finish') && (scope.row.teamLeaderId == userStore.id || userStore.roles.includes('admin')) "
                type="danger"
                link
                @click="handleSuspend(scope.row)"
                v-hasPermi="['gxt:maintenance:order:suspend']"
            ><i class="fa fa-stop"></i>挂起</el-button>

            <el-button
                v-if="(scope.row.workOrderStatus === 'to_finish') && (scope.row.teamLeaderId == userStore.id || userStore.roles.includes('admin'))"
                type="success"
                link
                @click="handleFinish(scope.row)"
                v-hasPermi="['gxt:maintenance:order:complete']"
            ><i class="fa fa-check"></i>结单</el-button>

            <el-button
                v-if="scope.row.workOrderStatus === 'to_approve'"
                type="primary"
                link
                @click="handleApprove(scope.row)"
                v-hasPermi="['gxt:maintenance:order:approve']"
            ><i class="fa fa-check-circle"></i>审批</el-button>

            <el-button
                link type="success"
                @click="handleRestart(scope.row)"
                v-if="scope.row.restartTime == null && scope.row.workOrderStatus != 'to_issue' && scope.row.workOrderStatus != 'auto_suspend'"
                v-hasPermi="['gxt:maintenance:order:restart']">
              <i class="fa fa-refresh"></i>复运
            </el-button>
          </template>

          <el-button
              type="info"
              link
              @click="handleView(scope.row)"
          ><i class="fa fa-eye"></i>查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 维修工单详情对话框 -->
    <ViewDialog
        v-model="repairDetailDialogVisible"
        :data="detailData"
        :work-order-status-options="gxt_work_order_status"
        :reset-method-options="gxt_reset_method"
        :repair-order-flow-action-type-options="gxt_repair_order_flow_action_type"
        :work-area-options="gxt_work_area"
        :return-type-options="gxt_return_type"
    />

    <!-- 维保工单详情对话框 -->
    <ViewWorkOrderDialog
        v-model="workDetailDialogVisible"
        :data="detailData"
        :work-order-status-options="gxt_work_order_status"
        :repair-order-flow-action-type-options="gxt_repair_order_flow_action_type"
    />

    <!-- 接单对话框 (维修工单) -->
    <el-dialog title="接单" v-model="acceptRepairDialogVisible" width="800px" append-to-body>
      <el-form ref="acceptRepairFormRef" :model="acceptRepairForm" :rules="acceptRepairRules" label-width="120px" label-position="top">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工单编码"><el-input v-model="acceptRepairForm.workOrderProjectNo" disabled /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="风机编号"><el-input v-model="acceptRepairForm.pcsDeviceName" disabled /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单状态">
              <el-select v-model="acceptRepairForm.workOrderStatus" style="width: 100%" disabled>
                <el-option
                    v-for="dict in gxt_work_order_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维保中心"><el-input v-model="acceptRepairForm.gxtCenter" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="场站"><el-input v-model="acceptRepairForm.pcsStationName" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌"><el-input v-model="acceptRepairForm.brand" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="故障代码"><el-input v-model="acceptRepairForm.faultCode" disabled /></el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="故障信息">
              <el-input
                  v-model="acceptRepairForm.faultBarcode"
                  type="textarea"
                  placeholder="请输入故障信息"
                  maxlength="100"
                  show-word-limit
                  :rows="3"
                  disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="工作负责人" prop="teamLeaderId">
              <el-input
                  v-model="acceptRepairForm.teamLeaderName"
                  placeholder="请输入工作负责人姓名或点击选择"
                  clearable
                  @focus="handleTeamLeaderInputFocus"
                  @blur="handleTeamLeaderInputBlur"
                  @input="handleTeamLeaderInput"
                  @clear="handleTeamLeaderClear"
              >
              </el-input>
              <!-- 快速检索下拉框 -->
              <div class="quick-select-dropdown" v-show="showTeamLeaderQuickSelect && quickTeamLeaderList.length > 0">
                <div
                    v-for="item in quickTeamLeaderList"
                    :key="item.userId"
                    class="quick-select-item"
                    @click="handleTeamLeaderQuickSelect(item)">
                  <span class="user-name">{{ item.nickName }}</span>
                  <span class="user-dept">{{ item.dept?.deptName }}</span>
                </div>
              </div>
              <div class="quick-select-dropdown no-data" v-show="showTeamLeaderQuickSelect && quickTeamLeaderList.length === 0 && acceptRepairForm.teamLeaderName && !teamLeaderLoading">
                <div>未找到匹配的人员</div>
              </div>
              <div class="quick-select-dropdown no-data" v-show="showTeamLeaderQuickSelect && teamLeaderLoading">
                <div>
                  <i class="el-icon-loading"></i>
                  搜索中...
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="acceptRepairDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitAcceptRepair">确认接单</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 接单对话框 (维保工单) -->
    <el-dialog title="接单" v-model="acceptWorkDialogVisible" width="800px" append-to-body>
      <el-form ref="acceptWorkFormRef" :model="acceptWorkForm" :rules="acceptWorkRules" label-width="120px" label-position="top">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工单编码"><el-input v-model="acceptWorkForm.workOrderProjectNo" disabled /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="风机编号"><el-input v-model="acceptWorkForm.pcsDeviceName" disabled /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单状态">
              <el-select v-model="acceptWorkForm.workOrderStatus" style="width: 100%" disabled>
                <el-option
                    v-for="dict in gxt_work_order_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维保中心"><el-input v-model="acceptWorkForm.gxtCenter" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="场站"><el-input v-model="acceptWorkForm.pcsStationName" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌"><el-input v-model="acceptWorkForm.brand" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="MIS工单编码"><el-input v-model="acceptWorkForm.misNo" disabled /></el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="维保内容" prop="content">
              <el-input v-model="acceptWorkForm.content" type="textarea" :rows="3" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="工作负责人" prop="teamLeaderId">
              <el-input
                  v-model="acceptWorkForm.teamLeaderName"
                  placeholder="请输入工作负责人姓名或点击选择"
                  clearable
                  @focus="handleTeamLeaderInputFocus"
                  @blur="handleTeamLeaderInputBlur"
                  @input="handleTeamLeaderInput"
                  @clear="handleTeamLeaderClear"
              >
              </el-input>
              <!-- 快速检索下拉框 -->
              <div class="quick-select-dropdown" v-show="showTeamLeaderQuickSelect && quickTeamLeaderList.length > 0">
                <div
                    v-for="item in quickTeamLeaderList"
                    :key="item.userId"
                    class="quick-select-item"
                    @click="handleTeamLeaderQuickSelect(item)">
                  <span class="user-name">{{ item.nickName }}</span>
                  <span class="user-dept">{{ item.dept?.deptName }}</span>
                </div>
              </div>
              <div class="quick-select-dropdown no-data" v-show="showTeamLeaderQuickSelect && quickTeamLeaderList.length === 0 && acceptWorkForm.teamLeaderName && !teamLeaderLoading">
                <div>未找到匹配的人员</div>
              </div>
              <div class="quick-select-dropdown no-data" v-show="showTeamLeaderQuickSelect && teamLeaderLoading">
                <div>
                  <i class="el-icon-loading"></i>
                  搜索中...
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="acceptWorkDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitAcceptWork">确认接单</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 结单对话框 (维修工单) -->
    <el-dialog title="结单" v-model="finalizeRepairDialogVisible" width="800px" append-to-body>
      <el-alert type="info" :closable="false" style="border-color: #14b8a6; background-color: #f0fdfa; color: #0d9488; height: 35px;">
        <template #default>
          <i class="fa fa-file-text-o mr-2" style="color: #0d9488;"> 请选择信息录入方式，并上传相关附件完成结单。</i>
        </template>
      </el-alert>
      <el-form ref="finalizeRepairFormRef" :model="finalizeRepairForm" :rules="finalizeRepairRules" label-width="120px" label-position="top">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工单编码"><el-input v-model="finalizeRepairForm.workOrderProjectNo" disabled /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="风机编号"><el-input v-model="finalizeRepairForm.pcsDeviceName" disabled /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单状态">
              <el-select v-model="finalizeRepairForm.workOrderStatus" style="width: 100%" disabled>
                <el-option
                    v-for="dict in gxt_work_order_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维保中心"><el-input v-model="finalizeRepairForm.gxtCenter" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="场站"><el-input v-model="finalizeRepairForm.pcsStationName" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌"><el-input v-model="finalizeRepairForm.brand" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="故障代码"><el-input v-model="finalizeRepairForm.faultCode" disabled /> </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="故障信息">
              <el-input
                v-model="finalizeRepairForm.faultBarcode"
                type="textarea"
                placeholder="请输入故障信息"
                maxlength="100"
                show-word-limit
                :rows="3"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下发人"><el-input v-model="finalizeRepairForm.assignUserName" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下发时间"><el-input v-model="finalizeRepairForm.assignTime" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="接单人"><el-input v-model="finalizeRepairForm.acceptUserName" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="接单时间"><el-input v-model="finalizeRepairForm.acceptTime" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作负责人"><el-input v-model="finalizeRepairForm.teamLeaderName" disabled /> </el-form-item>
          </el-col>
<!--          <el-col :span="12">-->
<!--            <el-form-item label="维修方式" prop="repairMethod">-->
<!--              <el-select-->
<!--                v-model="finalizeRepairForm.repairMethod"-->
<!--                placeholder="请选择维修方式"-->
<!--                style="width: 100%"-->
<!--                @change="handleRepairMethodChange"-->
<!--              >-->
<!--                <el-option-->
<!--                    v-for="dict in gxt_repair_method"-->
<!--                    :key="dict.value"-->
<!--                    :label="dict.label"-->
<!--                    :value="dict.value"-->
<!--                />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="信息录入" prop="infoEntry">
              <el-radio-group v-model="finalizeRepairForm.infoEntry" @change="handleInfoEntryChange">
                <el-radio
                    v-for="dict in gxt_info_entry"
                    :key="dict.value"
                    :label="dict.value"
                >
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <!-- 正常维修时显示的字段 -->
<!--          <template v-if="!finalizeRepairForm.repairMethod || finalizeRepairForm.repairMethod === '1'">-->
            <el-col :span="12" v-if="finalizeRepairForm.infoEntry == 1">
              <el-form-item label="MIS工单编码" prop="misOrderNo">
                <el-input
                  v-model="finalizeRepairForm.misOrderNo"
                  placeholder="请输入MIS工单编码或点击搜索选择"
                  clearable
                  @focus="handleMisNoInputFocus"
                  @blur="handleMisNoInputBlur"
                  @input="handleMisNoInput"
                  @clear="handleMisNoClear"
                >
                  <template #append>
                    <el-button @click="handleSelectMisInfo" icon="Search"></el-button>
                  </template>
                </el-input>
                <!-- 快速检索下拉框 -->
                <div class="quick-select-dropdown" v-show="showMisNoQuickSelect && quickMisNoList.length > 0">
                  <div
                      v-for="item in quickMisNoList"
                      :key="item.misNo"
                      class="quick-select-item"
                      @click="handleMisNoQuickSelect(item)">
                    <span class="mis-no">{{ item.misNo }}</span>
                  </div>
                </div>
                <div class="quick-select-dropdown no-data" v-show="showMisNoQuickSelect && quickMisNoList.length === 0 && finalizeRepairForm.misOrderNo && !misNoLoading">
                  <div>未找到匹配的MIS工单</div>
                </div>
                <div class="quick-select-dropdown no-data" v-show="showMisNoQuickSelect && misNoLoading">
                  <div>
                    <i class="el-icon-loading"></i>
                    搜索中...
                  </div>
                </div>
              </el-form-item>
            </el-col>

          <el-col :span="12" v-if="finalizeRepairForm.infoEntry == 2">
            <el-form-item label="工作票编号" prop="workPermitNum">
              <el-input v-model="workPermitNumProxy"   maxlength="20" show-word-limit  />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="realStartTime">
              <el-date-picker
                  v-model="finalizeRepairForm.realStartTime"
                  type="datetime"
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm"
                  placeholder="请选择开始时间"
                  style="width: 100%"
                  :readonly="finalizeRepairForm.infoEntry == 1"
                  :disabled-date="disabledStartDate"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作部位" prop="workArea">
              <el-select
                  v-model="finalizeRepairForm.workArea"
                  multiple
                  placeholder="请选择工作部位"
                  style="width: 100%"
              >
                <el-option
                    v-for="dict in gxt_work_area"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

<!--            <el-col :span="12">-->
<!--              <el-form-item label="开始时间" prop="realStartTime">-->
<!--                <el-date-picker-->
<!--                    v-model="finalizeRepairForm.realStartTime"-->
<!--                    type="datetime"-->
<!--                    format="YYYY-MM-DD HH:mm"-->
<!--                    value-format="YYYY-MM-DD HH:mm"-->
<!--                    placeholder="请选择开始时间"-->
<!--                    style="width: 100%"-->
<!--                    :disabled="getMisDataConfig === '1'"-->
<!--                    readonly-->
<!--                />-->
<!--              </el-form-item>-->
<!--            </el-col>-->
            <el-col :span="12">
              <el-form-item label="结束时间" prop="realEndTime">
                <el-date-picker
                    v-model="finalizeRepairForm.realEndTime"
                    type="datetime"
                    format="YYYY-MM-DD HH:mm"
                    value-format="YYYY-MM-DD HH:mm"
                    placeholder="请选择结束时间"
                    style="width: 100%"
                    :readonly="finalizeRepairForm.infoEntry == 1"
                    :disabled-date="disabledEndDate"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="检修人员" prop="workGroupMemberName">
                <el-input
                    v-model="finalizeRepairForm.workGroupMemberName"
                    placeholder="请输入检修人员"
                    maxlength="200"
                    show-word-limit
                    :readonly="finalizeRepairForm.infoEntry == 1"
                />
              </el-form-item>
            </el-col>
<!--          </template>-->

<!--          &lt;!&ndash; 复位启机时显示的字段 &ndash;&gt;-->
<!--          <template v-else-if="finalizeRepairForm.repairMethod === '2'">-->
<!--            <el-col :span="12">-->
<!--              <el-form-item label="复位方式" prop="resetMethod">-->
<!--                <el-select-->
<!--                  v-model="finalizeRepairForm.resetMethod"-->
<!--                  placeholder="请选择复位方式"-->
<!--                  style="width: 100%"-->
<!--                >-->
<!--                  <el-option-->
<!--                      v-for="dict in gxt_reset_method"-->
<!--                      :key="dict.value"-->
<!--                      :label="dict.label"-->
<!--                      :value="dict.value"-->
<!--                  />-->
<!--                </el-select>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
<!--          </template>-->

<!--          <el-col :span="24">-->
<!--            <el-form-item label="维修总结" prop="finalizationRemark">-->
<!--              <el-input-->
<!--                  v-model="finalizeRepairForm.finalizationRemark"-->
<!--                  type="textarea"-->
<!--                  placeholder="请输入维修总结"-->
<!--                  maxlength="500"-->
<!--                  show-word-limit-->
<!--                  :rows="3"-->
<!--              />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="24">
            <el-form-item label="真实故障原因" prop="realContent">
              <el-input v-model="finalizeRepairForm.realFailureReason"
                        type="textarea"
                        placeholder="请输入真实故障原因，最多500字"
                        maxlength="500"
                        :rows="5"
                        show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="附件（可选）">
              <preview :limit="8" v-model="finalizeRepairForm.attachmentUrls" :filesize="5"></preview>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="finalizeRepairDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitFinalizeRepair">确认结单</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 结单对话框 (维保工单) -->
    <el-dialog title="结单" v-model="finalizeWorkDialogVisible" width="800px" append-to-body>
      <el-alert type="info" :closable="false" style="border-color: #14b8a6; background-color: #f0fdfa; color: #0d9488; height: 35px;">
        <template #default>
          <i class="fa fa-file-text-o mr-2" style="color: #0d9488;"> 请上传相关附件完成结单。</i>
        </template>
      </el-alert>
      <el-form ref="finalizeWorkFormRef" :model="finalizeWorkForm" :rules="finalizeWorkRules" label-width="120px" label-position="top">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工单编码"><el-input v-model="finalizeWorkForm.workOrderProjectNo" disabled /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="风机编号"><el-input v-model="finalizeWorkForm.pcsDeviceName" disabled /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单状态">
              <el-select v-model="finalizeWorkForm.workOrderStatus" style="width: 100%" disabled>
                <el-option
                    v-for="dict in gxt_work_order_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维保中心"><el-input v-model="finalizeWorkForm.gxtCenter" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="场站"><el-input v-model="finalizeWorkForm.pcsStationName" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌"><el-input v-model="finalizeWorkForm.brand" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机型"><el-input v-model="finalizeWorkForm.model" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="MIS工单编码"><el-input v-model="finalizeWorkForm.misNo" disabled /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="接单人"><el-input v-model="finalizeWorkForm.acceptUserName" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="接单时间"><el-input v-model="finalizeWorkForm.acceptTime" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="realStartTime">
              <el-date-picker
                  v-model="finalizeWorkForm.realStartTime"
                  type="datetime"
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm"
                  placeholder="请选择开始时间"
                  style="width: 100%"
                  readonly
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="realEndTime">
              <el-date-picker
                  v-model="finalizeWorkForm.realEndTime"
                  type="datetime"
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm"
                  placeholder="请选择结束时间"
                  style="width: 100%"
                  readonly
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="维保内容" prop="content">
              <el-input v-model="finalizeWorkForm.content" type="textarea" :rows="3" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作负责人">
              <el-input v-model="finalizeWorkForm.teamLeaderName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="检修人员">
              <el-input v-model="finalizeWorkForm.workGroupMemberName" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="附件（可选）">
              <preview :limit="8" v-model="finalizeWorkForm.attachmentUrls" :filesize="5"></preview>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="finalizeWorkDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitFinalizeWork">确认结单</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审批对话框 (维修工单) -->
    <ApproveRepairDialog
        v-model="approveRepairDialogVisible"
        :data="approveRepairForm"
        :work-order-status-options="gxt_work_order_status"
        :suspend-reason-options="gxt_order_suspend_reason"
        :on-submit="submitApproveFromParent"
        @success="handleApproveSuccess"
    />

    <!-- 维保审批对话框组件 -->
    <ApproveDialog
        v-model="approveWorkDialogVisible"
        :data="approveWorkForm"
        :work-order-status-options="gxt_work_order_status"
        :suspend-reason-options="gxt_order_suspend_reason"
        :on-submit="submitApproveFromParent"
        @success="handleApproveSuccess"
    />

    <!-- 复运对话框 (维修工单) -->
    <el-dialog title="复运" v-model="restartRepairDialogVisible" width="800px" append-to-body>
      <el-alert type="info" :closable="false" style="border-color: #0ea5e9; background-color: #ecf7ff; color: #0369a1; height: 35px;">
        <template #default>
          <i class="fa fa-refresh mr-2" style="color: #0369a1;"> 请填写复运相关信息，完成工单复运。</i>
        </template>
      </el-alert>
      <h4 class="text-sm font-medium text-gray-800 mb-3"></h4>
      <el-form ref="restartRepairFormRef" :model="restartRepairForm" :rules="restartRepairRules" label-width="120px" label-position="top">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工单编码"><el-input v-model="restartRepairForm.workOrderProjectNo" disabled /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="风机编号"><el-input v-model="restartRepairForm.pcsDeviceName" disabled /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维保中心"><el-input v-model="restartRepairForm.gxtCenter" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="场站"><el-input v-model="restartRepairForm.pcsStationName" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌"><el-input v-model="restartRepairForm.brand" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发生时间"><el-input v-model="restartRepairForm.occurTime" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="MIS工单编码"><el-input v-model="restartRepairForm.misOrderNo" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="恢复运行时间" prop="restartTime">
              <el-date-picker
                  v-model="restartRepairForm.restartTime"
                  type="datetime"
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm"
                  placeholder="请选择恢复运行时间"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="损失电量（kWh）" prop="lostPower">
              <el-input-number
                  v-model="restartRepairForm.lostPower"
                  controls-position="right"
                  style="width: 100%"
                  class="input-number-left"
                  :min="0"
                  placeholder="请输入损失电量"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="restartRepairDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitRestartRepair">确认复运</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 复运对话框 (维保工单) -->
    <el-dialog title="复运" v-model="restartWorkDialogVisible" width="800px" append-to-body>
      <el-alert type="info" :closable="false" style="border-color: #0ea5e9; background-color: #ecf7ff; color: #0369a1; height: 35px;">
        <template #default>
          <i class="fa fa-refresh mr-2" style="color: #0369a1;"> 请填写复运相关信息，完成工单复运。</i>
        </template>
      </el-alert>
      <h4 class="text-sm font-medium text-gray-800 mb-3"></h4>
      <el-form ref="restartWorkFormRef" :model="restartWorkForm" :rules="restartWorkRules" label-width="120px" label-position="top">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工单编码"><el-input v-model="restartWorkForm.workOrderProjectNo" disabled /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="风机编号"><el-input v-model="restartWorkForm.pcsDeviceName" disabled /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维保中心"><el-input v-model="restartWorkForm.gxtCenter" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="场站"><el-input v-model="restartWorkForm.pcsStationName" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌"><el-input v-model="restartWorkForm.brand" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机型"><el-input v-model="restartWorkForm.model" disabled /> </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="MIS工单编码"><el-input v-model="restartWorkForm.misNo" disabled /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="恢复运行时间" prop="restartTime">
              <el-date-picker
                  v-model="restartWorkForm.restartTime"
                  type="datetime"
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm"
                  placeholder="请选择恢复运行时间"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="损失电量（kWh）" prop="lostPower">
              <el-input-number
                  v-model="restartWorkForm.lostPower"
                  controls-position="right"
                  style="width: 100%"
                  class="input-number-left"
                  :min="0"
                  placeholder="请输入损失电量"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="restartWorkDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitRestartWork">确认复运</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 维修工单下发对话框 -->
    <el-dialog title="下发" v-model="assignRepairDialogVisible" width="800px" append-to-body >
      <el-form ref="repairOrderRef" :model="assignRepairForm" :rules="assignRepairRules" label-width="120px" label-position="top">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工单编码" prop="workOrderProjectNo" >
              <el-input v-model="assignRepairForm.workOrderProjectNo" placeholder="请输入工单编码" disabled readonly maxlength="50" show-word-limit v-chinese-limit/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="风机编号" prop="pcsDeviceName">
              <el-input v-model="assignRepairForm.pcsDeviceName" placeholder="请选择风机编号" readonly>
                <template #append>
                  <el-button @click="handleSelectEquipment" icon="Search"></el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="维保中心" prop="gxtCenter">
              <el-input v-model="assignRepairForm.gxtCenter" placeholder="请选择风机编号自动填充" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="场站" prop="pcsStationName">
              <el-input v-model="assignRepairForm.pcsStationName" placeholder="请选择风机编号自动填充" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="assignRepairForm.brand" placeholder="请选择风机编号自动填充" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机型" prop="model">
              <el-input v-model="assignRepairForm.model" placeholder="请选择风机编号自动填充" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发生时间" prop="occurTime">
              <el-date-picker
                  v-model="assignRepairForm.occurTime"
                  type="datetime"
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm"
                  placeholder="请选择发生时间"
                  style="width: 100%"
                  :disabled-date="disabledDate"
                  :disabled-time="disabledTime"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="故障代码" prop="faultCode">
              <el-input
                  v-model="assignRepairForm.faultCode"
                  placeholder="请输入故障代码"
                  maxlength="20"
                  show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="故障信息" prop="faultBarcode">
              <el-input
                  v-model="assignRepairForm.faultBarcode"
                  type="textarea"
                  placeholder="请输入故障信息"
                  maxlength="100"
                  show-word-limit
                  :rows="3"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="assignRepairDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitFormAndIssue">确认下发</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 维保工单下发对话框 -->
    <el-dialog title="下发" v-model="assignWorkDialogVisible" width="800px" append-to-body>
      <div style="max-height: 500px; overflow-y: auto; padding-right: 10px;">
        <el-form ref="workOrderRef" :model="assignWorkForm" :rules="assignWorkRules" label-width="120px" label-position="top">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="工单编码" prop="workOrderProjectNo">
                <el-input v-model="assignWorkForm.workOrderProjectNo" maxlength="50" show-word-limit v-chinese-limit readonly/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="风机编号" prop="pcsDeviceName">
                <el-input v-model="assignWorkForm.pcsDeviceName" readonly>
                  <template #append>
                    <el-button @click="handleSelectEquipment" icon="Search"></el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="维保中心" prop="gxtCenter">
                <el-input v-model="assignWorkForm.gxtCenter" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="场站" prop="pcsStationName">
                <el-input v-model="assignWorkForm.pcsStationName" readonly />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="品牌" prop="brand">
                <el-input v-model="assignWorkForm.brand" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="机型" prop="model">
                <el-input v-model="assignWorkForm.model" readonly />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="MIS工单编码" prop="misNo">
                <el-input v-model="assignWorkForm.misNo"
                          placeholder="请输入MIS工单编码或点击搜索选择"
                          clearable
                          @focus="handleMisNoInputFocus"
                          @blur="handleMisNoInputBlur"
                          @input="handleMisNoInput"
                          @clear="handleMisNoClear"
                >
                  <template #append>
                    <el-button @click="handleSelectMisInfo" icon="Search"></el-button>
                  </template>
                </el-input>
                <!-- 快速检索下拉框 -->
                <div class="quick-select-dropdown" v-show="showMisNoQuickSelect && quickMisNoList.length > 0">
                  <div
                      v-for="item in quickMisNoList"
                      :key="item.misNo"
                      class="quick-select-item"
                      @click="handleMisNoQuickSelect(item)">
                    <span class="mis-no">{{ item.misNo }}</span>
                  </div>
                </div>
                <div class="quick-select-dropdown no-data" v-show="showMisNoQuickSelect && quickMisNoList.length === 0 && assignWorkForm.misNo && !misNoLoading">
                  <div>未找到匹配的MIS工单</div>
                </div>
                <div class="quick-select-dropdown no-data" v-show="showMisNoQuickSelect && misNoLoading">
                  <div>
                    <i class="el-icon-loading"></i>
                    搜索中...
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="维保内容" prop="content">
                <el-input v-model="assignWorkForm.content" type="textarea" :rows="3" readonly />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="assignWorkDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitWorkFormAndIssue">确认下发</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- MIS选择组件 -->
    <MisInfoSelectSingle :key="commonKey" v-model="misInfoSelectVisible" @onSelected="onMisInfoSelected" :pcsStationName="finalizeFormData.pcsStationName || assignWorkForm.pcsStationName" :pcsDeviceName="finalizeFormData.pcsDeviceName || assignWorkForm.pcsDeviceName"></MisInfoSelectSingle>

    <!-- 设备选择组件 -->
    <equipment-select-single v-model="equipmentSelectVisible" @onSelected="onEquipmentSelected"></equipment-select-single>

    <!-- 复启对话框组件 -->
    <ResetDialog
      v-model="resetDialogVisible"
      :data="resetFormData"
      :reset-method-options="gxt_reset_method"
      :on-submit="submitResetFromParent"
      @success="handleResetSuccess"
    />

    <!-- 维修结单对话框组件 -->
    <FinalizeDialog
        v-model="finalizeDialogVisible"
        :data="finalizeFormData"
        :work-order-status-options="gxt_work_order_status"
        :info-entry-options="gxt_info_entry"
        :work-area-options="gxt_work_area"
        :on-submit="submitFinalizeFromParent"
        :list-repair-order="listRepairOrder"
        :list-work-person="listWorkPerson"
        :list-mis-info="listMisInfo"
        :list-user-data="listUserData"
        @success="handleFinalizeSuccess"
        @select-mis-info="handleSelectMisInfo"
    >
<!--      <template #mis-info-select>-->
<!--        <MisInfoSelectSingle :key="commonKey" v-model="misInfoSelectVisible" @onSelected="onMisInfoSelected" :pcsStationName="finalizeFormData.pcsStationName" :pcsDeviceName="finalizeFormData.pcsDeviceName"></MisInfoSelectSingle>-->
<!--      </template>-->
    </FinalizeDialog>

    <!-- 退回对话框 -->
    <ReturnDialog
        v-model="returnDialogVisible"
        :data="returnForm"
        :work-order-status-options="gxt_work_order_status"
        :return-type-options="returnForm.workOrderStatus == 'assigned' ? gxt_accept_return_reason : gxt_return_type "
        :on-submit="submitReturnFromParent"
        @success="handleReturnSuccess"
    />

    <!-- 维保结单对话框组件 -->
    <FinishDialog
        v-model="finishDialogVisible"
        :data="finishForm"
        :work-order-status-options="gxt_work_order_status"
        :info-entry-options="gxt_info_entry"
        :list-gxt-order="listGxtOrder"
        :list-work-person="listWorkPerson"
        :list-mis-info="listMisInfo"
        :list-user-data="listUserData"
        :on-submit="submitFinishFromParent"
        @success="handleFinishSuccess"
    />

    <!-- 维修挂起对话框 -->
    <SuspendDialog
        v-model="suspendRepairDialogVisible"
        :data="suspendForm"
        :suspend-reason-options="gxt_order_suspend_reason"
        :on-submit="submitSuspendFromParent"
        @success="handleSuspendSuccess"
    />

    <!-- 维保挂起对话框 -->
    <SuspendWorkDialog
        v-model="suspendDialogVisible"
        :data="suspendForm"
        :suspend-reason-options="gxt_order_suspend_reason"
        :on-submit="submitSuspendFromParent"
        @success="handleSuspendSuccess"
    />
  </div>
</template>

<script setup>
import { getCurrentInstance, reactive, ref, toRefs, onMounted } from "vue";
import {
  getOrderInfo,
  listMyTodo,
  // 使用现有的API接口
  acceptRepairOrder,
  acceptWorkOrder,
  // finalizeRepairOrder,
  finalizeWorkOrder,
  approveRepairOrder,
  restartRepairOrder,
  restartWorkOrder,
  listMyRate,
} from "@/api/gxt/orderMine.js";
import {listUserNoPermi, listLeader, listUserData} from "@/api/system/user.js";
import { listEquipment,listMaintenanceCenters, listStationsByMaintenanceCenter } from "@/api/gxt/equipment.js";
import { listMisInfo, listWorkPerson } from "@/api/gxt/misInfo.js";
import preview from '@/components/FileUpload/preview.vue'
import MisInfoSelectSingle from "@/components/misInfoSelect/single.vue";
import useUserStore from '@/store/modules/user'
import {
  listRepairOrder,updateRepairOrder,finalizeRepairOrder,getRepairOrder,returnRepairOrder,suspendRepairOrder, approveSuspendRepairOrder
} from "@/api/gxt/repairOrder";
import ResetDialog from '@/components/repairOrder/reset.vue'
import {
  listGxtOrder,
  updateGxtOrder,
  completeWorkOrder,
  getGxtOrder,
  suspendWorkOrder,
  approveWorkOrder
} from "@/api/gxt/gxtOrder"
import EquipmentSelectSingle from "@/components/equipmentSelect/single.vue"
import FinalizeDialog from "@/components/repairOrder/finalize.vue";
import ReturnDialog from "@/components/repairOrder/return.vue";
import FinishDialog from "@/components/gxtOrder/finalize.vue";
import SuspendDialog from "@/components/repairOrder/suspend.vue";
import SuspendWorkDialog from "@/components/gxtOrder/suspend.vue";
import ViewDialog from "@/components/repairOrder/view.vue";
import ViewWorkOrderDialog from "@/components/gxtOrder/view.vue";
import ApproveRepairDialog from "@/components/repairOrder/approve.vue";
import ApproveDialog from "@/components/gxtOrder/approve.vue";


const { proxy } = getCurrentInstance();
const userStore = useUserStore();

// 显示搜索栏
const showSearch = ref(true);

// 加载状态
const loading = ref(false);

// 表格高度
const tableHeight = ref(window.innerHeight - 300);

// 数据总数
const total = ref(0);

// 维修工单详情对话框可见性
const repairDetailDialogVisible = ref(false);

// 维保工单详情对话框可见性
const workDetailDialogVisible = ref(false);

// 接单对话框可见性
const acceptRepairDialogVisible = ref(false);
const acceptWorkDialogVisible = ref(false);

// 结单对话框可见性
const finalizeRepairDialogVisible = ref(false);
const finalizeWorkDialogVisible = ref(false);
// 维修结单组件对话框可见性
const finalizeDialogVisible = ref(false)
// 维保结单组件对话框可见性
const finishDialogVisible = ref(false)

// 审批对话框可见性
const approveRepairDialogVisible = ref(false);
const approveWorkDialogVisible = ref(false);

// 复运对话框可见性
const restartRepairDialogVisible = ref(false);
const restartWorkDialogVisible = ref(false);

// 复启对话框可见性
const resetDialogVisible = ref(false);

// 下发对话框可见性
const assignRepairDialogVisible = ref(false);
const assignWorkDialogVisible = ref(false);

// 退回
const returnDialogVisible = ref(false)

// 维修挂起
const suspendRepairDialogVisible = ref(false)
// 维保挂起
const suspendDialogVisible = ref(false)

// 维保中心选项
const maintenanceCenterOptions = ref([]);

// 场站选项
const stationOptions = ref([]);

// 工单列表
const orderList = ref([]);

// 详情数据
const detailData = ref({});

// 工单流转记录
const flowList = ref([]);

// 接单表单数据
const acceptRepairForm = ref({});
const acceptWorkForm = ref({});

// 结单表单数据
const finalizeRepairForm = ref({workArea: []});
const finalizeWorkForm = ref({});

// 维保结单表单数据
const finishForm = ref({})

// 控制结单表单中字段是否可编辑
const getMisDataConfig = ref("0"); // 默认值为"0"，表示可以手动输入

// 审批表单数据
const approveRepairForm = ref({});
const approveWorkForm = ref({});

// 复运表单数据
const restartRepairForm = ref({});
const restartWorkForm = ref({});

// 复启表单数据
const resetFormData = ref({});

// 下发表单数据
const assignRepairForm = ref({});
const assignWorkForm = ref({});

// 退回表单
const returnForm = ref({})

// 挂起表单
const suspendForm = ref({})

// 工作负责人快速检索相关响应式数据
const showTeamLeaderQuickSelect = ref(false);
const quickTeamLeaderList = ref([]);
const teamLeaderLoading = ref(false);
const teamLeaderSearchTimer = ref(null);
const allUserList = ref([]); // 存储所有用户数据用于快速检索
const lastLoadedCenterId = ref(null); // Track last loaded maintenance center ID

// MIS工单快速检索相关响应式数据
const showMisNoQuickSelect = ref(false);
const quickMisNoList = ref([]);
const allMisNoList = ref([]); // 存储所有MIS工单数据用于快速检索
const misNoLoading = ref(false);
const misNoSearchTimer = ref(null);
const misInfoSelectVisible = ref(false);
const equipmentSelectVisible = ref(false)

let commonKey = 0;

// 查询参数
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    workOrderProjectNo: undefined,
    workOrderStatus: undefined,
    gxtCenter: undefined,
    pcsStationName: undefined,
    pcsDeviceName: undefined
  }
});

const { queryParams } = toRefs(data);

// 获取字典数据
const {
  gxt_maintenance_type,
  gxt_work_order_status,
  gxt_order_priority_type,
  gxt_repair_order_flow_action_type,
  gxt_order_suspend_reason,
  gxt_inspection_type,
  gxt_pause_reasons,
  gxt_repair_method,
  gxt_reset_method,
  gxt_info_entry,
  gxt_work_area,
  gxt_return_type,
  gxt_accept_return_reason
} = proxy.useDict(
  "gxt_maintenance_type",
  "gxt_work_order_status",
  "gxt_order_priority_type",
  "gxt_repair_order_flow_action_type",
  "gxt_order_suspend_reason",
  "gxt_inspection_type",
  "gxt_pause_reasons",
  "gxt_repair_method",
  "gxt_reset_method",
  "gxt_info_entry",
  "gxt_work_area",
    "gxt_return_type",
    "gxt_accept_return_reason"
);

// 表单验证规则
const acceptRepairRules = ref({
  teamLeaderId: [{ required: true, message: "请选择工作负责人", trigger: "change" }]
});

const acceptWorkRules = ref({
  teamLeaderId: [{ required: true, message: "请选择工作负责人", trigger: "change" }]
});

const finalizeRepairRules = ref({
  misOrderNo: [
    { required: true, message: "MIS工单编码不能为空", trigger: "blur" }
  ],
  realStartTime: [
    { required: true, message: "请选择开始时间", trigger: "change" },
    {
      validator: (rule, value, callback) => {
        if (value && new Date(value) > new Date() && finalizeRepairForm.value.infoEntry ==  '2') {
          callback(new Error('开始时间不能大于当前时间'));
        } else if(value && new Date(value) < new Date(finalizeRepairForm.value.acceptTime) && finalizeRepairForm.value.infoEntry ==  '2') {
          callback(new Error('开始时间不能小于接单时间'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ],
  realEndTime: [
    { required: true, message: "请选择结束时间", trigger: "change" },
    {
      validator: (rule, value, callback) => {
        if (value && new Date(value) > new Date() && finalizeRepairForm.value.infoEntry ==  '2') {
          callback(new Error('结束时间不能大于当前时间'));
        } else if(value && new Date(value) < new Date(finalizeRepairForm.value.realStartTime) && finalizeRepairForm.value.infoEntry ==  '2') {
          callback(new Error('结束时间不能小于开始时间'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ],
  workGroupMemberName: [
    { required: false, message: "请输入检修人员", trigger: "blur" },
    {
      validator: async (rule, value, callback) => {
        // 如果值为空、关联MIS，直接通过验证
        if (!value || finalizeRepairForm.value.infoEntry ==  '1') {
          return callback();
        }
        try {
          // 将输入的检修人员姓名按逗号分割
          const names = value.split(',').map(name => name.trim());

          // 验证每个检修人员是否存在于组织架构中
          for (const name of names) {
            debugger
            if (name.length > 0) {
              const response = await listUserData({nickName: name});
              if (!response.rows || response.rows.length === 0) {
                return callback(new Error(`检修人员"${name}"非系统内人员，请重新输入`));
              }
            } else {
              return callback(new Error(`请正确输入检修人员名单`));
            }
          }
          callback();
        } catch (error) {
          callback(new Error('验证检修人员时发生错误'));
        }
      },
      trigger: 'blur'
    }
  ],
  workArea: [
    { required: true, message: "请选择工作部位", trigger: "change" }
  ],
  workPermitNum: [
    { required: true, message: "工作票编号不能为空", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (finalizeRepairForm.value.infoEntry == '2') {
          if (!value) {
            callback(new Error('工作票编号不能为空'))
          } else if (!/^[a-zA-Z0-9_\-\.]*$/.test(value)) {
            callback(new Error('仅支持英文、数字、下划线'))
          } else if (value.length > 20) {
            callback(new Error('不能超过20个字符'))
          } else {
            // 验证唯一性
            if (value) {
              listRepairOrder({pageNum: 1, pageSize: 10, workPermitNum: value}).then(response => {
                const gxtOrders = response.rows
                if (gxtOrders.length > 0) {
                  if (gxtOrders[0].id != finalizeRepairForm.value.id) {
                    callback(new Error('工作票编号已存在！'))
                  } else {
                    callback()
                  }
                } else {
                  callback()
                }
              })
            } else {
              callback()
            }
          }
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
});

const finalizeWorkRules = ref({
  realContent: [
    { required: true, message: "请输入实际维保内容", trigger: "blur" }
  ]
});

const approveRepairRules = ref({
  /*rejectionReason: [
    { required: true, message: "请输入审批意见", trigger: "blur" }
  ]*/
});

const approveWorkRules = ref({
  rejectionReason: [
    { required: true, message: "请输入审批意见", trigger: "blur" }
  ]
});

// 复运表单验证规则
const restartRepairRules = ref({
  lostPower: [
    { required: true, message: "损失电量不能为空", trigger: "change" }
  ],
  restartTime: [
    { required: true, message: "请选择恢复运行时间", trigger: "change" },
    {
      validator: (rule, value, callback) => {
        if (value && new Date(value) > new Date()) {
          callback(new Error('恢复运行时间不能大于当前时间'));
        // } else if(value && new Date(value) < new Date(restartRepairForm.value.realEndTime)) {
        //   callback(new Error('恢复运行时间不能小于结束时间'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ]
});

const restartWorkRules = ref({
  lostPower: [
    { required: true, message: "损失电量不能为空", trigger: "change" }
  ],
  restartTime: [
    { required: true, message: "请选择恢复运行时间", trigger: "change" },
    {
      validator: (rule, value, callback) => {
        if (value && new Date(value) > new Date()) {
          callback(new Error('恢复运行时间不能大于当前时间'));
        // } else if(value && new Date(value) < new Date(restartWorkForm.value.realEndTime)) {
        //   callback(new Error('恢复运行时间不能小于结束时间'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ]
});

const assignRepairRules = ref({
  workOrderProjectNo: [
    { required: true, message: "工单编码不能为空", trigger: "blur" }
  ],
  pcsDeviceName: [
    { required: true, message: "风机编号不能为空", trigger: "blur" }
  ],
  occurTime: [
    { required: true, message: "请选择发生时间", trigger: "change" },
    {
      validator: (rule, value, callback) => {
        if (value && new Date(value) > new Date()) {
          callback(new Error('发生时间不能大于当前时间'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ],
  faultBarcode: [
    { required: true, message: "故障信息不能为空", trigger: "blur" }
  ],
});

const assignWorkRules = ref({
  workOrderProjectNo: [{ required: true, message: "工单编码不能为空", trigger: "blur" }],
  misNo: [{ required: true, message: "MIS编码不能为空", trigger: "blur" }],
  pcsDeviceName: [{ required: true, message: "风机编号不能为空", trigger: "blur" }],
  gxtCenter: [{ required: true, message: "维保中心不能为空", trigger: "blur" }],
  pcsStationName: [{ required: true, message: "风电场不能为空", trigger: "blur" }]
});

// 页面加载时执行
onMounted(() => {
  getList();
  getMaintenanceCenterAndStationList();
  window.addEventListener('resize', handleResize);
});

// 获取列表数据
function getList() {
  loading.value = true;
  listMyTodo(queryParams.value).then(response => {
    debugger
    orderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 获取维保中心和场站列表
function getMaintenanceCenterAndStationList() {
  listMaintenanceCenters().then(response => {
    maintenanceCenterOptions.value = response.data.map(item => {
      return { deptName: item, deptId: item };
    });

    // 如果已选择维保中心，则筛选出该维保中心下的场站
    if (queryParams.value.gxtCenter) {
      listStationsByMaintenanceCenter(queryParams.value.gxtCenter).then(res => {
        stationOptions.value = res.data.map(item => {
          return { deptName: item, deptId: item };
        });
      });
    } else {
      // 如果未选择维保中心，则清空场站选项
      stationOptions.value = [];
    }
  });
}

// 处理维保中心变更
function handleMaintenanceCenterChange(selectedCenter) {
  // 清空场站选择
  queryParams.value.pcsStationName = null;

  // 如果选择了维保中心，则加载对应的场站
  if (selectedCenter) {
    listStationsByMaintenanceCenter(selectedCenter).then(response => {
      stationOptions.value = response.data.map(item => {
        return { deptName: item, deptId: item };
      });
    });
  } else {
    // 如果未选择维保中心，则清空场站选项
    stationOptions.value = [];
  }
}

// 搜索按钮操作
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

// 重置按钮操作
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 查看详情
function handleView(row) {
  // 调用后端接口获取详细信息
  getOrderInfo(row.orderType, row.id).then(response => {
    detailData.value = response.data;
    // 从工单详情中获取流转记录
    flowList.value = response.data.workOrderFlowList || response.data.repairOrderFlowList || [];

    if (row.orderType === 1) {
      // 维修工单
      repairDetailDialogVisible.value = true;
    } else {
      // 维保工单
      workDetailDialogVisible.value = true;
    }
  }).catch(error => {
    proxy.$modal.msgError("获取工单详情失败：" + error.message);
  });
}

// 处理窗口大小变化
function handleResize() {
  tableHeight.value = window.innerHeight - 300;
}

// 处理接单
function handleAccept(row) {
  getOrderInfo(row.orderType, row.id).then(response => {
    if (row.orderType === 1) {
      // 维修工单
      acceptRepairForm.value = { ...response.data, selectedMembers: [] };
      // 获取场站ID用于查询用户
      acceptRepairForm.value.pcsStationId = response.data.pcsStationId;
      acceptRepairForm.value.pcsStationPid = response.data.pcsStationPid;
      if (lastLoadedCenterId.value !== acceptRepairForm.value.gxtCenterId) {
        allUserList.value = [];
      }

      // 预加载工作负责人列表
      loadQuickTeamLeaderList();
      acceptRepairDialogVisible.value = true;
    } else {
      // 维保工单
      acceptWorkForm.value = response.data;
      acceptWorkForm.value.orderId = row.id;
      acceptWorkForm.value.teamLeaderId = undefined;
      acceptWorkForm.value.teamLeaderName = undefined;
      if (row.gxtCenterId) {
        if (lastLoadedCenterId.value !== acceptWorkForm.value.gxtCenterId) {
          allUserList.value = [];
        }

        // 预加载工作负责人列表
        loadQuickTeamLeaderList();
        acceptWorkDialogVisible.value = true;
      } else {
        proxy.$modal.msgWarning("未找到有效的部门信息，无法加载用户列表");
        acceptWorkDialogVisible.value = true;
      }
    }
  });
}

// 提交维修工单接单
function submitAcceptRepair() {
  proxy.$refs["acceptRepairFormRef"].validate(valid => {
    if (valid) {
      // 更新检修人员列表
      //handleMembersChange('acceptForm');
      acceptRepairOrder(acceptRepairForm.value).then(response => {
        proxy.$modal.msgSuccess("接单成功");
        acceptRepairDialogVisible.value = false;
        getList();
      }).catch(error => {
        proxy.$modal.msgError("接单失败: " + error.message);
      });
    }
  });
}

// 提交维保工单接单
function submitAcceptWork() {
  proxy.$refs["acceptWorkFormRef"].validate(valid => {
    if (valid) {
      // 组合acceptForm中的信息，构建完整的GxtWorkOrder对象流转给后端
      const data = {
        id: acceptWorkForm.value.orderId,
        workOrderProjectNo: acceptWorkForm.value.workOrderProjectNo,
        acceptUserId: acceptWorkForm.value.teamLeaderId,
        acceptUserName: acceptWorkForm.value.teamLeaderName,
        teamLeaderId: acceptWorkForm.value.teamLeaderId,
        teamLeaderName: acceptWorkForm.value.teamLeaderName,
        content: acceptWorkForm.value.content,
        workOrderStatus: 'to_finish'
      };

      acceptWorkOrder(data).then(response => {
        proxy.$modal.msgSuccess("接单成功");
        acceptWorkDialogVisible.value = false;
        getList();
      }).catch(error => {
        proxy.$modal.msgError("接单失败: " + error.message);
      });
    }
  });
}

// 处理结单
function handleFinalize(row) {
  getOrderInfo(row.orderType, row.id).then(response => {
    if (row.orderType === 1) {
      // 维修工单
      finalizeRepairForm.value = { ...response.data, selectedMembers: [] };
      // 设置默认维修方式为正常维修(1)
      if (!finalizeRepairForm.value.repairMethod) {
        finalizeRepairForm.value.repairMethod = '1';
        finalizeRepairForm.value.infoEntry = '1'
      }
      finalizeRepairDialogVisible.value = true;
      commonKey++; // 更新key以强制刷新组件
    } else {
      // 维保工单
      finalizeWorkForm.value = response.data;
      if (finalizeWorkForm.value.misNo != null) {
        listMisInfo({misNo: finalizeWorkForm.value.misNo}).then(response => {
          const misInfo = response.rows
          if (misInfo.length > 0) {
            finalizeWorkForm.value.realStartTime = misInfo[0].realStartTime
            finalizeWorkForm.value.realEndTime = misInfo[0].realEndTime
          }
        })

        listWorkPerson({misNo: finalizeWorkForm.value.misNo }).then(response => {
          finalizeWorkForm.value.workOrderPersonList = response.rows;
          if (finalizeWorkForm.value.workOrderPersonList) {
            const nickNames = finalizeWorkForm.value.workOrderPersonList
                .map(person => person.nickName)
                .join(',');
            finalizeWorkForm.value.workGroupMemberName = nickNames
          }
        })
      }
      // 打开对话框后重置表单验证错误
      proxy.$nextTick(() => {
        proxy.$refs["finalizeWorkFormRef"]?.clearValidate()
      })
      finalizeWorkDialogVisible.value = true;
    }
  });
}

// 提交维修工单结单
function submitFinalizeRepair() {
  proxy.$refs["finalizeRepairFormRef"].validate(valid => {
    if (valid) {
      // 根据维修方式执行不同的验证逻辑
      if (finalizeRepairForm.value.repairMethod === '1') {
        // 正常维修需要验证MIS相关字段
        if (!finalizeRepairForm.value.realEndTime) {
          proxy.$modal.msgError("该工单未结束，无法结单！");
          return;
        }
      }

      const data = finalizeRepairForm.value;
      // 根据维修方式清除不需要的字段
      if (data.repairMethod === '1') {
        // 正常维修时清除复位方式
        data.resetMethod = undefined;
      } else if (data.repairMethod === '2') {
        // 复位启机时清除MIS相关字段
        data.misOrderNo = undefined;
        data.realStartTime = undefined;
        data.realEndTime = undefined;
        data.workGroupMemberName = undefined;
        data.repairOrderPersonList = [];
      }

      finalizeRepairOrder(data).then(response => {
        proxy.$modal.msgSuccess("结单成功");
        finalizeRepairDialogVisible.value = false;
        getList();
      }).catch(error => {
        proxy.$modal.msgError("结单失败: " + error.message);
      });
    }
  });
}

// 提交维保工单结单
function submitFinalizeWork() {
  proxy.$refs["finalizeWorkFormRef"].validate(valid => {
    if (valid) {
      if (!finalizeWorkForm.value.realEndTime) {
        proxy.$modal.msgError("该工单未结束，无法结单！");
        return;
      }
      finalizeWorkForm.value.workOrderStatus = 'completed'
      finalizeWorkOrder(finalizeWorkForm.value).then(response => {
        proxy.$modal.msgSuccess("结单成功");
        finalizeWorkDialogVisible.value = false;
        // 清空附件列表
        finalizeWorkForm.value.attachmentUrls = undefined
        getList();
      }).catch(error => {
        proxy.$modal.msgError("结单失败: " + error.message);
      });
    }
  });
}

// 处理审批
function handleApprove(row) {
  getOrderInfo(row.orderType, row.id).then(response => {
    debugger
    if (row.orderType === 1) {
      // 维修工单
      approveRepairForm.value = response.data;
      approveRepairForm.value.rejectionReason = ""; // 清空审批意见
      approveRepairDialogVisible.value = true;
    } else {
      // 维保工单
      approveWorkForm.value = response.data;
      approveWorkForm.value.rejectionReason = ""; // 清空审批意见
      approveWorkDialogVisible.value = true;
    }
  });
}

// 提交维修工单审批
function submitApproveRepair(approvalStatusValue) {
  proxy.$refs["approveRepairFormRef"].validate(valid => {
    if (valid) {
      approveRepairForm.value.approvalStatus = approvalStatusValue
      if (approveRepairForm.value.approvalStatus === 'rejected' && !approveRepairForm.value.rejectionReason) {
        proxy.$modal.msgError("驳回时审批意见不能为空");
        return;
      }
      approveRepairOrder(approveRepairForm.value).then(response => {
        if (approvalStatusValue === "approved") {
          proxy.$modal.msgSuccess("审批通过成功");
        } else {
          proxy.$modal.msgSuccess("审批驳回成功");
        }
        approveRepairDialogVisible.value = false;
        getList();
      }).catch(error => {
        proxy.$modal.msgError("审批失败: " + error.message);
      });
    }
  });
}

// 提交维保工单审批
function submitApproveWork(approvalStatusValue) {
  approveWorkForm.value.workOrderStatus = approvalStatusValue
  proxy.$refs["approveWorkFormRef"].validate(valid => {
    if (valid) {
      approveWorkOrder(approveWorkForm.value).then(response => {
        const msg = approveWorkForm.value.workOrderStatus === 'suspended' ? '挂起审批通过' : '挂起审批驳回'
        proxy.$modal.msgSuccess(msg + "成功")
        approveWorkDialogVisible.value = false;
        getList();
      }).catch(error => {
        proxy.$modal.msgError("审批失败: " + error.message);
      });
    }
  });
}

/** 工作负责人输入框获取焦点 */
const handleTeamLeaderInputFocus = () => {
  showTeamLeaderQuickSelect.value = true;
  // 如果已有输入内容，立即搜索
  if ((acceptRepairForm.value && acceptRepairForm.value.teamLeaderName && acceptRepairForm.value.teamLeaderName.trim()) ||
      (acceptWorkForm.value && acceptWorkForm.value.teamLeaderName && acceptWorkForm.value.teamLeaderName.trim())) {
    const currentForm = acceptRepairDialogVisible.value ? acceptRepairForm.value : acceptWorkForm.value;
    handleTeamLeaderInput(currentForm.teamLeaderName);
  } else {
    // 如果没有输入内容，加载默认列表
    loadQuickTeamLeaderList();
  }
}

// 工作负责人输入框失去焦点
const handleTeamLeaderInputBlur = () => {
  // 延迟隐藏下拉框，确保点击选项能触发
  setTimeout(() => {
    showTeamLeaderQuickSelect.value = false;
  }, 200);
}





// 工作负责人输入事件 - 实时搜索
const handleTeamLeaderInput = (value) => {
  const searchText = value.trim();

  if (!searchText) {
    quickTeamLeaderList.value = [];
    showTeamLeaderQuickSelect.value = false;
    return;
  }

  showTeamLeaderQuickSelect.value = true;

  // 清除之前的定时器
  if (teamLeaderSearchTimer.value) {
    clearTimeout(teamLeaderSearchTimer.value);
  }

  // 设置新的定时器，防抖处理（300ms）
  teamLeaderSearchTimer.value = setTimeout(() => {
    filterQuickUserList(searchText);
  }, 300);
}

/** 过滤快速检索用户列表 */
const filterQuickUserList = (keyword) => {
  if (!allUserList.value.length) {
    loadQuickTeamLeaderList();
    return;
  }

  const lowerKeyword = keyword.toLowerCase();
  quickTeamLeaderList.value = allUserList.value.filter(item =>
    (item.nickName && item.nickName.toLowerCase().includes(lowerKeyword))
  );
}

/** 加载快速检索工作负责人列表 */
const loadQuickTeamLeaderList = async () => {
  // 如果已有所有用户数据，且是同一个维保中心，直接使用
  if (allUserList.value.length > 0) {
    quickTeamLeaderList.value = allUserList.value;
    return;
  }

  // 记录当前维保中心ID
  const currentForm = acceptRepairDialogVisible.value ? acceptRepairForm.value : acceptWorkForm.value;
  // 确保currentForm存在且有gxtCenterId属性
  if (currentForm && currentForm.gxtCenterId) {
    lastLoadedCenterId.value = currentForm.gxtCenterId;
  }

  teamLeaderLoading.value = true;
  try {
    // 加载当前部门下的用户列表
    const response = await listLeader({
      deptId: -1, // 通过后台配置部门
      status: '0'
    });
    allUserList.value = response.data || [];
    quickTeamLeaderList.value = allUserList.value;
  } catch (error) {
    console.error('加载工作负责人列表失败:', error);
    allUserList.value = [];
  } finally {
    teamLeaderLoading.value = false;
  }
}

// 快速选择工作负责人
const handleTeamLeaderQuickSelect = (item) => {
  if (acceptRepairDialogVisible.value && acceptRepairForm.value) {
    acceptRepairForm.value.teamLeaderId = item.userId;
    acceptRepairForm.value.teamLeaderName = item.nickName;
  } else if (acceptWorkDialogVisible.value && acceptWorkForm.value) {
    acceptWorkForm.value.teamLeaderId = item.userId;
    acceptWorkForm.value.teamLeaderName = item.nickName;
  }
  showTeamLeaderQuickSelect.value = false;
}

// 清空工作负责人
const handleTeamLeaderClear = () => {
  if (acceptRepairDialogVisible.value && acceptRepairForm.value) {
    acceptRepairForm.value.teamLeaderId = undefined;
    acceptRepairForm.value.teamLeaderName = '';
  } else if (acceptWorkDialogVisible.value && acceptWorkForm.value) {
    acceptWorkForm.value.teamLeaderId = undefined;
    acceptWorkForm.value.teamLeaderName = '';
  }
  quickTeamLeaderList.value = [];
  showTeamLeaderQuickSelect.value = false;
}

/** MIS工单编码输入框获取焦点 */
const handleMisNoInputFocus = () => {
  showMisNoQuickSelect.value = true;
  debugger
  // 如果已有输入内容，立即搜索
  if ((finalizeRepairForm.value && finalizeRepairForm.value.misOrderNo && finalizeRepairForm.value.misOrderNo.trim()) ||
      (assignWorkForm.value && assignWorkForm.value.misNo && assignWorkForm.value.misNo.trim())) {
    const currentForm = finalizeRepairDialogVisible.value ? finalizeRepairForm.value : assignWorkForm.value;
    handleMisNoInput(currentForm.misOrderNo || currentForm.misNo);
  } else {
    // 如果没有输入内容，加载默认列表
    loadQuickMisNoList();
  }
}

// MIS工单编码输入框失去焦点
const handleMisNoInputBlur = () => {
  // 延迟隐藏下拉框，确保点击选项能触发
  setTimeout(() => {
    showMisNoQuickSelect.value = false;
  }, 200);
}

// MIS工单编码输入事件 - 实时搜索
const handleMisNoInput = (value) => {
  const searchText = value.trim();

  if (!searchText) {
    quickMisNoList.value = [];
    showMisNoQuickSelect.value = false;
    return;
  }

  showMisNoQuickSelect.value = true;

  // 清除之前的定时器
  if (misNoSearchTimer.value) {
    clearTimeout(misNoSearchTimer.value);
  }

  // 设置新的定时器，防抖处理（300ms）
  misNoSearchTimer.value = setTimeout(() => {
    // filterQuickMisNoList(searchText);
    loadQuickMisNoList(searchText)
  }, 300);
}

/** 过滤快速检索MIS工单列表 */
const filterQuickMisNoList = (keyword) => {
  if (!allMisNoList.value.length) {
    loadQuickMisNoList(keyword);
    return;
  }
  debugger
  const lowerKeyword = keyword.toLowerCase();
  quickMisNoList.value = allMisNoList.value.filter(item =>
      (item.misNo && item.misNo.toLowerCase().includes(lowerKeyword))
  );
}

/** 加载快速检索MIS工单列表 */
const loadQuickMisNoList = async (keyword) => {
  // // 如果已有所有MIS工单数据，直接使用
  // if (allMisNoList.value.length > 0) {
  //   quickMisNoList.value = allMisNoList.value;
  //   return;
  // }
  if (!keyword) {
    quickMisNoList.value = []
    return
  }

  misNoLoading.value = true;
  try {
    // 加载MIS工单列表
    const response = await listMisInfo({
      pageNum: 1,
      // pageSize: 100
      misNo: keyword,
      pcsDeviceName: keyword,
      pcsStationName: keyword
    });
    debugger
    // allMisNoList.value = response.rows || [];
    // quickMisNoList.value = allMisNoList.value;

    quickMisNoList.value = response.rows || []
    // 如果没有找到结果，可以尝试更宽松的搜索
    if (quickMisNoList.value.length === 0 && keyword.length >= 2) {
      // 可以尝试只按MIS工单编码搜索
      const retryResponse = await listMisInfo({
        pageNum: 1,
        // pageSize: 10,
        misNo: keyword
      })
      quickMisNoList.value = retryResponse.rows || []
    }
  } catch (error) {
    console.error('加载MIS工单列表失败:', error);
    allMisNoList.value = [];
  } finally {
    misNoLoading.value = false;
  }
}

// 快速选择MIS工单
const handleMisNoQuickSelect = (item) => {
  onMisInfoSelected(item);
  showMisNoQuickSelect.value = false;
}

// 清空MIS工单编码
const handleMisNoClear = () => {
  // 清空与MIS工单相关的字段
  if (finalizeRepairDialogVisible.value && finalizeRepairForm.value) {
    finalizeRepairForm.value.misOrderNo = undefined;
    finalizeRepairForm.value.realStartTime = undefined;
    finalizeRepairForm.value.realEndTime = undefined;
    finalizeRepairForm.value.workGroupMemberName = undefined;
    finalizeRepairForm.value.repairOrderPersonList = [];
  } else if (assignWorkDialogVisible.value && assignWorkForm.value) {
    assignWorkForm.value.misNo = null;
    assignWorkForm.value.content = null;
  }
  quickMisNoList.value = [];
  showMisNoQuickSelect.value = false;
}

const disabledDate = (time) => {
  return time.getTime() > Date.now();
};

const disabledTime = (date) => {
  const now = new Date();
  if (date && date.toDateString() === now.toDateString()) {
    const currentHour = now.getHours();
    const currentMinute = now.getMinutes();

    const disabledHours = () => {
      const hours = [];
      for (let i = currentHour + 1; i < 24; i++) {
        hours.push(i);
      }
      return hours;
    };

    const disabledMinutes = (hour) => {
      if (hour === currentHour) {
        const minutes = [];
        for (let i = currentMinute + 1; i < 60; i++) {
          minutes.push(i);
        }
        return minutes;
      }
      return [];
    };

    return {
      disabledHours,
      disabledMinutes
    };
  };
  return {};
};

// 打开设备选择对话框
function handleSelectMisInfo() {
  misInfoSelectVisible.value = true;
}

// 设备MIS信息回调
function onMisInfoSelected(row) {
  if (row) {
    listRepairOrder({pageNum: 1, pageSize: 10, misOrderNo: row.misNo }).then(response => {
      const  gxtOrders= response.rows
      if (gxtOrders.length > 0) {
        proxy.$modal.msgWarning('选择工单已存在！请重新选择！')
        return
      }
      // 使用展开运算符创建新对象以确保响应式更新
      finalizeFormData.value = {
        ...finalizeFormData.value,
        misOrderNo: row.misNo,
        realStartTime: row.realStartTime,
        realEndTime: row.realEndTime
      };
      // finalizeFormData.value.content = row.content
      // 使用从属性传入的listWorkPerson方法
      if (typeof listWorkPerson === 'function') {
        listWorkPerson({ misNo: row.misNo }).then(response => {
          debugger
          const updatedData = {
            ...finalizeFormData.value,
            repairOrderPersonList: response.rows
          };
          if (response.rows) {
            const nickNames = response.rows
                .map(person => person.nickName)
                .join(',');
            updatedData.workGroupMemberName = nickNames
          }
          finalizeFormData.value = updatedData;
        })
      }
      misInfoSelectVisible.value = false
    })
  }
}

// 维修方式变化处理
function handleRepairMethodChange(value) {
  // 如果切换到正常维修(1)，清除复位方式
  if (value === '1') {
    finalizeRepairForm.value.resetMethod = undefined;
  }
  // 如果切换到复位启机(2)，清除MIS相关字段
  else if (value === '2') {
    finalizeRepairForm.value.misOrderNo = undefined;
    finalizeRepairForm.value.realStartTime = undefined;
    finalizeRepairForm.value.realEndTime = undefined;
  }
}

// 处理复运
function handleRestart(row) {
  getOrderInfo(row.orderType, row.id).then(response => {
    if (row.orderType === 1) {
      // 维修工单
      restartRepairForm.value = response.data;
      restartRepairDialogVisible.value = true;
    } else {
      // 维保工单
      restartWorkForm.value = response.data;
      restartWorkDialogVisible.value = true;
    }
  });
}

// 提交维修工单复运
async function submitRestartRepair() {
  proxy.$refs["restartRepairFormRef"].validate(async valid => {
    if (valid) {
      // 判断 restartTime 是否小于 realEndTime
      if (new Date(restartRepairForm.value.restartTime) < new Date(restartRepairForm.value.realEndTime)) {
        // 如果是，弹出确认对话框
        const confirmResult = await proxy.$confirm('复运时间早于实际结束时间，是否继续？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(() => {
          // 如果用户点击了取消按钮，这里会捕获到错误并返回
          return false;
        });

        // 如果用户点击了取消按钮，终止操作
        if (!confirmResult) {
          return;
        }
      }
      restartRepairOrder(restartRepairForm.value).then(response => {
        proxy.$modal.msgSuccess("复运成功");
        restartRepairDialogVisible.value = false;
        getList();
      }).catch(error => {
        proxy.$modal.msgError("复运失败: " + error.message);
      });
    }
  });
}

// 提交维保工单复运
async function submitRestartWork() {
  proxy.$refs["restartWorkFormRef"].validate(async valid => {
    if (valid) {
      // 判断 restartTime 是否小于 realEndTime
      if (new Date(restartWorkForm.value.restartTime) < new Date(restartWorkForm.value.realEndTime)) {
        // 如果是，弹出确认对话框
        const confirmResult = await proxy.$confirm('复运时间早于实际结束时间，是否继续？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(() => {
          // 如果用户点击了取消按钮，这里会捕获到错误并返回
          return false;
        });

        // 如果用户点击了取消按钮，终止操作
        if (!confirmResult) {
          return;
        }
      }
      restartWorkForm.value.workOrderStatus = 'restarted'
      restartWorkOrder(restartWorkForm.value).then(response => {
        restartWorkDialogVisible.value = false
        proxy.$modal.msgSuccess("复运成功")
        getList()
      }).catch(error => {
        proxy.$modal.msgError("复运失败：" + (error?.response?.data?.msg || "未知错误"))
      })
    }
  })
}

// 处理下发
function handleUpdate(row) {
  getOrderInfo(row.orderType, row.id).then(response => {
    if (row.orderType === 1) {
      // 维修工单
      assignRepairForm.value = response.data;
      assignRepairDialogVisible.value = true;
    } else {
      // 维保工单
      assignWorkForm.value = response.data;
      assignWorkDialogVisible.value = true;
    }
  });
}

/** 打开设备选择对话框 */
function handleSelectEquipment() {
  equipmentSelectVisible.value = true
}

/** 设备选择回调 */
function onEquipmentSelected(row) {
  // Determine which form we're updating based on which dialog is visible
  let targetForm = assignRepairForm;
  if (assignWorkDialogVisible.value) {
    targetForm = assignWorkForm;
  }

  if (row) {
    // 检查维保中心ID和场站ID是否存在
    if (!row.maintenanceCenterId) {
      proxy.$modal.msgError("该设备的维保中心没有对应的部门，请完善部门信息后再更新设备数据！");
      return;
    }
    if (!row.stationId) {
      proxy.$modal.msgError("该设备的场站没有对应的部门，请完善部门信息后再更新设备数据！");
      return;
    }
    targetForm.value.pcsDeviceId = row.equipmentId
    targetForm.value.pcsDeviceName = row.equipmentCode
    targetForm.value.gxtCenterId = row.maintenanceCenterId
    targetForm.value.gxtCenter = row.maintenanceCenter
    targetForm.value.pcsStationId = row.stationId
    targetForm.value.pcsStationName = row.station
    targetForm.value.brand = row.brand
    targetForm.value.model = row.model
  }
  equipmentSelectVisible.value = false
}

/** 保存并下发维修工单 */
function submitFormAndIssue() {
  proxy.$refs["repairOrderRef"].validate(valid => {
    if (valid) {
      // 设置状态为待接单
      assignRepairForm.value.workOrderStatus = "assigned"
      updateRepairOrder(assignRepairForm.value).then(response => {
        proxy.$modal.msgSuccess("下发成功")
        assignRepairDialogVisible.value = false
        getList()
      })
    }
  })
}

/** 保存并下发维保工单 */
function submitWorkFormAndIssue() {
  proxy.$refs["workOrderRef"].validate(valid => {
    if (valid) {
      // 设置状态为待接单
      assignWorkForm.value.workOrderStatus = "assigned"
      updateGxtOrder(assignWorkForm.value).then(response => {
        proxy.$modal.msgSuccess("下发成功")
        assignWorkDialogVisible.value = false
        getList()
      })
    }
  })
}

const handleInfoEntryChange = (val) => {
  // 选中2工作票编号时修改其他值
  if (val === '2') {
    finalizeRepairForm.value.misOrderNo = undefined;
    finalizeRepairForm.value.realStartTime = undefined;
    finalizeRepairForm.value.realEndTime = undefined;
    finalizeRepairForm.value.workGroupMemberName = undefined;
    finalizeRepairForm.value.repairOrderPersonList = [];
  } else {
    finalizeRepairForm.value.workPermitNum = undefined;
  }
};

// 复启操作
function handleReset(row) {
  getOrderInfo(row.orderType, row.id).then(response => {
    // 使用新的组件方式
    resetFormData.value = { ...response.data }
    resetDialogVisible.value = true
  })
}

// 在提交复启成功后的回调函数
function handleResetSuccess() {
  resetDialogVisible.value = false
  getList()
}

// 用于传递给复启组件的提交方法
async function submitResetFromParent(data) {
  await finalizeRepairOrder(data)
}

// 计算属性：双向绑定代理
const workPermitNumProxy = computed({
  get() {
    return finalizeRepairForm.value.workPermitNum
  },
  set(val) {
    // 1. 去掉首尾空格
    let trimmed = val.trim()

    // 2. 只保留允许的字符：中文、英文字母、数字、下划线
    // 如果你希望更宽松（比如允许横杠 -），可调整正则
    trimmed = trimmed.replace(/[^a-zA-Z0-9_\-\.]/g, '')

    // 3. 截断到 20 个字符（按字符数，不是字节）
    if (trimmed.length > 20) {
      trimmed = trimmed.substring(0, 20)
    }

    // 4. 写回表单
    finalizeRepairForm.value.workPermitNum = trimmed
  }
})

const disabledStartDate = (time) => {
  const getYYYYMMDD = (date) => {
    const y = date.getFullYear();
    const m = String(date.getMonth() + 1).padStart(2, '0');
    const d = String(date.getDate()).padStart(2, '0');
    return `${y}-${m}-${d}`;
  };
  const today = getYYYYMMDD(new Date());
  let acceptDateStr = null;
  const acceptStr = finalizeRepairForm.value.acceptTime; // 脚本中用 .value
  if (acceptStr) {
    // 假设 acceptTime 格式是 "2025-12-09 18:01"，取前面日期部分
    acceptDateStr = acceptStr.split(' ')[0]; // 得到 "2025-12-09"
  }
  const selectedDateStr = getYYYYMMDD(time);
  // 如果没有 acceptTime，只禁用未来日期
  if (!acceptDateStr) {
    return selectedDateStr > today;
  }
  // 禁用：早于 acceptDate 或 晚于今天
  return selectedDateStr < acceptDateStr || selectedDateStr > today;
};

const disabledEndDate = (time) => {
  const getYYYYMMDD = (date) => {
    const y = date.getFullYear();
    const m = String(date.getMonth() + 1).padStart(2, '0');
    const d = String(date.getDate()).padStart(2, '0');
    return `${y}-${m}-${d}`;
  };
  const today = getYYYYMMDD(new Date());
  let acceptDateStr = null;
  const acceptStr = finalizeRepairForm.value.acceptTime; // 脚本中用 .value
  const startStr = finalizeRepairForm.value.realStartTime;
  if (startStr) {
    // 假设 acceptTime 格式是 "2025-12-09 18:01"，取前面日期部分
    acceptDateStr = startStr.split(' ')[0]; // 得到 "2025-12-09"
  } else if(acceptStr) {
    acceptDateStr = acceptStr.split(' ')[0];
  }
  const selectedDateStr = getYYYYMMDD(time);
  // 如果没有 acceptTime，只禁用未来日期
  if (!acceptDateStr) {
    return selectedDateStr > today;
  }
  // 禁用：早于 acceptDate 或 晚于今天
  return selectedDateStr < acceptDateStr || selectedDateStr > today;
};

// 添加响应式数据用于结单组件
const finalizeFormData = ref({})

/** 结单操作 */
function handleRepairOrderFinalize(row) {
  getRepairOrder(row.id).then(response => {
    finalizeFormData.value = { ...response.data, selectedMembers: [] }
    debugger
    finalizeFormData.value.repairMethod = '1';
    finalizeFormData.value.infoEntry = '1'
    finalizeDialogVisible.value = true
    commonKey++
  })
}

// 在提交结单成功后的回调函数
function handleFinalizeSuccess() {
  finalizeDialogVisible.value = false
  getList()
}

// 用于传递给结单组件的提交方法
async function submitFinalizeFromParent(data) {
  await finalizeRepairOrder(data)
}

/** 退回 */
function handleReturn(row) {
  getRepairOrder(row.id).then(response => {
    returnForm.value = response.data
    if (row.workOrderStatus != 'return') {
      returnForm.value.returnType = undefined
      returnForm.value.returnReason = undefined
    }
    returnDialogVisible.value = true
  })
}

// 用于传递给退回组件的提交方法
async function submitReturnFromParent(data) {
  await returnRepairOrder(data)
}

// 在提交退回成功后的回调函数
function handleReturnSuccess() {
  returnDialogVisible.value = false
  getList()
}

/** 待结单状态：结单按钮 */
function handleFinish(row) {
  getGxtOrder(row.id).then(response => {
    finishForm.value = response.data
    finishForm.value.orderId = row.id
    if (finishForm.value.infoEntry != null && finishForm.value.infoEntry == '1') {
      if (row.misNo != null) {
        listMisInfo({misNo: row.misNo}).then(response => {
          const misInfo = response.rows
          debugger
          if (misInfo.length > 0) {
            finishForm.value.realStartTime = misInfo[0].realStartTime
            finishForm.value.realEndTime = misInfo[0].realEndTime
          }
        })
      }
      listWorkPerson({misNo: row.misNo}).then(response => {
        finishForm.value.workOrderPersonList = response.rows;
        if (finishForm.value.workOrderPersonList) {
          const nickNames = finishForm.value.workOrderPersonList
              .map(person => person.nickName)
              .join(',');
          finishForm.value.workGroupMemberName = nickNames
          finishDialogVisible.value = true
        }
      })
    } else {
      finishForm.value.realStartTime = null
      finishForm.value.realEndTime = null
      finishDialogVisible.value = true
    }
    // 打开对话框后重置表单验证错误
    proxy.$nextTick(() => {
      proxy.$refs["finishRef"]?.clearValidate()
    })
  })
}

/** 保存结单工单 */
function saveFinishWorkOrder() {
  // if (!finishForm.value.realEndTime) {
  //   proxy.$modal.msgError("该工单未结束，无法结单！")
  //   return
  // }
  finishForm.value.workOrderStatus = 'completed'
  completeWorkOrder(finishForm.value.orderId, finishForm.value).then(response => {
    finishDialogVisible.value = false
    // 清空附件列表
    finishForm.value.attachmentUrls = undefined
    // proxy.$modal.msgSuccess("结单成功")
    getList()
  }).catch(error => {
    console.log("操作失败: " + error.message)
  })
}

// 用于传递给结单组件的提交方法
async function submitFinishFromParent(data) {
  finishForm.value = data
  await saveFinishWorkOrder()
}

// 在提交结单成功后的回调函数
function handleFinishSuccess() {
  finishDialogVisible.value = false
  getList()
}

/** 挂起维修工单 */
function handleRepairSuspend(row) {
  debugger
  suspendForm.value = row
  suspendForm.value.suspendReason = undefined
  suspendRepairDialogVisible.value = true
  proxy.resetForm("suspendFormRef")
}

// 用于传递给退回组件的提交方法
async function submitSuspendFromParent(data) {
  if (data.orderType == '1') {
    await suspendRepairOrder(data)
  }
  if (data.orderType == '2') {
    await suspendWorkOrder(data.id, data)
  }
}

// 在提交退回成功后的回调函数
function handleSuspendSuccess() {
  suspendRepairDialogVisible.value = false
  suspendDialogVisible.value = false
  getList()
}

/** 维保挂起 */
function handleSuspend(row) {
  getGxtOrder(row.id).then(response => {
    suspendForm.value = response.data
    suspendForm.value.orderId = row.id
    suspendDialogVisible.value = true
    // 打开对话框后重置表单验证错误
    proxy.resetForm("suspendFormRef")
  })
}

// 在提交审批成功后的回调函数
async function submitApproveFromParent(data) {
  if (data.orderType == '1') {
    await approveSuspendRepairOrder(data)
  }
  if (data.orderType == '2') {
    await approveWorkOrder(data.id, data)
  }
}

// 在提交审批成功后的回调函数
function handleApproveSuccess() {
  approveRepairDialogVisible.value = false
  approveWorkDialogVisible.value = false
  getList()
}
</script>

<style scoped>
/* 表单字段间距调整 */
.el-form-item {
  margin-bottom: 18px;
}

.text-gray-500 {
  color: #6b7280;
}

.card-header {
  font-weight: bold;
  font-size: 16px;
}

.info-section {
  padding: 16px 0;
  height: 100%;
  box-sizing: border-box;
}

.section-title {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.info-content {
  height: calc(100% - 30px);
  overflow-y: auto;
  overflow-x: hidden; /* 防止横向滚动 */
  padding: 0 10px; /* 添加内边距防止内容贴边 */
}

.info-item {
  margin-bottom: 12px;
}

.info-item label {
  display: block;
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

.info-item p {
  font-size: 14px;
  color: #333;
  margin: 0;
  line-height: 1.4;
}

.flow-history {
  height: 100%;
  padding: 0 10px; /* 添加内边距防止内容贴边 */
}

.flow-history .el-timeline {
  margin-left: 0;
  padding-left: 0;
}

.flow-item {
  /*padding: 10px;
  border-radius: 4px;*/
}

.flow-item h4 {
  margin: 0 0 5px 0;
  font-size: 14px;
  font-weight: bold;
}

.flow-item p {
  margin: 0;
  font-size: 12px;
  line-height: 1.4;
  color: #606266;
}

/* 修复对话框底部按钮点击区域问题 */
:deep(.el-dialog__footer) {
  padding: 20px !important;
  position: relative;
  z-index: 10;
}

/* 确保关闭按钮有完整的点击区域 */
.dialog-footer :deep(.el-button) {
  padding: 12px 20px;
  min-width: 80px;
  z-index: 20;
  position: relative;
}

/* 表单字段间距调整 */
:deep(.el-form-item) {
  margin-bottom: 18px;
}

.content-text {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.5;
}

/* 快速检索下拉框样式 */
.quick-select-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  z-index: 1000;
  max-height: 200px;
  overflow-y: auto;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 6px 0;
}

.quick-select-dropdown .quick-select-item {
  padding: 8px 12px;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
}

.quick-select-dropdown .quick-select-item:hover {
  background-color: #f5f7fa;
}

.quick-select-dropdown .user-name {
  font-size: 14px;
  color: #606266;
}

.quick-select-dropdown.no-data {
  text-align: center;
  padding: 12px;
  color: #909399;
  font-size: 14px;
}

/* 表单字段间距调整 */
:deep(.el-form-item) {
  margin-bottom: 18px;
}

/* 表单中的列间距调整 */
:deep(.el-col) {
  padding-left: 5px;
  padding-right: 5px;
}

/* 表单行间距调整 */
:deep(.el-row) {
  margin-left: -5px;
  margin-right: -5px;
}

/* 穿透修改组件内部输入框的对齐方式（关键） */
:deep(.input-number-left .el-input__inner) {
  text-align: left !important; /* !important 覆盖组件默认的居中 */
}
</style>
